title: Spring MVC - difference between HttpSession.setAttribute and model.addObject
body: <p>I am trying to learn Spring MVC recently. It seems that i did not understand well the functionalities of @ModelAttribute annotation and HttpSession.</p>
  
  <pre><code>@SessionAttributes({"shoppingCart", "count"})
  public class ItemController {
  
  @ModelAttribute("shoppingCart")
  public List&lt;Item&gt; createShoppingCart() {
      return new ArrayList&lt;Item&gt;();
  }
  
  @ModelAttribute("count")
  public Integer createCount() {
      return 0;
  }
  
  @RequestMapping(value="/addToCart/{itemId}", method=RequestMethod.GET)
  public ModelAndView addToCart(@PathVariable("itemId") Item item, 
          @ModelAttribute("shoppingCart") List&lt;Item&gt; shoppingCart, @ModelAttribute("count") Integer count) {
  
      if(item != null) {
          shoppingCart.add(item);
          count = count + 1;
      }
  
      return new ModelAndView(new RedirectView("showAllItems")).addObject("count", count);
  }
  
  @RequestMapping(value="/deleteFromCart/{itemId}", method=RequestMethod.GET)
  public ModelAndView deleteFromCart(@PathVariable("itemId") Item item, 
          HttpSession session) {
  
      List&lt;Item&gt; list = (List&lt;Item&gt;) session.getAttribute("shoppingCart");
      list.remove(item);
      //session.setAttribute("shoppingCart", list);
  
      Integer count = (Integer) session.getAttribute("count");
      count = count - 1;
      session.setAttribute("count", count);
  
      return new ModelAndView(new RedirectView("showAllItems"));
  }
  </code></pre>
  
  <p>ShoppingCart and count are the session attributes.</p>
  
  <p>The problem is in the deleteFromCart method. I get the <strong>count</strong> from session, <strong>reassign</strong> it and <strong>overwrite</strong> it in session. But i <strong>cant see the updated value</strong> of count on jsp. However, the updated shoppingCart object can be seen updated, although i do not overwrite the session object (since the object is the same object which is already in session).</p>
  
  <p>But why is the count not updated, although i overwrite it with session.setAttribute?
  When i add the new count object to the model (model.addObject("count", count)) then i can see the updated value of count. But why does not session.setAttribute give the same result?</p>