注:仅供个人学习和方便查阅使用,不做其余用途
一、pom文件引入thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
二、配置文件配置属性
#一般用来使用的html文件放在template文件夹中
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.encoding=UTF-8
#表示是否缓存
spring.thymeleaf.cache=false
spring.thymeleaf.suffix=.html
spring.thymeleaf.servlet.content-type=text/html
三、在目标目录中添加html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test HTML</title>
</head>
<body>
Hello World!
</body>
</html>
注:这样就可以直接通过控制器+GET方法在浏览器中访问了
@Controller
public class TestController {
@GetMapping("/verify/plugin/test")
public String testThymeleaf(){
return "AdEmailTemplate.html";
}
}
四、在页面中渲染model数据
(1)html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Test HTML</title>
</head>
<body>
Hello World!
<h1 th:text="${msg}"></h1>
<h1 th:text="${testObj.uid}"></h1>
<h1 th:text="${testObj.name}"></h1>
<h1 th:text="${testObj.age}"></h1>
<div></div>
</body>
</html>
(2)java
@GetMapping("/verify/plugin/test")
public String testThymeleaf(Model model){
model.addAttribute("msg", "welcome you!" );
Map<String,String> testObj = new HashMap<>();
testObj.put("uid","11111");
testObj.put("name","小华");
testObj.put("age","18");
model.addAttribute("testObj", testObj);
return "AdEmailTemplate.html";
}
(3)效果
五、后台获取页面(一般用于发邮件)
(1)html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Test HTML</title>
</head>
<body>
Hello World!
<h1 th:text="${uid}"></h1>
<h1 th:text="${name}"></h1>
<h1 th:text="${age}"></h1>
<div></div>
</body>
</html>
(2)java
@Resource
private TemplateEngine templateEngine;
@GetMapping("/verify/plugin/test")
public String testThymeleaf(){
Map<String,Object> testObj = new HashMap<>();
testObj.put("uid","11111");
testObj.put("name","小华");
testObj.put("age","18");
//import org.thymeleaf.context.Context;
Context context = new Context();
//定义模板数据
context.setVariables(testObj);
//获取thymeleaf的html模板
String mail = templateEngine.process("AdEmailTemplate",context);
System.out.println(mail);
return "AdEmailTemplate.html";
}
(3)效果
在控制台成功打印 (可以用于邮件发送html的方式)