liveBook · Manning

@modelattribute

As explained in Spring in Action, Sixth Edition

@ModelAttribute is a Spring MVC annotation that binds request data to a model or method parameter and exposes the resulting object to a controller method.

@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

How Spring in Action, Sixth Edition covers it

How deep it goes
Shows method and parameter placement in a working controller, but does not examine annotation internals.
Examples
Uses ingredient lists and blank taco objects for a design form, then adds a submitted taco to an order.
What it assumes
Introduces the Model as the carrier between controller and view while using basic GET, POST, and Java controller methods.
What you can do after
Apply it in a Spring MVC controller to supply view data and access a previously modeled order.
How it connects
Connects Spring MVC models, controller methods, session attributes, form binding, and converters.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.