Spring store object in session

后端 未结 4 1468
醉梦人生
醉梦人生 2020-12-04 09:15

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

4条回答
  •  失恋的感觉
    2020-12-04 09:39

    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:

    1. Scope the controller to session scope (use @scope("session") on controller level) and just have a shopping cart instance in the controller.
    2. Scope the controller to request and have session-scoped shopping cart injected.
    3. Just use the session directly - kind of messy, IMO.
    4. Use Spring's annotation .

    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.

提交回复
热议问题