在Spring Boot项目中,Thymeleaf是一个非常流行的模板引擎,它允许开发者以声明式的方式在HTML页面中嵌入Java代码。使用Thymeleaf处理表单提交List数据是一种常见的需求,下面将详细解析如何实现这一功能。
1. 准备工作
首先,确保你的Spring Boot项目中已经包含了Thymeleaf的依赖。
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. 创建数据模型
在Spring Boot项目中,我们通常使用POJO(Plain Old Java Object)来表示数据模型。假设我们需要提交一个包含多个用户信息的列表,首先创建一个User类。
public class User {
private String name;
private int age;
// 省略getter和setter方法
}
然后创建一个用于存储用户列表的类。
public class UserListForm {
private List<User> users;
// 省略getter和setter方法
}
3. 创建表单页面
在Thymeleaf模板中,使用表单标签 <form> 来创建表单,并使用th:object属性绑定到数据模型。
<!-- users.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>用户列表表单</title>
</head>
<body>
<form th:action="@{/submitForm}" th:object="${userListForm}" method="post">
<div th:each="user, userStat : *{users}">
<label for="name">用户名:</label>
<input type="text" id="name" name="users[+{userStat.index}].name" th:value="*{user.name}"/>
<label for="age">年龄:</label>
<input type="number" id="age" name="users[+{userStat.index}].age" th:value="*{user.age}"/>
<button type="button" onclick="removeUser(this)">移除用户</button>
</div>
<button type="button" onclick="addUser()">添加用户</button>
<input type="submit" value="提交"/>
</form>
<script>
function addUser() {
var users = document.getElementsByName("users[]");
var userCount = users.length;
var nameInput = document.createElement("input");
nameInput.type = "text";
nameInput.name = "users[" + userCount + "].name";
nameInput.id = "name" + userCount;
var ageInput = document.createElement("input");
ageInput.type = "number";
ageInput.name = "users[" + userCount + "].age";
ageInput.id = "age" + userCount;
var removeButton = document.createElement("button");
removeButton.type = "button";
removeButton.onclick = function() {
removeUser(this);
};
removeButton.textContent = "移除用户";
var div = document.createElement("div");
div.appendChild(nameInput);
div.appendChild(ageInput);
div.appendChild(removeButton);
document.querySelector("form").appendChild(div);
}
function removeUser(button) {
var div = button.parentNode;
div.parentNode.removeChild(div);
}
</script>
</body>
</html>
在这个例子中,我们使用JavaScript来动态添加和移除用户输入框。
4. 处理表单提交
在控制器中,创建一个方法来处理表单提交。
@RestController
public class UserController {
@PostMapping("/submitForm")
public String submitForm(@Valid @ModelAttribute UserListForm userListForm) {
// 处理提交的数据
return "提交成功";
}
}
5. 总结
通过以上步骤,我们使用Thymeleaf创建了一个可以提交用户列表的表单。在模板中,我们使用Thymeleaf表达式来绑定数据模型,并通过JavaScript来动态地添加和移除用户输入框。控制器端则接收这些数据并处理。
这种方式使得表单数据的提交和处理变得简单而灵活,非常适合在Spring Boot项目中使用。
