一、SpringBoot中使用Thymeleaf
1、在创建SpringBoot 的项目时,选择Thymeleaf的组件,或者自己手动在maven中添加库依赖:
org.springframework.boot
spring-boot-starter-thymeleaf
2、在 application.yml(或aproperties)中添加相应的配置:
server:
port: 80
# thymeleaf 配置
spring:
thymeleaf:
# 是否使用缓存,开发阶段最填false
cache: false
# 检查该模板是否存在
check-template-location: true
# 模板中内容的类型
servlet:
content-type: text/html
# 启动 MVC 对Thymeleaf 视图的解析
enabled: true
# 模板的字符集
encoding: UTF-8
# 从解析中排除的视图名称的逗号分隔列表,没有的话就为空
excluded-view-names:
# 使用的是什么类型模板
mode: HTML5
# 设定文件路径
prefix: classpath:/templates/
# 设定文件后缀名
suffix: .html
# 设定静态文件路径,js,css等
mvc:
static-path-pattern: /static/**
3、新建一个controller类
@Controller
public class IndexController {
@GetMapping("/index")
public String indexJsp(Model model){
User user = new User();
user.setUsername("张三");
user.setAge(18);
user.setBirthday(new Date());
User user2 = new User();
user2.setUsername("李四");
user2.setAge(17);
user2.setBirthday(new Date());
List userList = new ArrayList();
userList.add(user);
userList.add(user2);
model.addAttribute("userList", userList);
return "indexThymeleaf";
}
}
4、新建一个.html页面文件
加上名称空间,就会有thymeleaf的代码提示
接下来便可以使用th:标签库中的方法了。这些方法和jsp极其相像
Title
Thymeleaf首页
用户名
密码
年龄
出生年月
空值
5、启动项目访问即可
Thymeleaf 官方文档
标签参考文章:https://www.cnblogs.com/beyrl-blog/p/6633182.html
end ~