gstackoverflow gstackoverflow - 3 months ago 32
Java Question

How to use Session attributes in Spring-mvc

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

session.setAttribute("name","value");


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

Answer

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

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

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

    then inject class in each controller that you want

       @Autowired
       private User user
    

that keep class on session.

  1. 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>
    

    then inject class in each controller that you want

    @Autowired
    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.

Comments