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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With