Model attributes

Common web forms contain a number of drop-down values--the list of states, the list of countries, and so on. These lists of values need to be available in the model so that the view can display the list. Such common things are typically populated into the model using methods that are marked with @ModelAttribute annotations.

There are two variations possible. In the following example, the method returns the object that needs to be put into the model:

    @ModelAttribute 
public List<State> populateStateList() {
return stateService.findStates();
}

The approach in this example is used to add multiple attributes to the model:

    @ModelAttribute 
public void populateStateAndCountryList() {
model.addAttribute(stateService.findStates());
model.addAttribute(countryService.findCountries());
}

An important thing to note is that there is no limitation to the number of methods that can be marked with the @ModelAttribute annotation.

Model attributes can be made common across multiple controllers using Controller Advice. We will discuss Controller Advice later in this section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset