gstackoverflow gstackoverflow - 1 month ago 16
Java Question

How to use Session attributes in Spring-mvc

Could you help me write spring mvc style analog of this code?


And how to add an element that is annotated by
annotation to session and then get access to it?


If you want to deleting object after each response no need to session,

If you want keep object during user session , It has some ways:

  1. directly add one attribute to session: declare HttpSession as a parameter to your controller method as aksappy said in above code

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

    and you can get it fro controller like this :

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

  3. Scope the Objects ,for example you have user object that want be in session every time:

    public class User
        String user;
        /*  setter getter*/

    then inject class in each controller that you want

       private User user

that keep class on session.

  1. The AOP proxy injection : in spring -xml:

    <beans xmlns=""
      <bean id="user"    class="com.User" scope="session">     

    then inject class in each controller that you want

    private User user

each one has advantage and disadvantage:

@session may use more memory in cloud systems it copies session to all nodes, and direct method has messy approach, it is not good to unit test.