This is how it all looks now:
@SessionAttributes("shoppingCart")
public class ItemController {
@ModelAttribute
public ShoppingCart createShoppingCart() {
return new ShoppingCart();
}
@RequestMapping(value=RequestMappings.ADD_TO_CART + RequestMappings.PARAM_ITEM_ID, method=RequestMethod.GET)
public String addToCart(@PathVariable("itemId") Item item, @ModelAttribute ShoppingCart shoppingCart) {
if(item != null) {
shoppingCartService.addItem(shoppingCart, item);
}
return ViewNamesHolder.SHOPPING_CART;
}
}
When the addToCart method is called first time, the shoppingCart object will be initialized by the createShoppingCart method. After the addToCart method runs, the initialized object will be added to the session and it will be used from the session for the later use. That means the createShoppingCart methode is called just once (as long as it does not removed from the session).
Why does Spring eliminate the need for the ModelAttribute annotated initializer method, by simply creating this object whenever is needed? Then it would all look simpler like this:
@SessionAttributes("shoppingCart")
public class ItemController {
@RequestMapping(value=RequestMappings.ADD_TO_CART + RequestMappings.PARAM_ITEM_ID, method=RequestMethod.GET)
public String addToCart(@PathVariable("itemId") Item item, @ModelAttribute ShoppingCart shoppingCart) {
if(item != null) {
shoppingCartService.addItem(shoppingCart, item);
}
return ViewNamesHolder.SHOPPING_CART;
}
}
Whenever the shoppingCart object will not be found in the session, it would be initialized by its default constructor.. What do you think the reason is for that decision?