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()); ...

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.