Question

I am trying to learn Spring MVC recently. It seems that i did not understand well the functionality of @SessionAttributes and @ModelAttribute annotations.

This is a part of my controller:

@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 + 2;
    }

    return new ModelAndView(new RedirectView("showAllItems"));
}

Basically there is a jsp listing all the items. Wenn user click "addToCart" for a specific item, this item will be added to the shoppingCart list. I better explain my understanding of this controller first and you can tell me what i do not get.

First time when the ItemController is called, the createShoppingCart and createCount methods will be executed and the return parameters will be saved in session under names "shoppingCart" and "count". When the user calls the url ".../addToCart/1", addToCart method will be called. Since i need there in the method signature 2 values from session, the controller will look in the session whether the values are already there. Yes they are.. At this time shoppingCart is an empty list, and count is 0. In the method body, the selected item will be added to list, count will be 2. The jsp will be displayed again.

The problem is, jsp can see that the list shoppingCart is now not empty. but the count is still 0. When i add Items to basket, I can see on jsp that the shoppingCart is filled with items, but the value of count is always 0.

Actually there is no any difference between shoppingCart and count objects.. i dont get it why it behaves like this. I first doubted that the count type was primitive int, then i changed it to Integer typ, still the problem is not solved.

Était-ce utile?

La solution

You don't change count (You can't in fact), you assign to it. So the model still points to the old value. You would have to add the new value manually.

myModelAndView.add("count", count);

But why bothering with count if you can use warenkorb.size anyway?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top