SpringBoot 集成 Thymeleaf 简洁入门

1. 引言

Thymeleaf 是 SpringBoot 官方推荐的模板引擎,语法简洁、与 HTML 完美融合,非常适合快速开发服务端渲染页面。本文用最少的篇幅带你跑通一个 Thymeleaf 示例。

2. 引入依赖

在 pom.xml 中添加:

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

3. 目录结构

模板文件默认放在 src/main/resources/templates/ 下,静态资源放在 static/ 下。

复制代码
src/main/resources/
├── static/
└── templates/
    └── index.html

4. 编写控制器

java 复制代码
@Controller
public class HelloController {

    @GetMapping("/")
    public String index(Model model) {
        model.addAttribute("name", "SpringBoot");
        return "index";
    }
}

5. 编写模板

html 复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
    <h1 th:text="'Hello, ' + ${name}">Hello</h1>
</body>
</html>

6. 常用语法

  • 取值 :th:text="${name}"
  • 条件 :th:if="${condition}"
  • 循环 :th:each="item : ${list}"
  • 链接 :th:href="@{/path}"

7. 用法总结

7.1 标准表达式

  • 变量表达式 :${name},等价于 model.addAttribute("name", ...) 中的取值。
  • 选择表达式 :*{field},配合 th:object 使用,直接取当前对象的属性。
  • 链接表达式 :@{/path},自动拼接上下文路径,支持参数如 @{/user/{id}(id=${user.id})}。
  • 消息表达式 :#{msg},读取国际化资源文件中的文案。

7.2 常用属性

属性 作用 示例
th:text 输出文本 th:text="${name}"
th:if 条件判断 th:if="${user != null}"
th:unless 条件取反 th:unless="${user.admin}"
th:each 循环遍历 th:each="item : ${list}"
th:href 生成链接 th:href="@{/detail/{id}(id=${item.id})}"
th:src 图片地址 th:src="@{/img/logo.png}"
th:class 动态样式 th:class="${active ? 'on' : 'off'}"
th:object 绑定对象 th:object="${user}"

7.3 内联写法

不想写标签属性时,可用 [[${name}]] 直接输出变量,适合在 <script> 或文本中混用。

7.4 片段复用

用 th:fragment 定义公共片段,用 th:replace 或 th:insert 引入,实现页面组件化复用。

7.5 小结

掌握表达式、常用属性、内联与片段复用这四块,就能覆盖绝大多数 Thymeleaf 开发场景。配合 SpringBoot 的自动配置,无需额外 XML 配置即可开箱即用。

相关推荐
驭渊的小故事2 小时前
Spring AI Alibaba 实战:从maven依赖治理到声明式工具调用
java·人工智能·spring
Elastic 中国社区官方博客3 小时前
我们如何通过 70 多个拉取请求,将 OpenTelemetry Java agent 迁移到 invokedynamic
java·大数据·开发语言·elasticsearch·搜索引擎·全文检索·es
tyn1883 小时前
记录本地安装nacos服务的方法及异常
java·开发语言
步行cgn4 小时前
Spring MVC 视图机制的核心接口与类
java·开发语言·后端·spring·mvc
y1su4 小时前
Leetcode 字符串模板
java·数据结构·算法·leetcode·职场和发展·动态规划
码事漫谈4 小时前
AI 读你的提示词,其实很没耐心
后端
用户8356290780515 小时前
如何使用 Python 格式化 Excel 单元格中的长文本
后端·python
我命由我123455 小时前
Python 开发 - Python 的 pathlib
java·开发语言·后端·python·学习·java-ee·学习方法
IT_陈寒5 小时前
Java性能优化完全指南
前端·人工智能·后端