1、简介
Thymeleaf是一个流行的模板引擎,该模板引擎采用 Java 语言开发。
Java 中常见的模板引擎有 Velocity、Freemaker、Thymeleaf 等。不同的模板引擎都会具有自己的特定的标签体系,而 Thymeleaf 以 HTML 标签为载体,在 HTML 的标签下实现对数据的展示。
Thymeleaf 本身与 SpringBoot 是没有关系的,但 SpringBoot 官方推荐使用 Thymeleaf 作为前端页面的数据展示技术。同时,SpringBoot 很好地集成了这种模板技术。
关于Thymeleaf 的详情可访问其官网: http://www.thymeleaf.org
2、Spring Boot集成Thymeleaf
2.1、添加依赖
-
方法1:通过创建工程添加依赖
-
方法2:通过pom.xml添加配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.2、在开发阶段关闭thymeleaf缓存
打开application.yml文件并添加如下属性:
spring:
...
thymeleaf:
cache: false
生产环境建议开启(即默认)
2.3、编写Controller类并传参
将需要传递的参数传递到Model对象中:
@Controller
public class ThymeleafController {
@RequestMapping("/demo")
public String thymeleafHandler(Model model) {
model.addAttribute("welcome", "hello thymeleaf");
// 返回 resources/templates 目录下指定html页面,无需添加后缀
return "index";
}
}
2.4、添加index.html页面并测试
在 resources/templates 目录下创建index.html页面,编写界面,并从model对象中读取参数值:
<!DOCTYPE html>
<!-- 添加thymeleaf命名空间 -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<p th:text="${welcome}">这里将要显示数据,但这些文字不显示。</p>
</body>
</html>
启动并测试:
3、Thymeleaf标准表达式
3.1、变量表达式${}
获取从Model或Request对象中设置的参数.。
-
创建实体类
package com.blairscott.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class Teacher { private Integer id; private String name; private int age; }
-
Controller传递参数
@Controller public class ThymeleafController { @RequestMapping("/demo") public String thymeleafHandler(Model model) { model.addAttribute("teacher", new Teacher(1, "zhangsan", 18)); return "index"; } }
-
创建index.html接受并输出参数
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <p th:text="${teacher}">这里将要显示数据,但这些文字不显示。</p> <p th:text="${teacher.id}">这里将要显示数据,但这些文字不显示。</p> <p th:text="${teacher.name}">这里将要显示数据,但这些文字不显示。</p> <p th:text="${teacher.age}">这里将要显示数据,但这些文字不显示。</p> </body> </html>
-
启动服务并测试
3.2、选择表达式*{}
先通过th:object="${teacher}"
选择了对象,再通过th:text="*{id}"
等选择属性