Thymeleaf教程

news/2025/10/4 15:24:17/文章来源:https://www.cnblogs.com/smalldong/p/19125638

一 Thymeleaf是什么

Thymeleaf 是一款现代服务器端 Java 模板引擎,专为 Web 开发设计,尤其适合与 Spring Boot 框架搭配使用。它的核心目标是实现 “自然模板”(Natural Templates)—— 即模板文件本身可直接作为纯 HTML 在浏览器中打开预览,无需依赖服务器渲染,同时能在后端动态填充数据,兼顾开发效率与前端预览体验。

1. 核心定位与优势

  1. 自然模板特性Thymeleaf 模板以标准 HTML 为基础,通过自定义的 th:* 系列属性(如 th:textth:if)实现动态逻辑,而非嵌入特殊标签或脚本。这意味着开发者可直接用浏览器打开模板文件查看静态样式,无需启动后端服务,大幅提升前后端协作效率。

    示例:静态 HTML 与 Thymeleaf 模板的对比

    静态 HTML Thymeleaf 模板
    <p>用户名:张三</p> <p>用户名:<span th:text="${username}">张三</span></p>
    (固定文本) th:text 动态填充 username,静态预览时显示 “张三”)
  2. 强大的动态渲染能力支持变量输出、条件判断、循环遍历、URL 生成、模板复用等全场景动态逻辑,能覆盖 Web 开发中几乎所有后端渲染需求,且语法简洁直观,易于理解。

  3. 无缝集成 Spring 生态作为 Spring Boot 官方推荐的模板引擎(默认集成),Thymeleaf 与 Spring MVC、Spring Security 等组件深度兼容,可直接接收 Spring 控制器传递的 Model 数据,无需额外配置,上手成本极低。

  4. 多模板模式支持除了 HTML,还支持 XML、TEXT、JavaScript、CSS 等多种模板类型,可用于生成邮件内容、配置文件等非 Web 场景,灵活性强。

2.核心工作原理

  1. 模板文件位置在 Spring Boot 项目中,Thymeleaf 模板默认存放于 src/main/resources/templates 目录下,文件后缀为 .html(或其他支持的类型)。

  2. 渲染流程

    1. 前端发送请求到 Spring 控制器(@Controller);
    2. 控制器通过 Model 向模板传递动态数据(如 model.addAttribute("user", userObj));
    3. 控制器返回模板文件名(如 return "index",对应 templates/index.html);
    4. Thymeleaf 引擎加载模板,解析 th:* 属性,用 Model 中的数据替换动态占位符;
    5. 渲染后的静态 HTML 响应给前端浏览器。

3.关键语法特点

Thymeleaf 核心通过 “属性” 实现动态逻辑,常用核心属性如下:

  • 变量输出th:text(设置元素文本)、th:value(设置表单元素值),基于 $ {变量名} 读取后端数据;
  • 循环遍历th:each(遍历集合,如 th:each="user : ${userList}");
  • 条件判断th:if(条件成立时显示元素)、th:unless(条件不成立时显示)、th:switch(多分支判断);
  • URL 生成th:href(生成链接,如 th:href="@{/user/{id}(id=${userId})}",自动拼接上下文路径);
  • 模板复用th:fragment(定义可复用片段)、th:insert/th:replace(引入片段,实现导航栏、页脚等公共部分复用)。

二 Thymeleaf怎么用

image

1.环境准备

1. 创建 Spring Boot 项目

  • 使用 Spring Initializr 创建项目,添加依赖:

    • Spring Web:提供 Web 支持
    • Thymeleaf:模板引擎
    • Lombok(可选):简化实体类代码
  • pom.xml核心依赖:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.4</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.yqd</groupId><artifactId>Thymeleaf-Demo</artifactId><version>0.0.1-SNAPSHOT</version><name>Thymeleaf-Demo</name><description>Thymeleaf-Demo</description><properties><java.version>17</java.version></properties><dependencies><!-- Spring Web --><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><!-- Lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
    

2.配置文件的修改(application.yml)

spring:application:name: Thymeleaf-Demothymeleaf:cache: falseserver:port: 8080

2. Thymeleaf 基础语法

Thymeleaf 模板文件默认放在 src/main/resources/templates 目录下,后缀为 .html

1. 变量输出(${}

用于在页面中显示后端传递的变量。

后端 Controller

package com.yqd.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;@Controller
public class ThymeleafController {@GetMapping("/variable")public String variable(Model model) {model.addAttribute("username", "张三");model.addAttribute("age", 20);return "variable"; // 对应templates/variable.html}
}

前端模板(variable.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> <!-- 引入Thymeleaf命名空间 -->
<head><title>变量输出</title>
</head>
<body>
<h3>用户名:<span th:text="${username}"></span></h3>
<h3>年龄:<span th:text="${age}"></span></h3>
</body>
</html>
  • th:text:将变量值设置为元素的文本内容
  • 命名空间 xmlns:th="http://www.thymeleaf.org" 用于 IDE 识别 Thymeleaf 语法

2. 对象与集合处理

实体类(User.java)

package com.yqd.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data // Lombok注解,自动生成getter/setter
@AllArgsConstructor
@NoArgsConstructor
public class User {private String name;private Integer age;private String email;
}

后端传递对象和集合

@GetMapping("/object")
public String object(Model model) {// 单个对象User user = new User();user.setName("李四");user.setAge(25);user.setEmail("lisi@example.com");model.addAttribute("user", user);// 集合List<User> userList = Arrays.asList(new User("王五", 30, "wangwu@example.com"),new User("赵六", 35, "zhaoliu@example.com"));model.addAttribute("userList", userList);return "object";
}

前端模板(object.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>对象与集合</title>
</head>
<body>
<!-- 单个对象 -->
<h3>单个用户信息</h3>
<p>姓名:<span th:text="${user.name}"></span></p>
<p>年龄:<span th:text="${user.age}"></span></p><!-- 集合遍历(th:each) -->
<h3>用户列表</h3>
<ul><li th:each="u : ${userList}"> <!-- u是集合中的每个元素 -->姓名:<span th:text="${u.name}"></span>,邮箱:<span th:text="${u.email}"></span></li>
</ul>
</body>
</html>
  • th:each="变量 : ${集合}":遍历集合,变量名可自定义

3. 条件判断(th:if/th:unless/th:switch

后端传递条件变量

@GetMapping("/condition")
public String condition(Model model) {model.addAttribute("score", 85);model.addAttribute("role", "admin");return "condition";
}

前端模板(condition.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>条件判断</title>
</head>
<body>
<!-- th:if:条件为true时显示 -->
<p th:if="${score >= 60}">成绩合格</p>
<!-- th:unless:与th:if相反,条件为false时显示 -->
<p th:unless="${score >= 90}">未达到优秀</p><!-- th:switch/th:case:类似Java的switch -->
<div th:switch="${role}"><p th:case="'admin'">您是管理员</p><p th:case="'user'">您是普通用户</p><p th:case="*">未知角色</p> <!-- *表示默认 -->
</div>
</body>
</html>

4. 链接与表单

后端处理请求

@GetMapping("/link")
public String link(Model model) {model.addAttribute("id", 100);return "link";
}// 处理表单提交
@PostMapping("/submit")
public String submit(@RequestParam String username, Model model) {model.addAttribute("msg", "提交成功!用户名:" + username);return "result";
}

前端模板(link.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>链接与表单</title>
</head>
<body>
<a href="/variable">原始跳转方式</a>
<!-- 链接(th:href) -->
<a th:href="@{/variable}">跳转到变量页面</a>
<br>
<a th:href="@{/user/{id}(id=${id})}">带参数的链接(id=100)</a> <!-- 路径参数 --><!-- 表单(th:action/th:method) -->
<form th:action="@{/submit}" th:method="post">用户名:<input type="text" name="username"><button type="submit">提交</button>
</form>
</body>
</html>

前端模板(result.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> <!-- 引入Thymeleaf命名空间 -->
<head><title>result页面</title>
</head>
<body>
<span th:text="${msg}">hello</span>
</body>
</html>
  • @{}:用于生成 URL,自动拼接上下文路径(避免硬编码)
  • 表单提交需注意:th:method 支持 get/post,参数通过 name 属性绑定

5. 内置对象与工具类

Thymeleaf 提供了常用内置对象(如请求参数、会话)和工具类(如日期格式化)。

后端传递数据

@GetMapping("/utility")
public String utility(Model model, HttpSession session) {model.addAttribute("date", new Date());session.setAttribute("loginUser", "admin"); // 会话对象return "utility";
}

前端模板(utility.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>内置对象与工具类</title>
</head>
<body>
<!-- 请求参数(param对象) -->
<p>URL参数name:<span th:text="${param.name}"></span></p>
<!-- 访问:http://localhost:8080/utility?name=test 可看到结果 --><!-- 会话对象(session对象) -->
<p>登录用户:<span th:text="${session.loginUser}"></span></p><!-- 日期格式化(#dates工具类) -->
<p>原始日期:<span th:text="${date}"></span></p>
<p>格式化日期:<span th:text="${#dates.format(date, 'yyyy-MM-dd HH:mm:ss')}"></span></p><!-- 字符串工具类(#strings) -->
<p>字符串长度:<span th:text="${#strings.length('hello')}"></span></p>
<p>字符串大写:<span th:text="${#strings.toUpperCase('hello')}"></span></p>
</body>
</html>
  • 常用内置对象:param(请求参数)、session(会话)、application(应用上下文)
  • 常用工具类:#dates(日期)、#strings(字符串)、#numbers(数字)

6. 模板复用(th:fragment/th:insert/th:replace

用于抽取公共部分(如导航栏、页脚),减少重复代码。

后端传递数据

@GetMapping("/reuse")
public String utility() {return "reuse";
}

公共模板(common/footer.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<!-- 定义片段 -->
<div th:fragment="footer"><p>© 2025 我的网站 版权所有</p>
</div>
</body>
</html>

使用公共片段的页面(reuse.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>模板复用</title>
</head>
<body>
<h3>主内容</h3>
<!-- 引入公共片段 -->
<div th:insert="~{common/footer :: footer}"></div>
<!-- 或使用th:replace(替换当前标签) -->
<!-- <div th:replace="~{common/footer :: footer}"></div> -->
</body>
</html>
  • th:fragment="片段名":定义可复用片段
  • th:insert="~{模板路径 :: 片段名}":插入片段(保留当前标签)
  • th:replace="~{模板路径 :: 片段名}":替换当前标签为片段

三、运行与测试

  1. 启动 Spring Boot 应用(主类添加 @SpringBootApplication 注解)
  2. 访问以下地址测试各功能:
    • 变量输出:http://localhost:8080/variable
    • 对象与集合:http://localhost:8080/object
    • 条件判断:http://localhost:8080/condition
    • 链接与表单:http://localhost:8080/link
    • 内置对象:http://localhost:8080/utility?name=test
    • 模板复用:http://localhost:8080/reuse

四、总结

Thymeleaf 的核心优势是自然模板(模板文件可直接作为 HTML 打开),常用语法包括:

  • 变量输出:${} + th:text
  • 遍历:th:each
  • 条件:th:if/th:unless/th:switch
  • URL 生成:@{}
  • 模板复用:th:fragment + th:insert

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/927271.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

商务网站建设的流程图专注新乡网站建设

1. 聚量推客&#xff1a; “聚量推客”汇聚了众多市场上有的和没有的地推网推拉新接单项目&#xff0c;目前比较火热&#xff0c;我们做地推和网推从业者如果长期在这行业去做推广可以使用这个平台&#xff0c;价格高数据也好&#xff0c;大部分拉新项目也都是官签一手资源 一…

VMware虚拟机设置中处理器数量和内核内存再次探讨

VMware虚拟机设置中处理器数量和内核内存再次探讨, 如何设置性能较好.设置内核数量 1*8 根据VMWARE虚拟机的CPU分配(VMWARE14):处理器数量、核心数量分配验证 - imxiangzi - 博客园 VMware Workstation CPU如何设置…

VMware中Ubuntu迁移(复制)后进入紧急模式You are in emergency mode.

解决了VMware虚拟机迁移后报错You are in emergency mode.在复制或迁移虚拟机后, Ubuntu进入紧急模式, 可以看见Error -107 cannot open Connection 这是共享文件夹功能被禁用导致的! 开启后输入reboot -f重启即可. 解…

2025年全国大学生电子设计竞赛A题:能量回馈的变流器负载试验装置(国一方案分享+代码工程+仿真) - 详解

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

太简单了!原来PS在线抠图可以这么玩,背景分离无压力

你是不是总被“抠图”困扰?想给图片换背景,却觉得下载安装Photoshop太费事?放心,这篇教程就是为你准备的!今天我来手把手教你用在线PS抠图工具,无需安装、打开网页就能轻松搞定背景分离,就算是零基础新手,也能…

深入解析:【Leetcode】随笔

深入解析:【Leetcode】随笔pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco",…

DateStyle日期时间字符串序列化 - br

import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.ChronoField;import static java.time.temporal.ChronoField.*;public class DataStyle …

如何用AI工具编写一个轻量化CRM系统(七):AI生成pytest测试脚本

如何用AI工具编写一个轻量化CRM系统(七):AI生成pytest测试脚本2025-10-04 15:12 tlnshuju 阅读(0) 评论(0) 收藏 举报pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !im…

网站建设总结心得游戏运营备案官方网站

昨天一个客户要在RK3399 Linux开发板上面使用身份证读卡器&#xff0c;由于没有客户的开发板&#xff0c;故只能用本机ubuntu虚拟机来交叉编译&#xff0c;用客户发过来的交叉编译工具&#xff0c;已经编译好libusb然后编译libdonsee.so的时候提示找不到libusb&#xff0c;报错…

实用指南:Linux驱动之V4L2

实用指南:Linux驱动之V4L2pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", …

湖北省建设人力资源网站网页制作素材教学

目录 一、代入排除法 例题 练习 二、数字特性 例题 练习 整除特性 例题 倍数特性 普通倍数 因子倍数 比例倍数 例题 练习 三、方程法 例题 练习 四、 不定方程&#xff08;组&#xff09; 例题 练习 一、代入排除法 例题 素数&#xff1a…

儿童与青少年数据安全及体育发展新方向会议

本次会议聚焦儿童和青少年数据安全保护,探讨人工智能对隐私的影响及体育文化在教育中的作用,涵盖数据保护、AI隐私风险等关键技术议题。会议信息 时间:2025年10月10日 地点:克拉科夫布罗尼斯瓦夫捷克体育学院 组织…

做网站运营需要具备什么能力建站公司都有哪些

在Flutter中&#xff0c;异步编程是非常重要的一部分&#xff0c;特别是在处理用户输入、网络请求或其他涉及时间的操作时。Flutter提供了一种强大的工具&#xff0c;称为Stream&#xff0c;用于简化异步编程的过程。 什么是 Stream&#xff1f; Stream是一种用于处理异步数据…

网站等保建设上海好的设计公司

SV-7042T 30W网络对讲广播一体音柱 一、描述 SV-7042T是深圳锐科达电子有限公司的一款壁挂式网络有源音柱&#xff0c;具有10/100M以太网接口&#xff0c;可将网络音源通过自带的功放和喇叭输出播放&#xff0c;其采用防水设计&#xff0c;功率可以从20W到40W。SV-7042T作为网…

Embarcadero Dev-C++ 6.3 中文乱码问题 - 教程

Embarcadero Dev-C++ 6.3 中文乱码问题 - 教程pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", &q…

2025.10.4——2绿

普及/提高- P9869 [NOIP2023] 三值逻辑 图上的问题,听完老师讲解还看了题解才理解。 P3847 [TJOI2007] 调整队形 刚开始用最长公共子序列做,结果是错的。 后来换成区间DP,就过了。

网站建设迁移方案优化官网咨询

支付开宝的本地生活来了&#xff01;按支付宝财大气粗的做法&#xff0c;它一旦要推什么项目&#xff0c;那自然会在前期疯狂洒钱&#xff0c;以求通过这种模式快速占领市场。 所以&#xff0c;这次支付宝要推本地生活项目&#xff0c;这一贯做法自然得跟上&#xff0c;只是这…

怎么提高自己网站的知名度目前网站开发语言

思维导图 案例一&#xff1a;内在-资产提取-AppinfoScanne AppinfoScanner 一款适用于以 HW 行动/红队/渗透测试团队为场景的移动端(Android、iOS、WEB、H5、静态网站)信息收集扫描工具&#xff0c;可以帮助渗透测试工程师、攻击队成员、红队成员快速收集到移动端或者静态 WEB …

二级域名解析网站专业做网站设计公司价格

在Java并发场景中&#xff0c;会涉及到各种各样的锁&#xff0c;比如&#xff1a;高并发编程系列&#xff1a;4种常用Java线程锁的特点&#xff0c;性能比较、使用场景&#xff0c;这些锁有对应的种类&#xff1a;公平锁&#xff0c;乐观锁&#xff0c;悲观锁等等&#xff0c;这…

十月四日就听《10월 4일》

왠지 요즘에 난 그 소녀가 떠올라 不知为何最近 那女孩总浮现在脑海 내가 숨을 멈출 때 每当我屏住呼吸 就会想起你 너를 떠올리곤 해 在我眼前浮现的 내 눈가엔 아련한 시절의 只有那段朦胧岁月里 너무나 짧았던 太过…