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

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.xdnf.cn/news/17833.html

相关文章:

  • 数据结构初阶(12)排序算法—插入排序(插入、希尔)(动图演示)
  • 基于R语言的现代贝叶斯统计学方法(贝叶斯参数估计、贝叶斯回归、贝叶斯计算实践过程
  • 为什么 sim(3) 中的尺度 s 与旋转 R 相乘,而不是平移 t?
  • CMake笔记:配置(Configure)、生成(Generate)和构建(Build)
  • 猿大师中间件:Chrome网页内嵌PhotoShop微信桌面应用程序
  • php7 太空船运算符
  • opencv:直方图
  • 【车联网kafka】Kafka核心架构与实战经验(第四篇)
  • mapbox进阶,实现精灵图生成和拆分(小图任意大小,不固定),并简单使用
  • Laravel 使用ssh链接远程数据库
  • 第十六届蓝桥杯青少组C++省赛[2025.8.9]第二部分编程题(1 、庆典队列)
  • 【Java基础|第十八篇】面向对象(八)——包装类
  • Docker安装influxdb以及python基本操作
  • 微店平台平台关键字搜索接口实战:从精准检索到智能推荐实现
  • JetPack系列教程(六):Paging——让分页加载不再“秃”然
  • 职场与生活如何在手机中共存?(二)
  • aliases 的意义和作用?
  • Harmony OS 开发入门 第三章
  • 四、深入剖析Java程序逻辑控制:从字节码到性能优化
  • Android 双屏异显技术全解析:从原理到实战的多屏交互方案
  • sqli-libs通关教程(51-65)
  • Linux系统编程Day13 -- 程序地址空间(进阶)
  • 18.9 BERT问答模型实战:从数据到部署的完整指南
  • dolphinscheduler 依赖节点不通过
  • 【Spring Boot 3.0 + JDK 17 新手指南:完整用户管理系统】
  • ADB 无线调试连接(Windows + WSL 环境)
  • AI一周事件(2025年8月6日-8月12日)
  • 字符串匹配算法
  • 深度学习——03 神经网络(3)-网络优化方法
  • cisco无线WLC flexconnect配置