在 spring boot 中集成 thymeleaf 只需引入 spring-boot-starter-thymeleaf 依赖,无需额外配置视图解析器;模板默认放在 src/main/resources/templates/ 下,后缀为 .html;controller 返回逻辑视图名(如 "index")即可映射到对应模板,并支持通过 model 传递数据。

在 Spring Boot 中集成 Thymeleaf 渲染服务端页面非常简单,核心是引入依赖、配置视图解析器(Spring Boot 默认已自动配置)、编写 Controller 返回逻辑视图名,并在 src/main/resources/templates 下放置 HTML 模板文件。
添加 Thymeleaf 依赖
确保 pom.xml 中包含 Thymeleaf Starter:
- 使用 Maven 的话,加入以下依赖(Spring Boot 2.4+ 推荐用
spring-boot-starter-thymeleaf):
无需额外配置,Spring Boot 会自动装配 Thymeleaf 的 TemplateResolver、TemplateEngine 和 ThymeleafViewResolver。
准备模板文件
Thymeleaf 默认查找路径为 src/main/resources/templates/(classpath 下的 templates 目录),文件后缀为 .html。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 例如:创建
src/main/resources/templates/index.html - 模板中使用标准 Thymeleaf 语法,如
th:text、th:each、th:href等 - 注意:HTML 文件必须是合法的 XML/HTML 结构,避免自闭合标签(如
<img>应写成<img>)
编写 Controller 返回视图
Controller 方法返回字符串(逻辑视图名),不带路径和后缀,Spring Boot 自动映射到 templates/xxx.html:
- 例如返回
"index"→ 对应templates/index.html - 可传入模型数据,用
Model或ModelMap:
public String home(Model model) {
model.addAttribute("message", "Hello from Thymeleaf!");
return "index";
}
模板中通过 th:text="${message}" 输出。
可选:自定义 Thymeleaf 配置
如需调整行为(开发时禁用缓存、修改前缀/后缀等),可在 application.yml 中配置:
thymeleaf:
cache: false # 开发时建议关闭
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
mode: HTML
注意:Thymeleaf 3.x 默认使用 HTML 模式(更宽松),无需再设 XHTML。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










