在Thymeleaf中设置表单,你可以使用Thymeleaf的标签来创建表单,并利用Thymeleaf的表达式绑定模型数据。以下是一个简单的例子:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Form Example</title>
</head>
<body>
<form th:action="@{/submitForm}" th:object="${formBean}" method="post">
<label for="name">Name:</label>
<input type="text" id="name" th:field="*{name}" />
<label for="email">Email:</label>
<input type="email" id="email" th:field="*{email}" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
在这个例子中:
-
th:action
设置表单提交的URL。 -
th:object
设置表单绑定的模型对象。 -
th:field
在输入字段中设置属性,以绑定到对象的属性。
假设你有一个名为FormBean
的Java类,它有name
和email
属性,你需要在控制器中设置这个模型对象,以便它可以在Thymeleaf模板中使用。例如:
@Controller
public class FormController {
@GetMapping("/form")
public String showForm(Model model) {
FormBean formBean = new FormBean();
model.addAttribute("formBean", formBean);
return "form"; // 返回对应的Thymeleaf模板名称
}
@PostMapping("/submitForm")
public String submitForm(@ModelAttribute FormBean formBean) {
// 处理表单提交逻辑
return "result";
}
}
在这个例子中,当显示表单时,showForm
方法创建了一个FormBean
实例并将其添加到模型中。用户填写表单并提交时,submitForm
方法会被调用,并接收填写的表单数据。