安装

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

使用

方法一

1
2
3
4
5
6
7
8
9
10
11
12
@GetMapping("/test")
public ModelAndView test()
{
ModelAndView view = new ModelAndView();
// 对应 \src\main\resources\templates\index.html
view.setViewName("index");
// 设置属性
view.addObject("title", "测试页面");
view.addObject("desc", "这里测试 Thymeleaf 模板引擎");

return view;
}

方案二

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@GetMapping("/test2")
public HashMap test2(HttpServletRequest servletRequest)
{
servletRequest.setAttribute("title", "测试页面");
servletRequest.setAttribute("desc", "这里测试 Thymeleaf 模板引擎");

HashMap author = new HashMap<>();
author.put("name", "哲哲");
author.put("age", 25);

servletRequest.setAttribute("author", author);

return author;
}

模板文件

位置 \src\main\resources\templates\index.html

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html> 
<html lang="en">
<head>
<meta charset="UTF-8" />
<title th:text="${title}"></title>
</head>
<body>
<h1 th:text="${title}"></h1>
<p th:text="${desc}"></p>
</body>
</html>

访问