title: How to share SessionAttributes between Controllers in Spring MVC?
body: <p>I would like to share Session Attributes betweet two Controllers in Spring MVC, using the @SessionAttributes annotation.</p>
  
  <p>Here is a simple code I use to test the attributes sharing :
  
  AController.java</p>
  
  <pre class="lang-java prettyprint-override"><code>@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);
  }
  
  }
  </code></pre>
  
  <p>
  a.jsp</p>
  
  <pre class="lang-jsp prettyprint-override"><code>&lt;%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %&gt;
  &lt;html&gt;
  &lt;h1&gt;Page A&lt;/h1&gt;
  &lt;p&gt;Param = ${myParam}&lt;/p&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>
  BController.java</p>
  
  <pre class="lang-java prettyprint-override"><code>@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);
  }
  
  }
  </code></pre>
  
  <p>
  b.jsp</p>
  
  <pre class="lang-jsp prettyprint-override"><code>&lt;%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %&gt;
  &lt;html&gt;
  &lt;h1&gt;Page B&lt;/h1&gt;
  &lt;p&gt;Param = ${myParam}&lt;/p&gt;
  </code></pre>
  
  <p></p>
  
  <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.</p>
  
  <p>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).</p>
  
  <p>Once the two controllers methods have been executed, the value is shared, but before, each controller redefines a new value.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>I would like to know if I missed something or if there are other practices to share data in a session between controllers.</p>
  
  <p>NB : the webapp was deployed on a Tomcat7 server.</p>