spring boot uses ModelAndView to pass parameters to Thymeleaf template

Recently, I was debugging an example of Spring Boot transferring parameters to Thymeleaf template, but I stepped on many pits. Here, I will record the detailed process for your reference.

First, create a Maven project named ModelAndViewDemo, and in the following table, give the description of important files.

Important documents



The dependency package used in the project is introduced, especially the dependency package of Thymeleaf


Startup class


Controller class, in which the front-end Thymeleaf interacts with the ModelAndView object


Configuration file, which contains the relevant configuration of Thymeleaf


The front-end page file containing the Thymeleaf template. Please note that it is in the templates directory of the resources directory. This directory structure needs to be consistent with the configuration in the configuration file

The first step is in POM XML contains the dependency package of this project, and the key code is as follows. Among them, the dependent package of thymeleaf template is introduced through the code from lines 6 to 9.  

1  <dependencies>
2	        <dependency>
3	            <groupId>org.springframework.boot</groupId>
4	            <artifactId>spring-boot-starter-web</artifactId>
5	        </dependency>
6	        <dependency>
7	            <groupId>org.springframework.boot</groupId>            
8	<artifactId>spring-boot-starter-thymeleaf</artifactId>
9	        </dependency>
10	    </dependencies>

The second step is to write the startup class.     

1	package prj;
2	import org.springframework.boot.SpringApplication;
3	import org.springframework.boot.autoconfigure.SpringBootApplication;
4	@SpringBootApplication
5	public class SpringBootApp {
6	    public static void main(String[] args) {
7	        SpringApplication.run(SpringBootApp.class, args);
8	    }
9	}

The third step is to write the controller class. The code is as follows.         

1	package prj.controller;
2	import org.springframework.web.bind.annotation.RequestMapping;
3	import org.springframework.web.bind.annotation.RestController;
4	import org.springframework.web.servlet.ModelAndView;
5	@RestController
6	public class Controller {
7	    @RequestMapping("/welcome")
8	    public ModelAndView welcome() {
9	        ModelAndView modelAndView = new ModelAndView("hello");
10	        modelAndView.getModel().put("name", "Tom");
11	        return modelAndView;
12	    }
13	}

In the welcome method in line 8, first create an object of ModelAndView type in line 9, and specify the view in the object as "hello" through the constructor. Then, through the code in line 10, add the data with key name and value Tom in the form of key value pair in the Model of the object. Taken together, the welcome method will return a key value pair data to the Hello view.

Step 4, in application Properties, write the relevant parameters of the thymeleaf template. The specific code is as follows.     

1	#Enable thymeleaf view
2	spring.thymeleaf.enabled=true
3	#Set content type value
4	spring.thymeleaf.content-type=text/html
5	## Check whether the template exists before rendering
6	spring.thymeleaf.check-template-location=true
7	# Do not enable caching
8	spring.thymeleaf.cache=false
9	# Build prefix
10	spring.thymeleaf.prefix=classpath:/templates/
11	# Build suffix
12	spring.thymeleaf.suffix=.html

There are notes in front of the corresponding parameter items, which you can read by yourself. However, here are the following two points for attention.

  1. To use the thymeleaf view, you must configure the parameters shown in line 2.
  2. The prefixes and suffixes defined in lines 10 and 12 will be integrated with the views in the ModelAndView object. For example, in the controller In Java, the view returned in ModelAndView is hello, so the Prefix suffix will be added accordingly. The value after the plus sign is classpath: / templates / Hello HTML, which can specify the location of the view file to jump to finally.

Step 5: you need to write a hello.html containing the thymeleaf template HTML page, the code is as follows.     

1	<!DOCTYPE html>
2	<html  lang="en" xmlns:th="http://www.thymeleaf.org">
3	<head>
4	    <meta charset="UTF-8">
5	    <title>welcome</title>
6	</head>
7	<body>
8	    Welcome:<span th:text="${name}"></span>
9	</body>
10	</html>

In line 2, the namespace of the th tag to be used in line 8 is specified, which is from the thymeleaf template.

In line 8, a placeholder for the ${name} parameter is specified in the form of th:text="${name}", and the specific name parameter value will be returned from the back end. From this page, you can see the following style features of thymeleaf template.

  1. In this example, the thymeleaf template is embedded in HTML5 code. When using it, you need to introduce the namespace of the attribute element of the template as shown in line 2.
  2. In the front-end page such as html5, you can set the placeholder of the parameter through the syntax of thymeleaf as in line 8, so that when the back-end passes the parameter through the form of ModelAndView, it can be displayed dynamically at the location of the placeholder.

After completing the development, start the project and enter it in the browser as shown in the @ RequestMapping annotation before the welcome method in the controller http://localhost:8080/welcome , you can see the output of "Welcome:Tom". From initiating the request to displaying the data, you mainly go through the following process.

  1. As defined by the @ RequestMapping annotation, http://localhost:8080/welcome The request is processed by the welcome method.
  2. In the welcome method, set the return view to hello, and set the value of the name parameter to Tom.
  3. According to application The configuration in properties will determine the view page to be returned according to the pre suffix configured. Here is hello in the templates directory under the resources directory (because the directory is in the classpath of the project) html.
  4. Will eventually show hello HTML, which is defined by the thymeleaf template, and displays the words "Tom" at the place where the name parameter placeholder is located. This shows what you finally see.

Tags: Spring Cloud

Posted by Chris 96 WS6 on Sun, 17 Apr 2022 12:07:19 +0930