一、Thymeleaf 的基本介绍
1.1 什么是Thymeleaf
Thymeleaf 是适用于 Web 和独立环境的现代服务器端 Java 模板引擎。 Thymeleaf 的主要目标是为开发工作流程带来优雅的自然模板,既可以在浏览器中正确显示的 HTML,也可以 用作静态原型,从而在开发团队中实现更强大的协作。
1.2 Thymeleaf的优势
与传统的 JSP 不同,Thymeleaf 可以使用浏览器直接打开,因为可以忽略掉拓展属性,相当于打开原生页面,给前端人员也带来一定的便利。 在本地环境或者有网络的环境下,Thymeleaf 均可运行。由于 thymeleaf 支持 html 原型,也支持在 html 标签里增加额外的属性来达到【模板+数据】的展示方式,所以美工可以直接在浏览器中查看页面效果,当服务启动后,也可以让后台开发人员查看带数据的动态页面效果。
模板引擎在web领域的主要作用:让网站实现界面和数据分离,这样大大提高了开发效率,让代码重用更加容易。
二、Thymeleaf的使用
用IDEA基于Springboot编写一个Thymeleaf程序
2.1 导入依赖
选择与jdk对应的版本号
在创建项目工程时勾选 Thymeleaf
在创建项目工程时勾选 Thymeleaf,也可以创建之后再pom.xml文件中手动导入一下依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.2 访问静态页面
在 templates/目录下新建一个 error 文件 夹,专门放置错误的 html 页面,然后分别打印些信息。例如 404.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>这是 404 页面</body>
</html>
再写一个 controller 来测试一下 404 和 500 页面:
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {
@RequestMapping("/test404")
public String test404() {
return "index";
}
@RequestMapping("/test500")
public String test500() {
int i = 1 / 0;
return "index";
}
}
当在浏览器中输入 localhost:8080/thymeleaf/test400 时,故意输入错误,找不到对应的方法,就会跳转到 404.html 显示。 当在浏览器中输入 localhost:8088/thymeleaf/test505 时,会抛出异常,然后会自动跳转到 500.html 显示。
2.3 Thymeleaf 相关配置
因为 Thymeleaf 中已经有默认的配置了,不需要再对其做过多的配置,需要注意一下,Thymeleaf 默认是开启 页面缓存的,所以在开发的时候,需要关闭这个页面缓存 spring: thymeleaf: cache: false #关闭缓存 否则会有缓存,导致页面没法及时看到更新后的效果。比如修改了一个文件,已经 update 到 tomcat 了,但刷 新页面还是之前的页面,就是因为缓存引起的。
2.4 thymeleaf 中的一些常用的标签操作: