Spring Boot 整合Thymeleaf

时间:2022-07-22
本文章向大家介绍Spring Boot 整合Thymeleaf,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

概要信息

什么是 Thymeleaf

Thymeleaf 是一个跟 VelocityFreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点

  • Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板 + 数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
  • Thymeleaf 开箱即用的特性。它提供标准和 Spring 标准两种方言,可以直接套用模板实现 JSTLOGNL 表达式效果,避免每天套模板、改 JSTL、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  • Thymeleaf 提供 Spring 标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

为什么需要 Thymeleaf

如果希望以 Jar 形式发布模块则尽量不要使用 JSP 相关知识,这是因为 JSP 在内嵌的 Servlet 容器上运行有一些问题 (内嵌 Tomcat、 Jetty 不支持 Jar 形式运行 JSPUndertow 不支持 JSP)。

Spring Boot 中推荐使用 Thymeleaf 作为模板引擎,因为 Thymeleaf 提供了完美的 Spring MVC 支持,Spring Boot 提供了大量模板引擎,包括:

  • FreeMarker
  • Groovy
  • Mustache
  • Thymeleaf
  • Velocity

构建DEMO

pom 中导入 thymeleaf 的依赖

<!--thymeleaf模板-->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>

等待maven导入完成后,我们可以在下载完的jar包

double shift 键,搜索 ThymeleafProperties.java 我们可以看到thymeleaf的源码

我们可以看到,thymeleaf 会从 classpath:/templates 也就是springboot目录下的 resources 目录下 读取以 .html 开头的文件进行渲染。

我们下面通过一个小案例,来感受一下 Thymeleaf 模板引擎

创建一个 controller

@Controller
public class HelloController {
    @RequestMapping("hello")
    public String Hello(Model model){
        // 创建一个model,添加变量msg
        model.addAttribute("msg", "hello springboot");
        return "hello";
    }
}

我们看到代码中的 returl "hello" 表示渲染并返回一个hello.html 的页面数据,所以我们在 teamlates下创建一个 hello.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>123123</h1>
    <div th:text="${msg}"></div>
</body>
</html>

使用 thymeleaf模板语法中的 th:text 将controller 中名字为 msg 的 model变量渲染到对应的标签当中

所有的html元素都可以被thymeleaf替换接管:th:元素名称

我们重启 springboot 项目,访问查看效果

成功将定义在 controller 中的 model 变量渲染到 html

常见的一些使用案例

字符串转义,识别html标签

model 中定义一个带有标签的变量

controller > HelloController.java

@Controller
public class HelloController {
    @RequestMapping("/")
    public String Hello(Model model){
        // 创建一个model,添加变量msg
        model.addAttribute("msg", "<h2>hello springboot</h2>");
        return "hello";
    }
}

html 模板中取值 text 为普通文本,utext 表示为转义后的文本

templates > hello.html

<body>
    <h1>123123</h1>
    <div th:text="${msg}"></div>
    <div th:utext="${msg}"></div>
</body>

运行效果

each遍历集合

controller 添加一个 model,并将数组转换为集合

controller > HelloController.java

model.addAttribute("users", Arrays.asList("user1", "user2"));

html 模板处使用 th:each 对集合进行遍历,并将集合中每一个项都渲染到页面

templates > hello.html

<!--遍历集合-->
<h3 th:each="user:${users}" th:text="${user}"></h3>

运行效果