Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a @ModelAttribute annotated method called precisely?

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?

like image 851
Jérôme Verstrynge Avatar asked Jul 15 '12 17:07

Jérôme Verstrynge


1 Answers

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.

like image 153
Biju Kunjummen Avatar answered Sep 30 '22 10:09

Biju Kunjummen