Spring boot uses ModelAndView to pass parameters to Thymeleaf template

    Recently, I was debugging an example of Spring Boot passing parameters to Thymeleaf template, but I stepped on a lot of pits. Here is the detailed process for your reference.

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

Important documents

Description

pom.xml

Introduced the dependency packages used by the project, especially the Thymeleaf dependency package

SpringBootApp.java

Start class

Controller.java

Controller class, in which through ModelAndView object and front-end Thymeleaf interaction

Application.properties

Configuration file, which contains the relevant configuration of Thymeleaf

hello.html

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 to include the dependency package of this project in pom.xml. The key code is as follows. Among them, the dependency package of the 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 shown below.        

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 on line 8, an object of type ModelAndView is first created on line 9, and the view in the object is designated as "hello" through the constructor, and then the code on line 10 is used in the Model of the object Here, in the form of key-value pairs, data whose key is name and value is Tom is added. Taken together, the welcome method will return a key-value pair data to the hello view.

    The fourth step is to write the relevant parameters of the thymeleaf template in application.properties . The specific code is as follows.    

1	#启用thymeleaf视图
2	spring.thymeleaf.enabled=true
3	#设置Content-Type值
4	spring.thymeleaf.content-type=text/html
5	## 检查模板是否存在,然后再呈现
6	spring.thymeleaf.check-template-location=true
7	# 不启用缓存
8	spring.thymeleaf.cache=false
9	# 构建前缀
10	spring.thymeleaf.prefix=classpath:/templates/
11	# 构建后缀
12	spring.thymeleaf.suffix=.html

    There are notes in front of the corresponding parameter items, you can read it yourself, but here are the following two major points of attention.

  1. In order to use the thymeleaf view, the parameters shown in line 2 must be configured.
  2. The prefixes and suffixes defined in lines 10 and 12 will be used in conjunction with the views in the ModelAndView object. For example, in Controller.java, the view returned in ModelAndView is hello, so the prefix and 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 which the final jump will be made. .

    In the fifth step, you need to write a hello.html page containing the thymeleaf template. The code is shown below.    

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>

    Among them, in the second line, the namespace of the th tag to be used in the eighth line is specified, which is from the thymeleaf template.

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

  1. In this example, the thymeleaf template is embedded in the HTML5 code. When using it, you need to introduce the namespace of the template attribute element as shown in line 2.
  2. In front-end pages such as html5, you can use thymeleaf syntax to set placeholders for parameters as in line 8, so that when the back-end passes parameters through ModelAndView and other forms, they can be in the place where the placeholders are. Dynamic display.

    After completing the development, start the project, and as shown in the @RequestMapping annotation before the welcome method in the controller, enter http://localhost:8080/welcome in the browser, and you can see the output "Welcome:Tom". And from initiating a request to displaying data, the main process is as follows.

  1. According to the definition of @RequestMapping annotation, http://localhost:8080/welcome request is processed by welcome method.
  2. In the welcome method, the return view is set to hello, and the value of the name parameter is set to Tom.
  3. According to the configuration in application.properties, the view page to be returned will be determined according to the configured prefix and suffix. Here is the hello.html in the templates directory under the resources (because the directory is in the classpath of this project).
  4. Eventually, hello.html will be displayed, as defined in the thymeleaf template, and the word "Tom" will be displayed in the place where the name parameter placeholder is located. This shows the results that everyone finally saw.

Guess you like

Origin blog.csdn.net/sxeric/article/details/113913717