在 Spring Boot 中,使用 Thymeleaf 模板进行数据绑定主要包括以下几个步骤:
添加依赖首先,确保你的项目中已经添加了 Thymeleaf 和 Spring Boot 相关的依赖。在 pom.xml 文件中添加以下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>创建 Controller创建一个 Controller 类,用于处理 HTTP 请求并返回 Thymeleaf 模板。例如,创建一个名为 UserController 的类:
import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/user")public class UserController { @GetMapping("/form") public String showForm(Model model) { model.addAttribute("user", new User()); return "userForm"; } @PostMapping("/submit") public String submitForm(@ModelAttribute User user) { // 处理提交的数据,例如保存到数据库 System.out.println("User: " + user); return "userResult"; }}创建实体类创建一个实体类,例如 User,用于存储表单数据:
public class User { private String name; private int age; // getter 和 setter 方法 // ... @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + '}'; }}创建 Thymeleaf 模板在 src/main/resources/templates 目录下创建两个 Thymeleaf 模板文件:userForm.html 和 userResult.html。
userForm.html:
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <title>User Form</title></head><body> <h1>User Form</h1> <form action="#" th:action="@{/user/submit}" th:object="${user}" method="post"> <label for="name">Name:</label> <input type="text" id="name" th:field="*{name}" /> <br/> <label for="age">Age:</label> <input type="number" id="age" th:field="*{age}" /> <br/> <input type="submit" value="Submit" /> </form></body></html>userResult.html:
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <title>User Result</title></head><body> <h1>User Result</h1> <p th:text="'Name: ' + ${user.name}"></p> <p th:text="'Age: ' + ${user.age}"></p></body></html>运行应用程序运行你的 Spring Boot 应用程序,然后访问 http://localhost:8080/user/form,你将看到一个表单,可以输入用户信息。提交表单后,将显示用户信息。这就是在 Spring Boot 中使用 Thymeleaf 模板进行数据绑定的基本过程。


