如何在 spring 应用程序中向会话添加属性

How to add attribute to session in spring app

我有一个在线商店的应用程序。我希望每个用户创建自己的篮子,他们可以在其中放置一些产品。之后,他可以编辑这个篮子等等。最好的方法是什么?我已经在这里问过这个问题,但没有足够的答案。我搜索了有关此问题的信息,但也找不到我需要的形式。

我目前正在使用以下方案
一旦用户访问我的网站,我就会为他创建一个购物车并像这样添加到会话中:

@GetMapping("/")
    public String sayHello(HttpSession session) {
        session.setAttribute("bucket", new ArrayList<ProductDto>());
        return "index";
    }

要将商品添加到此购物车,我使用此方法:

@GetMapping("/add/{id}")
    public String addProductToBucket(@SessionAttribute("bucket")ArrayList<ProductDto> bucket,
                                     @PathVariable("id") long id,
                                     Model model){
        bucket.add(productService.getById(id));
        return "redirect:/product";
    }

要清空我刚写的购物车

bucket.clear ();

我做的每件事都是正确的还是我需要换一种方式工作?还有一个问题。如何在会话中设置此对象的生命周期?有条件我要他住20分钟

下面带注释的代码会将“值”设置为“项目”:

@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){

   request.getSession().setAttribute("item",value);
   return "index.html";
}

如果你想在用户会话期间保留对象,有一些方法:

//directly add one attribute to the session

@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
   ShoppingCart cart = (ShoppingCart)request.getSession().setAttribute("cart",value);
   return "testJsp";
}

 //get it from the controller

ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
Make your controller session scoped


//Scope the Objects, for example, you have a user object that should be in session every time

@Component
@Scope("session")
public class User
 {
    String user;
    /*  setter getter*/
  }

//inject class in each controller that you want.

   @Autowired
   private User user

//The AOP proxy injection : in spring -xml

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">

  <bean id="user"    class="com.User" scope="session">     
      <aop:scoped-proxy/>
  </bean>
</beans>


//Pass HttpSession to method

 String index(HttpSession session) {
            session.setAttribute("mySessionAttribute", "someValue");
            return "index";
        }

//Make ModelAttribute in session By @SessionAttributes("ShoppingCart"):

  public String index (@ModelAttribute("ShoppingCart") ShoppingCart shoppingCart, SessionStatus sessionStatus) {
//Spring V4
//you can modify session status  by sessionStatus.setComplete();
}
//or you can add Model To entire Controller Class like,

@Controller
    @SessionAttributes("ShoppingCart")
    @RequestMapping("/req")
    public class MYController {

        @ModelAttribute("ShoppingCart")
        public Visitor getShopCart (....) {
            return new ShoppingCart(....); //get From DB Or Session
        }  
      }

首先,通过添加@Scope("session") 使您的控制器会话有范围。

@Controller
@Scope("session")

然后向会话添加一个属性

@RequestMapping(method = RequestMethod.GET)
public String sayHello(HttpServletRequest request){
  request.getSession().setAttribute("cart",valueOfCart);
    return "index";
}

对于会话超时,在您的 application.properties 中设置 属性 server.session.timeout= 值以秒为单位。

然后 Scope 每次都应该在会话中的用户对象

@Component
@Scope("session")
public class User
 {
    String user;
    /*getter setter*/
  }

然后在您想要的每个控制器中注入 class

@Autowired
   private User user