当前位置: 首页 > news >正文

Spring Boot 整合 Thymeleaf 模板引擎:从零开始的完整指南

引言:为什么选择 Thymeleaf?

Thymeleaf 是一个现代化的服务器端 Java 模板引擎,专为 Web 开发而设计。与 JSP 不同,Thymeleaf 模板是纯 HTML 文件,可以直接在浏览器中预览,无需后端服务器支持。这种"自然模板"特性让前端开发和后端开发可以无缝协作。Spring Boot 官方推荐使用 Thymeleaf 作为视图技术,它提供了:

  • 简洁优雅的语法

  • 强大的表达式语言

  • 与 Spring 生态的完美集成

  • 丰富的布局功能

  • 开箱即用的国际化支持

本文将带你从零开始,全面掌握 Spring Boot 中 Thymeleaf 的使用。

一、环境搭建

1. 创建 Spring Boot 项目

使用 Spring Initializr (https://start.spring.io/) 创建项目,选择以下依赖:

  • Spring Web

  • Thymeleaf

2. Maven 依赖

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

3. 目录结构

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── demo
│   │               ├── controller
│   │               ├── model
│   │               └── DemoApplication.java
│   └── resources
│       ├── static   # 静态资源(CSS, JS, 图片)
│       ├── templates # Thymeleaf 模板
│       └── application.properties

二、基础配置

application.properties 配置

# Thymeleaf 配置
spring.thymeleaf.cache=false # 开发时关闭缓存
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8# 静态资源路径
spring.resources.static-locations=classpath:/static/

三、第一个 Thymeleaf 页面

1. 创建控制器

@Controller
public class HomeController {@GetMapping("/")public String home(Model model) {model.addAttribute("message", "Hello, Thymeleaf!");model.addAttribute("currentDate", new Date());return "home"; // 对应 templates/home.html}
}

2. 创建模板文件 (templates/home.html)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Thymeleaf 入门</title>
</head>
<body><h1 th:text="${message}">默认标题</h1><p>当前时间:<span th:text="${#dates.format(currentDate, 'yyyy-MM-dd HH:mm:ss')}"></span></p><!-- 使用 Thymeleaf 表达式 --><div th:if="${not #strings.isEmpty(message)}"><p>消息长度:<span th:text="${#strings.length(message)}"></span></p></div><!-- 链接表达式 --><a th:href="@{/about}">关于我们</a>
</body>
</html>

3. 运行并访问

启动应用后访问 http://localhost:8080,你将看到:

  1. "Hello, Thymeleaf!" 标题

  2. 格式化的当前时间

  3. 消息长度计算

  4. 指向关于页面的链接

四、Thymeleaf 核心语法

1. 变量表达式 (${...})

用于访问模型中的数据:

<p th:text="${user.name}">用户名</p>
<p th:text="${user.age > 18 ? '成年' : '未成年'}">年龄状态</p>

2. 选择表达式 (*{...})

与 th:object 配合使用:

<div th:object="${user}"><p>姓名: <span th:text="*{name}"></span></p><p>邮箱: <span th:text="*{email}"></span></p>
</div>

3. 消息表达式 (#{...})

用于国际化:

<p th:text="#{welcome.message}">欢迎信息</p>

4. 链接表达式 (@{...})

生成正确的 URL:

<a th:href="@{/users/{id}/profile(id=${userId})}">用户资料</a>
<img th:src="@{/images/logo.png}">

5. 片段表达式 (~{...})

包含模板片段:

<div th:insert="~{fragments/header :: header}"></div>

五、常用功能详解

1. 条件判断

<div th:if="${user.isAdmin}"><button>管理面板</button>
</div><div th:unless="${user.active}"><p class="warning">账户未激活</p>
</div><div th:switch="${user.role}"><p th:case="'admin'">管理员</p><p th:case="'user'">普通用户</p><p th:case="*">未知角色</p>
</div>

2. 循环遍历

<table><tr th:each="user, iterStat : ${users}"><td th:text="${iterStat.index + 1}">序号</td><td th:text="${user.name}">姓名</td><td th:text="${user.email}">邮箱</td><td><span th:if="${user.active}" th:text="激活"></span><span th:unless="${user.active}" th:text="未激活"></span></td></tr>
</table>

3. 表单处理

<form th:action="@{/users}" th:object="${user}" method="post"><input type="text" th:field="*{name}" placeholder="姓名"><input type="email" th:field="*{email}" placeholder="邮箱"><button type="submit">保存</button><!-- 显示字段错误 --><div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="error"></div>
</form>

4. 布局模板

layout.html (布局文件)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title th:text="${title}">默认标题</title><th:block th:replace="fragments/head :: head"></th:block>
</head>
<body><header th:replace="fragments/header :: header"></header><main><!-- 内容区域 --><div th:replace="${view}"></div></main><footer th:replace="fragments/footer :: footer"></footer>
</body>
</html>

home.html (具体页面)

<!DOCTYPE html>
<html th:replace="~{layout :: layout(~{::title}, ~{::main})}">
<head><title>首页</title>
</head>
<body><main><h1>欢迎来到首页</h1><p>这是主要内容区域</p></main>
</body>
</html>

六、实用技巧与最佳实践

1. 工具对象

Thymeleaf 提供了一系列实用工具:

  • #dates:日期格式化

  • #strings:字符串操作

  • #numbers:数字格式化

  • #lists:集合操作

  • #arrays:数组操作

  • #objects:对象操作

    <p th:text="${#dates.format(user.birthday, 'yyyy年MM月dd日')}"></p>
    <p th:text="${#strings.capitalize(user.name)}"></p>
    <p th:text="${#lists.size(user.roles)}"></p>

2. 内联表达式

使用 [[...]] 或 [(...)] 在 HTML 属性中内联表达式:

<script th:inline="javascript">var userId = [[${user.id}]];var userName = /*[[${user.name}]]*/ '默认名称';
</script><p data-user-id="${user.id}">用户ID: [[${user.id}]]</p>

3. 模板缓存管理

开发环境关闭缓存,生产环境开启缓存:

# application-dev.properties
spring.thymeleaf.cache=false# application-prod.properties
spring.thymeleaf.cache=true

4. 自定义方言

创建自定义 Thymeleaf 处理器:

public class AlertDialect extends AbstractProcessorDialect {public AlertDialect() {super("Alert Dialect", "alert", 1000);}@Overridepublic Set<IProcessor> getProcessors(String dialectPrefix) {return Set.of(new AlertTagProcessor(dialectPrefix));}
}public class AlertTagProcessor extends AbstractElementTagProcessor {// 实现自定义标签处理逻辑
}

注册方言:

@Configuration
public class ThymeleafConfig {@Beanpublic AlertDialect alertDialect() {return new AlertDialect();}
}

七、常见问题解决

1. 静态资源加载问题

确保路径正确:

<!-- 正确方式 -->
<link th:href="@{/css/style.css}" rel="stylesheet"><!-- 错误方式 -->
<link href="/css/style.css" rel="stylesheet">

2. 表单绑定失败

确保表单对象和字段名匹配:

// Controller
@PostMapping("/save")
public String saveUser(@ModelAttribute("userForm") User user) {// ...
}
<!-- 模板 -->
<form th:object="${userForm}"><input th:field="*{name}">
</form>

3. 国际化支持

配置消息源:

# application.properties
spring.messages.basename=messages

创建 messages.properties:

welcome.message=欢迎您, {0}!

在模板中使用:

<p th:text="#{welcome.message(${user.name})}"></p>

八、进阶学习资源

  1. 官方文档

    • Thymeleaf 官方文档

    • Spring Boot Thymeleaf 文档

  2. 推荐书籍

    • "Thymeleaf: Practical Natural Templates" by José Samper

    • "Spring Boot in Action" by Craig Walls

  3. 实战项目

    • GitHub 搜索 "spring-boot-thymeleaf-example"

    • Spring 官方示例项目

总结

Thymeleaf 作为 Spring Boot 的官方推荐模板引擎,提供了强大的功能和优雅的语法。通过本文的学习,你应该能够:

  1. 搭建 Spring Boot + Thymeleaf 开发环境

  2. 使用基础表达式和常用功能

  3. 实现复杂的页面布局

  4. 处理表单和验证

  5. 解决常见开发问题

Thymeleaf 的"自然模板"特性使其成为现代 Web 开发的理想选择,它让前后端协作更加高效。现在就开始在你的项目中尝试使用 Thymeleaf 吧!

http://www.dtcms.com/a/329634.html

相关文章:

  • 攒钱学概论:5、创业术
  • Gemma 3 报告中的蒸馏
  • PHP imagick扩展安装以及应用
  • 16_基于深度学习的道路缺陷检测识别系统(yolo11、yolov8、yolov5+UI界面+Python项目源码+模型+标注好的数据集)
  • 自动驾驶轨迹规划算法——Apollo EM Planner
  • 从0开始配置conda环境并在PyCharm中使用
  • 8.13打卡 DAY 41 简单CNN
  • 对比学习中核心损失函数的发展脉络
  • 内存泄漏系列专题分析之三十三:cameraserver ION骤降成-1导致内存占用超标
  • 《Power Voronoi图的数学原理》
  • Nginx学习笔记(六)—— Nginx反向代理
  • CSS保持元素宽高比,固定元素宽高比
  • Socket 套接字的学习--UDP
  • 设计秒杀系统从哪些方面考虑
  • 服务器安全检测和防御技术
  • 符合实时AUTOSAR OS的形式化设计和验证方法
  • WPF的c1FlexGrid的动态列隐藏和动态列名设置
  • AI企业培训系统构建指南
  • 在 Conda 环境下编译 C++ 程序时报错:version `GLIBCXX_3.4.30‘ not found
  • 数据结构:队列(Queue)与循环队列(Circular Queue)
  • setsockopt函数详解
  • 海洋通信系统技术文档(1)
  • HTTP 缓存机制全面解析
  • 体制内程序员证书扫盲(中国内地)
  • 可搜索的 HTML 版本 Emoji 图标大全,可以直接打开网页使用,每个图标可以点击复制,方便使用
  • 【unity实战】在unity实现一套可扩展的Model-View-Data (MVD) 系统架构设计
  • 常用 MaxKB 函数库(HTTP、MYSQL)
  • Qt中实现OpenGL应用的编程框架
  • [系统架构]系统架构基础知识(一)
  • 面向局部遮挡场景的目标检测系统设计与实现