认识Thymeleaf模板引擎
一、定义
首先要知道SpringBoot默认不支持jsp,因为jsp性能较低
thymeleaf是Java模板引擎开发库,可以处理和生成HTML、XML、JavaScript、CSS和文本,在Web和非Web环境下都可以正常工作
、使用方法
1、导入依赖(启动器)
!-- 导入thymeleaf模板引擎依赖-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
2、在templates下编写一个HTML
记得导入约束
<!DOCTYPE html>
<!--导入thymeleaf约束-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--简单的取值直接使用$符号即可-->
<h1 th:text="${msg}"></h1>
</body>
</html>
3、编写Controller类
@Controller
public class IndexController {
//页面凡是放在templates目录下,无法直接访问,需要通过Controller跳转访问
@RequestMapping("/test")
public String index(Model model){
model.addAttribute("msg","hello,SpringBoot!");
return "test";
}
}
4、启动服务器,成功将model中的值获取到前端
Thymeleaf基本语法
一、简单的取值和遍历
1、代码
(1)HTML
<!DOCTYPE html>
<!--导入thymeleaf约束-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--简单的取值直接使用$符号即可-->
<h1 th:text="${msg}"></h1>
<!--遍历获取数组中的值-->
<h3 th:each="user:${users}" th:text="${user}"></h3>
</body>
</html>
(2)Controller
@Controller
public class IndexController {
//页面凡是放在templates目录下,无法直接访问,需要通过Controller跳转访问
@RequestMapping("/test")
public String index(Model model) {
model.addAttribute("msg", "hello,SpringBoot!");
//将集合转换成数组
model.addAttribute("users", Arrays.asList("张三","李四"));
return "test";
}
}
2、启动服务器,前端展示
二、标记链接
用@{}
三、标记国际化
用#{}
四、在application.yaml中配置关闭thymeleaf的模板缓存
至此,你已经掌握了怎么使用模板引擎,后续还会持续更新,敬请期待!