When is a @ModelAttribute annotated method called precisely?
Asked Answered
T

1

6

The following is a simple Spring form controller to handle 'add item' user requests:

@Controller
@RequestMapping("/addItem.htm")
public class AddItemFormController {

    @Autowired
    ItemService itemService;

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(ModelMap model) {
        return "addItem";
    }

    @ModelAttribute("item")
    public Item setupItem() {
        Item item = new Item();
        return item;
    }

    @RequestMapping(method = RequestMethod.POST)
    protected String addItem(@ModelAttribute("item") Item item) {
        itemService.addItem(item);
        return "itemAdded";
    }

}

I read somewhere that: (...) the @ModelAttribute is also pulling double duty by populating the model with a new instance of Item before the form is displayed and then pulling the Item from the model so that it can be given to addItem() for processing.

My question is, when and how often is setupItem() going to be called precisely? Will Spring keep a separate model copy if user requests multiple add item?

Tiga answered 15/7, 2012 at 17:12 Comment(0)
G
10

The setupItem is going to be called once per request to any of the @RequestMapping methods in this controller, right before the @RequestMapping method is called. So for your addItem method the flow will be - call the setupItem, creating a model attribute called item, since your addItem argument is also tagged with @ModelAttribute, the item is going to be enhanced with POST'ed parameters at this point.

Gabriellagabrielle answered 15/7, 2012 at 20:58 Comment(1)
Ok, so for setupForm(), an item is created and stored in the model for later display in addItem.jsp and for addItem() an item is also created, and 'stuffed' with values returned by the user, correct?Macomber

© 2022 - 2024 — McMap. All rights reserved.