Model, ModelMap, and ModelAndView in Spring MVC

1. Overview

In this article, we’ll look at the use of the core org.springframework.ui.Modelorg.springframework.ui.ModelMap and org.springframework.web.servlet.ModelAndView provided by Spring MVC.

2. Maven Dependencies

Let’s start with the spring-context dependency in our pom.xml file:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>

The latest version of spring-context dependency can be found here.

For the ModelAndView, the spring-web dependency is required:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>

The latest versions of spring-web dependency can be found here.

And, if we use Thymeleaf as our view, we should add this dependency to pom.xml:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>

The latest version of Thymeleaf dependency can be found here.

3. Model

Let’s start with the most basic concept here – the Model.

Simply put, the model can supply attributes used for rendering views.

To provide a view with usable data, we simply add this data to its Model object. Additionally, maps with attributes can be merged with Model instances:

@GetMapping("/showViewPage")
public String passParametersWithModel(Model model) {
    Map<String, String> map = new HashMap<>();
    map.put("spring", "mvc");
    model.addAttribute("message", "VietMX");
    model.mergeAttributes(map);
    return "viewPage";
}

4. ModelMap

Just like the Model interface above, ModelMap is also used to pass values to render a view.

The advantage of ModelMap is it gives us the ability to pass a collection of values and treat these values as if they were within a Map:

@GetMapping("/printViewPage")
public String passParametersWithModelMap(ModelMap map) {
    map.addAttribute("welcomeMessage", "welcome");
    map.addAttribute("message", "VietMX");
    return "viewPage";
}

5. ModelAndView

The final interface to pass values to a view is the ModelAndView.

This interface allows us to pass all the information required by Spring MVC in one return:

@GetMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
    ModelAndView modelAndView = new ModelAndView("viewPage");
    modelAndView.addObject("message", "VietMX");
    return modelAndView;
}

6. The View

All the data, we place within these models, is used by a view – in general, a templated view to render the web page.

If we have a Thymeleaf template file targeted by our controller’s methods as their view. A parameter passed through the model will be accessible from within the thymeleaf HTML code:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Title</title>
</head>
<body>
    <div>Web Application. Passed parameter : th:text="${message}"</div>
</body>
</html>

The parameter passed here is used through the syntax ${message}, which is known as a placeholder. The Thymeleaf template engine will replace this placeholder with an actual value from an attribute of the same name passed through the model.

7. Conclusion

In this quick tutorial, we’ve discussed three core concepts in Spring MVC – the Model, the ModelMap and the ModelAndView. We also had a look at examples of how the view can make use of these values.

As always, the implementation of all these examples and code snippets can be found over on Github.

Related posts:

Composition, Aggregation, and Association in Java
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Hướng dẫn Java Design Pattern – Factory Method
An Example of Load Balancing with Zuul and Eureka
Hướng dẫn Java Design Pattern – Mediator
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Java Program to Implement Selection Sort
Java Program to Implement Gabow Algorithm
Java Program to Implement Gift Wrapping Algorithm in Two Dimensions
Java Program to Solve any Linear Equations
Lập trình đa luồng trong Java (Java Multi-threading)
Guide to Dynamic Tests in Junit 5
Phương thức tham chiếu trong Java 8 – Method References
REST Web service: Tạo ứng dụng Java RESTful Client với Jersey Client 2.x
Java Program to Implement K Way Merge Algorithm
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Java Program to Implement Pollard Rho Algorithm
A Guide to Java HashMap
Giới thiệu luồng vào ra (I/O) trong Java
StringBuilder vs StringBuffer in Java
Java Program to Implement Coppersmith Freivald’s Algorithm
Java Program to Implement Quick Sort with Given Complexity Constraint
Java Program to Implement ArrayDeque API
Check if there is mail waiting
Java Program to Implement Efficient O(log n) Fibonacci generator
Using a Mutex Object in Java
Java 14 Record Keyword
Generate Spring Boot REST Client with Swagger
JUnit 5 @Test Annotation
Creating Docker Images with Spring Boot
Guide to the Java Clock Class
Java Program to Implement Fibonacci Heap