会话中的 Spring 存储对象
我想用 Spring 实现一个购物车,所以我需要在会话中保存一个对象 Cart
(它具有产品、paymentType 和 deliveryType 等属性).我试图用 bean 和属性范围"设置为会话"来创建它,但它不起作用,我应该在我的控制器或 Cart
类中使用一些额外的注释吗?任何示例用法都会非常有帮助:-) 提前致谢.
I would like to implement a shopping cart with Spring, so I need to save an object Cart
( which has attributes like products, paymentType and deliveryType ) in session. I've tried to create it with bean and attribute "scope" set to "session", but it just doesn't work, should I use some additional annotations in my controller or Cart
class? Any example usage would be really helpful :-) Thanks in advance.
@Component
@Scope("session")
public class Cart { .. }
然后
@Inject
private Cart cart;
应该可以工作,如果它是在 web 上下文 (dispatcher-servlet.xml) 中声明的.另一种选择是使用原始会话并将您的购物车对象放在那里:
should work, if it is declared in the web context (dispatcher-servlet.xml). An alternative option is to use the raw session and put your cart object there:
@RequestMapping(..)
public String someControllerMethod(HttpSession session) {
session.setAttribute(Constants.CART, new Cart());
...
Cart cart = (Cart) session.getAttribute(Constants.CART);
}