springboot + thymeleaf
时间: 2025-05-21 10:41:24 浏览: 11
### Spring Boot与Thymeleaf集成指南
Spring Boot 提供了一个开箱即用的解决方案来简化 Thymeleaf 的集成过程。通过引入 `spring-boot-starter-thymeleaf` 依赖项,可以快速实现模板引擎的功能支持[^1]。
#### 添加依赖
为了启用 Thymeleaf 支持,在项目的构建文件中添加以下 Maven 或 Gradle 配置:
对于 Maven 用户:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
对于 Gradle 用户:
```gradle
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
```
此依赖会自动配置 Thymeleaf 并将其注册到 Spring 容器中[^4]。
#### 创建控制器
创建一个简单的控制器用于处理 HTTP 请求并返回视图名称。例如:
```java
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello from Thymeleaf!");
return "hello"; // 返回名为 "hello" 的 Thymeleaf 模板
}
}
```
在此示例中,当访问 `/hello` 路径时,模型中的数据会被传递给 Thymeleaf 模板渲染[^3]。
#### 编写 Thymeleaf 模板
默认情况下,Spring Boot 将寻找位于 `src/main/resources/templates/` 文件夹下的 HTML 文件作为 Thymeleaf 模板。创建一个名为 `hello.html` 的文件,其内容如下所示:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello Page</title>
</head>
<body>
<h1 th:text="${message}">Default Message</h1>
</body>
</html>
```
在这个例子中,`${message}` 是从控制器传入的数据绑定表达式[^5]。
#### 启动应用程序
确保项目根目录下存在启动类,并标注有 `@SpringBootApplication` 注解。运行该程序后即可测试功能正常与否[^3]。
---
阅读全文
相关推荐


















