1. Overview

In this tutorial, we'll investigate the model-related classes that Spring MVC provides. Namely, we'll look at the Model, ModelMap, Map and ModelView classes.

2. Model

Let's start with the Model interface.

We use the Model interface to pass data to our views. The implementations of this interface function as a holder of model attributes.

Spring MVC also allows us to add Model as a parameter to our controller methods so that we can access/modify the model.

@Controller
public class GreetingController {

    @RequestMapping(path = "/getWithModel", method = RequestMethod.GET)
    public String getWithModel(@RequestParam("name") String name, Model model) {
        Greeting greeting = new Greeting(name);
        model.addAttribute("greeting", greeting);

        return "greet";
    }
}

Here we're defining the /getWithModel endpoint. Notice the usage of Model as the second method parameter. Thus, Spring gives us an implementation of the Model interface at runtime. Then we're adding a Greeting object to the model under the key greeting:

public class Greeting {

    private final String name;

    // Getter method ...
}

Finally, we can access the model attribute greeting in our view - greet.html:

<!DOCTYPE html>
<html>
    <body>
        Hello <span th:text="${greeting.name}"/>!
    </body>
</html>

3. ModelMap

ModelMap is very similar in behavior to Model. It also acts as a container for model attributes and we can add ModelMap as a method parameter:

@RequestMapping(path = "/getWithModelMap", method = RequestMethod.GET)
public String getWithModelMap(@RequestParam("name") String name, ModelMap modelMap) {
    Greeting greeting = new Greeting(name);
    modelMap.addAttribute("greeting", greeting);

    return "greet";
}

4. Map

To access the model attributes, we can also declare a Map<String, Object> parameter in the controller methods.

@RequestMapping(path = "/getWithMap", method = RequestMethod.GET)
public String getWithMap(@RequestParam("name") String name, Map<String, Object> model) {
    Greeting greeting = new Greeting(name);
    model.put("greeting", greeting);

    return "greet";
}

5. ModelAndView

The ModelAndView class combines two aspects of rendering. In the previous examples, we defined the view name as the return value of the method - greet. Moreover, the model instance was given to us by Spring MVC.

In contrast, when using ModelAndView, we construct the ModelAndView object ourselves specifying the view and model:

@RequestMapping(path = "/get", method = RequestMethod.GET)
public ModelAndView get(@RequestParam("name") String name) {
    Map<String, Object> modelMap = new HashMap<>();
    Greeting greeting = new Greeting(name);
    modelMap.put("greeting", greeting);
    
    return new ModelAndView("greet", modelMap);
}

6. Summary

In this tutorial, we've looked at the different model-related classes like Model, ModelMap and ModelAndView.

Finally, check out the source code for all examples over on Github.