Spring Boot集成Thymeleaf:快速上手指南
1. 添加依赖
首先,需要在pom.xml文件中添加Thymeleaf的依赖。Spring Boot提供了spring-boot-starter-thymeleaf模块,它包含了Thymeleaf的核心依赖和自动配置。
<dependencies>
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Thymeleaf Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2. 创建模板文件
Thymeleaf模板文件默认存放在src/main/resources/templates目录下。创建一个HTML文件作为模板,例如index.html。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Example</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'"></h1>
</body>
</html>
-
xmlns:th="http://www.thymeleaf.org":声明Thymeleaf命名空间,允许使用Thymeleaf的属性。 -
${name}:从模型中获取变量name的值。
3. 创建Controller
在Spring Boot项目中,需要创建一个Controller来处理请求,并将数据传递到模板。
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 ThymeleafController {
@GetMapping("/")
public String index(Model model) {
// 添加模型数据
model.addAttribute("name", "World");
// 返回模板名称
return "index";
}
}
-
@Controller:声明这是一个控制器。 -
@GetMapping("/"):定义一个GET请求的处理方法。 -
model.addAttribute("name", "World"):将变量name添加到模型中。 -
return "index":返回模板名称(不带.html后缀),Spring Boot会自动从templates目录下查找对应的文件。
4. 配置Thymeleaf(可选)
如果需要自定义Thymeleaf的配置,可以在application.properties或application.yml文件中添加相关配置。
示例:application.properties
# 模板前缀和后缀
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
# 是否启用缓存(开发环境下建议关闭)
spring.thymeleaf.cache=false
# 是否启用HTML5模式
spring.thymeleaf.mode=HTML5
5. 启动项目
启动Spring Boot应用后,访问http://localhost:8080/,应该会看到页面显示Hello, World!。
6. 其他Thymeleaf功能
Thymeleaf支持多种功能,例如条件判断、循环、表单绑定等。以下是一些常用功能的示例:
条件判断
<div th:if="${name == 'World'}">
<p>Welcome,Worldi!</p>
</div>
循环
<ul>
<li th:each="item : ${list}" th:text="${item}"></li>
</ul>
表单绑定
<form th:action="@{/submit}" method="post">
<input type="text" th:field="${user.name}" />
<input type="submit" value="Submit" />
</form>
浙公网安备 33010602011771号