I am trying to learn Spring MVC recently. It seems that i did not understand well the functionalities of @ModelAttribute annotation and HttpSession.
@SessionAttributes({"shoppingCart", "count"})
public class ItemController {
@ModelAttribute("shoppingCart")
public List<Item> createShoppingCart() {
return new ArrayList<Item>();
}
@ModelAttribute("count")
public Integer createCount() {
return 0;
}
@RequestMapping(value="/addToCart/{itemId}", method=RequestMethod.GET)
public ModelAndView addToCart(@PathVariable("itemId") Item item,
@ModelAttribute("shoppingCart") List<Item> 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<Item> list = (List<Item>) 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"));
}
ShoppingCart and count are the session attributes.
The problem is in the deleteFromCart method. I get the count from session, reassign it and overwrite it in session. But i cant see the updated value 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).
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?