Spring Boot 整合 Thymeleaf

112 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第12天,点击查看活动详情

Spring Boot 整合 Thymeleaf

创建springboot的项目

引入 Thymeleaf 依赖


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>


    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--Thymeleaf模板引擎依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

创建模板文件

在resources/templates目录下新建模板文件thymeleaf.html。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf demo</title>
</head>
<body>
<p>description字段值为:</p>
<p th:text="${description}">这里显示的是 description 字段内容</p>
</body>
</html>

编辑 Controller 代码

在controller包下新增ThymeleafController.java文件,将模板文件所需的description字段赋值并转发至模板文件,代码如下所示:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class ThymeleafControlle {
    @GetMapping("/thymeleaf")
    public String hello(HttpServletRequest request,
                        @RequestParam(  value = "description",
                                        required = false,
                                        defaultValue = "这是一个测试")
                                String description) {
        request.setAttribute("description", description);
        return "thymeleaf";
    }
}

最终的目录结构如下

image.png

启动并访问

在项目启动成功后,打开浏览器并输入本地域名和端口号,我们访问 /thymeleaf

image.png

Thymeleaf 模板引擎使用注意事项

  • 模板引擎的后缀名称注意事项

虽然Thymeleaf模板引擎文件的后缀名称是.html,但是这种文件严格来说并不属于静态资源文件,而是模板文件,存放的目录也是在模板目录中

模板引擎文件一般不允许直接访问,而是要经过Controller控制器的处理,将动态数据返回到模板文件中进行读取并渲染的。

  • 必须引入名称空间
<html lang="en" xmlns:th="http://www.thymeleaf.org">

引入之后会有Thymeleaf代码的语法提示,能够提升开发效率,也能减少人为造成的低级错误。

  • 禁用模板缓存

Thymeleaf 的默认缓存设置是通过配置文件的 spring.thymeleaf.cache 配置属性决定的,通过如上 Thymeleaf 模板的配置属性类 ThymeleafProperties 可以发现该属性默认为 true,因此 Thymeleaf 默认是使用模板缓存的,该设置有助于改善应用程序的性能,因为模板只需编译一次即可,但是在开发过程中不能实时看到页面变更的效果,除非重启应用程序,因此建议将该属性设置为 false,在配置文件中修改如下:

spring.thymeleaf.cache=false
  • IDEA 中通过 Thymeleaf 语法读取变量时爆红色波浪线问题

只是由于 IDEA 中默认开启了表达式参数验证,即使在后端的 model 数据中添加了该变量,但是对于前端文件是无法感知的,因此会报这个错误,修改就好

image.png