@ModelAttribute helps a Spring MVC controller prepare data for a view and retrieve that data when handling a request. Put it on a method to add objects to the model before a request-handling method runs. Put it on a handler parameter to use an object already in the model. section 2.1.2 section 2.2
Prepare a taco design form
For GET /design, an @ModelAttribute method adds available ingredients to the Model, grouped by type. Other annotated methods create a TacoOrder and a Taco. The design view can use those objects to render a form; the TacoOrder holds the order being built across requests. section 2.1.2
Use the order on submission
For POST /design, form fields bind to a Taco parameter. The separate @ModelAttribute TacoOrder parameter uses the order previously placed in the model. The handler adds the submitted taco to that order, then redirects to /orders/current. The annotation on TacoOrder is not what binds the Taco form fields. section 2.2
Listing 2.6 Handling POST requests with @PostMapping
@PostMapping
public String processTaco(Taco taco,
@ModelAttribute TacoOrder tacoOrder) {
tacoOrder.addTaco(taco);
log.info("Processing taco: {}", taco);
return "redirect:/orders/current";
}
The handler listing shows the distinction directly: Taco receives the submitted design, while @ModelAttribute marks the TacoOrder parameter used to collect it. section 2.2
If selected ingredient values arrive as strings but Taco needs Ingredient objects, a Converter<String, Ingredient> handles that conversion. This is a separate part of form binding, not a job performed by @ModelAttribute itself. section 2.2
