How to share SessionAttributes between Controllers in Spring MVC?

attributes, session, spring-mvc

Solution

In Spring MVC, @SessionAttributes are not meant to be shared accross Controllers.

What I did instead was to create an object (via a POJO) with the Session scope, that holds all the values I need to store for a Session.

I then use the JDK dynamic proxy to Autowire the object to the Controllers.

Problem

I would like to share Session Attributes betweet two Controllers in Spring MVC, using the @SessionAttributes annotation. Here is a simple code I use to test the attributes sharing : AController.java ``` @Controller @SessionAttributes("myParam") public class AController { @RequestMapping(value="/a") public String handle(Model model){ if(!model.containsAttribute("myParam")) model.addAttribute("myParam", randomInt()); return "a"; } private int randomInt(){ return new Random().nextInt(100); } } ``` a.jsp ``` <%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html> <h1>Page A</h1> <p>Param = ${myParam}</p> </html> ``` BController.java ``` @Controller @SessionAttributes("myParam") public class BController { @RequestMapping(value="/b") public String handle(Model model){ if(!model.containsAttribute("myParam")) model.addAttribute("myParam", randomInt()); return "b"; } private int randomInt(){ return new Random().nextInt(100); } } ``` b.jsp ``` <%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html> <h1>Page B</h1> <p>Param = ${myParam}</p> ``` The behaviour I expect is to go to the /a URL, myParam would be set to a random value between 0 and 99, then this value would be shared between the two controllers. However,what happens is the following: I go to the /a URL, myParam is set to a value (let's say 10). Then i go to the /b URL, myParam is set to another value (let's say 20). When I go back to the /a URL, myParam value is the one set by the BController ( myParam =20). Once the two controllers methods have been executed, the value is shared, but before, each controller redefines a new value. It seems like if a Controller has never set a value to a SessionAttribute, it does not detect that attribute if it was set by another Controller. I really would like to be able to share session attributes betwen controllers without using the HttpSession object and sticking with Spring MVC 3 objects. I would like to know if I missed something or if there are other practices to share data in a session between controllers. NB : the webapp was deployed on a Tomcat7 server.

Original source