Spring Boot - Thymeleaf模板引擎

什么是Thymeleaf?

  • Thymeleaf 是适用于 Web 和独立环境的现代服务器端 Java 模板引擎,能够处理 HTML,XML,JavaScript,CSS 甚至纯文本。
  • 常用于SpringBoot项目,能和 Spring 框架无缝集成,替代传统的 JSP 技术,是目前 Java Web 开发中最主流的前端模板方案之一。

Thymeleaf 可以处理哪种模板?

开箱即用的 Thymeleaf 允许您处理六种模板,每种模板都称为模板模式 (Template Mode)

  • HTML
  • XML
  • TEXT
  • JavaScript
  • CSS
  • RAW

有两种标记 模板模式(HTMLXML),三种文本 模板模式(TEXTJAVASCRIPTCSS)和无操作 模板模式(RAW)。

引入Thymeleaf

在pom.xml中引入thymeleaf相关的依赖。

XML 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

spring-boot-starter-thymeleaf 是 Spring Boot 提供的 Thymeleaf 模板引擎场景启动器。

核心作用是一键整合 Thymeleaf 到 Spring Boot 项目,无需手动配置复杂依赖和整合逻辑。

  • springBoot启动的时候会自动配置

    bash 复制代码
    org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration
  • 从ThymeleafAutoConfiguration的源代码中我们可以得知ThymeleafProperties中配置了Thymeleaf的规则

    默认的模板路径:classpath:/templates/

    后缀:.html

    可通过application.yml 覆盖

⭐⭐⭐注意:前端页面也需要引入Thymeleaf,否则在前端页面使用Thymeleaf标签是无效的!!!

html 复制代码
<html lang="en" xmlns:th="http://www.thymeleaf.org">

Thymeleaf语法

Thymeleaf官网文档地址:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

Thymeleaf中文文档地址:https://www.docs4dev.com/docs/zh/thymeleaf/3.0/reference/using_thymeleaf.html

标准表达语法

1. 变量表达式

即OGNL表达式或Spring EL表达式(在Spring术语中也叫model attributes)。

语法符号:${......}

**作用:**读取后端传递到页面的所有数据

实例:

后端通过 model.addAttribute("user", new User("张三", 25)) 传数据,前端读属性:

html 复制代码
<span th:text="${user.name}"></span>
<span th:text="${user.age}"></span>

渲染效果:

html 复制代码
<span>张三</span>
<span>25</span>

2. 选择(星号)表达式

语法符号:*{......}

作用: 配合 th:object 使用,获取当前选中对象的属性。

实例:

先通过 th:object="${对象}" 绑定对象,再用 *{属性名} 读属性。

html 复制代码
<div th:object="${session.user}">
    <p>Name: <span th:text="*{username}"></span></p>
    <p>password: <span th:text="*{password}"></span></p>
</div>

3. URL表达式

语法符号:@{......}

**作用:**生成绝对 / 相对 URL,自动处理应用上下文路径 (Context Path),支持参数。

实例:

  • **相对路径:**项目上下文路径是 /demo,<a th:href="@{/user/list}"></a>,自动生成 /demo/user/list
  • 带查询参数的 URL:<a th:href="@{/user/list(page=1, size=10)}"></a> ,生成 /demo/user/list?page=1&size=10
  • 带路径参数的 URL(REST 风格):<a th:href="@{/user/{id}(id=${user.id})}"></a> ,生成 /demo/user/1
  • 绝对 URL:<a th:href="@{https://www.baidu.com}"></a> → 直接生成 https://www.baidu.com

4. 文字国际化表达式

语法符号:#{......}

作用: 读取 .properties 配置文件中的消息文本,支持参数占位。

实例: #{main.title}

5. 片段表达式

语法符号:~{模板名::片段名}

**作用:**引用其他模板中的片段(用于模板布局,如公共头部、底部),公共部分一次编写,全项目复用,修改时只需改一处。

实例:

html 复制代码
<!--布局标签,定义一个代码片段,方便其它地方引用-->
<div th:fragment="top-header">
    <h1>这是头部</h1>
</div>
    
<!--布局标签,替换整个标签到引入的文件
    同一个文件中引用片段应该使用~{this :: site-header}或者~{::site-header}
-->
<!-- 引用片段 -->
<div th:replace="~{::top-header}"></div>

<!--~{fragments/person :: site-header}:
        fragments是路径,
        person是person.html
        site-header是person.html中的代码片段-->
<div id="header" th:replace="~{person :: site-header}">
    原始内容会被替换
</div>

表达式支持的字面量与运算符

  • 字面(Literals)
    文本文字(Text literals): 'one text', 'Another one!',... 用单引号包裹
    数字文本(Number literals): 0, 34, 3.0, 12.3,...
    布尔文本(Boolean literals): true, false
    空(Null literal): null
    文字标记(Literal tokens)标识符类字符串: one, sometext, main,...
  • 文本操作(Text operations)
    字符串连接(String concatenation): +
    文本替换(Literal substitutions): |The name is ${name}|
  • 算术运算(Arithmetic operations)
    二元运算符(Binary operators): +, -, *, /, %
    减号(单目运算符)Minus sign (unary operator): -
  • 布尔操作(Boolean operations)
    二元运算符(Binary operators):and, or
    布尔否定(一元运算符)Boolean negation (unary operator):!, not
  • 比较和等价(Comparisons and equality)
    比较(Comparators): >, <, >=, <= (gt, lt, ge, le)
    等值运算符(Equality operators):==, != (eq, ne)
  • 条件运算符(Conditional operators)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)

常用的thymeleaf标签

关键字 功能说明 案例
基础输出
th:id 替换 id 属性 <input th:id="'xxx' + ${collect.id}"/>
th:text 文本替换 (自动转义 HTML) <p th:text="${collect.description}">description</p>
th:utext 文本替换 (解析 HTML 标签) <p th:utext="${htmlcontent}">conten</p>
th:value 替换 value 属性 <input th:value="${user.name}" />
对象与绑定
th:object 选中一个对象,供子标签使用 *{} <div th:object="${session.user}">
交互与状态
th:onclick 点击事件 (注意:推荐配合 data-* 使用) th:οnclick="'getCollect()'"
th:selected 下拉框选中状态 th:selected="({xxx.id} == {configObj.dd})"
逻辑控制
th:if 条件判断 (True 显示) <a th:if="${userId == collect.userId}">
th:unless 条件判断 (False 显示,与 if 相反) <a th:unless="${session.user != null}">
th:switch 多路分支开关 <div th:switch="${user.role}">
th:case 分支匹配 <p th:case="'admin'">
循环迭代
th:each 遍历集合 <tr th:each="user,userStat:${users}">
链接与资源
th:href 生成超链接地址 <a th:href="@{/login}">
th:src 引入图片或脚本资源 <img th:src="@{/img/logo.png}" />
th:action 表单提交地址 <form th:action="@{/subscribe}">
布局片段
th:fragment 定义代码片段 <div th:fragment="alert">
th:include 包含片段 (内容放入当前标签) <head th:include="layout :: htmlhead">
th:replace 替换片段 (当前标签被完全替换) <div th:replace="fragments/header :: title">
相关推荐
爬山算法2 小时前
Hibernate(76)如何在混合持久化环境中使用Hibernate?
java·后端·hibernate
编程彩机2 小时前
互联网大厂Java面试:从分布式缓存到消息队列的技术场景解析
java·redis·面试·kafka·消息队列·微服务架构·分布式缓存
她说..2 小时前
策略模式+工厂模式实现单接口适配多审核节点
java·spring boot·后端·spring·简单工厂模式·策略模式
csdn_aspnet2 小时前
ASP.NET 8 - Cookie 身份验证
后端·asp.net·cookie·.net8
坚持就完事了2 小时前
Java的OOP
java·开发语言
笔画人生2 小时前
Cursor + 蓝耘API:用自然语言完成全栈项目开发
前端·后端
像少年啦飞驰点、2 小时前
零基础入门 Spring Boot:从“Hello World”到可部署微服务的完整学习路径
java·spring boot·微服务·编程入门·后端开发
undsky_3 小时前
【RuoYi-SpringBoot3-Pro】:将 AI 编程融入传统 java 开发
java·人工智能·spring boot·ai·ai编程
不光头强3 小时前
shiro学习要点
java·学习·spring