1、基本使用
在创建项目的时候要添加两个依赖
创建一个User类
package com.example.thy;
public class User {
private Integer id;
private String username;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id='" + id + ''' +
", username='" + username + ''' +
", address='" + address + ''' +
'}';
}
}
创建一个userController
package com.example.thy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
public class UserController {
@RequestMapping("/hello")
public String user(Model model){
List users =new ArrayList<>();
for (int i = 0; i <10; i++) {
User user = new User();
user.setId(i);
user.setUsername("张三"+i);
user.setAddress("山东"+i);
users.add(user);
}
model.addAttribute("users",users);
return "hello";
}
}
在src/main/resources/templates下创建一个hello.html
Title
运行结果
出现问题:
1.模版必须放在src/main/resources/templates下
2.模版中导入命名空间否则会报错
也可以在application.properties添加自己的配置
# 应用名称 spring.application.name=thy2 # THYMELEAF (ThymeleafAutoConfiguration) # 开启模板缓存(默认值: true ) spring.thymeleaf.cache=true # 检查模板是否存在,然后再呈现 spring.thymeleaf.check-template=true # 检查模板位置是否正确(默认值 :true ) spring.thymeleaf.check-template-location=true #Content-Type 的值(默认值: text/html ) spring.thymeleaf.content-type=text/html # 开启 MVC Thymeleaf 视图解析(默认值: true ) spring.thymeleaf.enabled=true # 模板编码 spring.thymeleaf.encoding=UTF-8 # 要被排除在解析之外的视图名称列表,⽤逗号分隔 spring.thymeleaf.excluded-view-names= # 要运⽤于模板之上的模板模式。另⻅ StandardTemplate-ModeHandlers( 默认值: HTML5) spring.thymeleaf.mode=HTML5 # 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ ) spring.thymeleaf.prefix=classpath:/templates/ # 在构建 URL 时添加到视图名称后的后缀(默认值: .html ) spring.thymeleaf.suffix=.html # 应用服务 WEB 访问端口 server.port=8080
2、手动渲染
为提高页面访问速度,可缓存html页面,客户端请求从缓存获取,获取不到再手动渲染
首先创建一个mail模版
Title
hello:欢迎 加入XXX公司,您的入职信息如下:
在测试类中进行渲染
package com.example.thy;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
@SpringBootTest
class ThyApplicationTests {
@Autowired
TemplateEngine templateEngine;
@Test
void contextLoads() {
Context context = new Context();
context.setVariable("username", "张三");
context.setVariable("position", "总监");
context.setVariable("money", "17000");
String mail = templateEngine.process("mail", context);
System.out.println(mail);
}
}
运行测试方法



