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 配置即可开箱即用。

相关推荐
深蓝AI6 小时前
Gemini Decisions API 来了:一次前向打分取代逐字解码,校准误差 0.0250 才是 agent 分支调用的真门槛
人工智能·后端
聪明的笨猪猪6 小时前
Java 工程案例:AI 生成 @Async 异步线程池踩坑
java·经验分享·面试·ai编程
学长毕设6 小时前
基于SpringBoot公务员考试交流平台-附源码
java·spring boot·后端
IT_陈寒7 小时前
Vue的watch把我坑惨了,原来要这样用才靠谱
前端·人工智能·后端
黃芢輝7 小时前
开源实战:基于 Spring Boot 3 + Vue 3 + Redis 的高校选修课管理系统(志愿填报 + 统一抽签)
后端
小雨的AI中台笔记7 小时前
502 还是 503?「无可用渠道」其实只有三个原因
后端
LCG元8 小时前
我让AI重写了这个老系统
后端
吴汐8 小时前
【CRMEB 社区版】二开第一问:这个需求该进 driver,还是进 modules?
后端
新*8 小时前
Elasticsearch 7.17 的 SQL 到底能查到什么?一次踩坑记录
后端·sql·elasticsearch·查询
卷无止境8 小时前
SALib敏感性分析的python库学习笔记
后端·python