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.
Getting HttpSession Object in Spring Controller is very easy . Just Put it as a method parameter in controller method and Spring will automatically inject it . There is another approach where we create Session scoped Controller . This Controller get created for each session and controller object is stored in session.
@SessionAttribute annotation retrieve the existing attribute from the session. This annotation allows you to tell Spring which of your model attributes will also be copied to HttpSession before rendering the view.
The Session object is created and made available through the context variable, $session . You do not need to perform any explicit call to create it. You can get a Session object by using the following syntax, if you already have a valid Entity object: $session=$entity->GetSession();
@Component @Scope("session") public class Cart { .. }
and then
@Inject private Cart cart;
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); }
If you are injecting the shopping cart directly into your controller, the issue is likely happening because your controller is singleton scoped (by default), which is wider scope than the bean you're injecting. This excellent article gives an overview of four approaches to exactly what you're trying to do: http://richardchesterwood.blogspot.co.uk/2011/03/using-sessions-in-spring-mvc-including.html.
Here's a quick summary of solutions:
@scope("session")
on controller level) and just have a shopping cart instance in the controller.<aop:scoped-proxy/>
. All of the methods have their pros and cons. I usually go with option 2 or 4. Option 4 is actually pretty simple and is the only approach I have seen documented by Spring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With