在Thymeleaf中显示模型对象通常是通过表单来实现的,但确实存在一些更高效或者更灵活的方法来处理这个问题。以下是一些基础概念和相关优势:
以下是一个使用Thymeleaf显示模型对象的简单示例:
@Controller
public class FormController {
@GetMapping("/form")
public String showForm(Model model) {
User user = new User();
user.setName("John Doe");
user.setEmail("john.doe@example.com");
model.addAttribute("user", user);
return "form";
}
@PostMapping("/form")
public String submitForm(@ModelAttribute User user, Model model) {
// 处理表单提交
model.addAttribute("user", user);
return "result";
}
}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Form</title>
</head>
<body>
<form action="#" th:action="@{/form}" th:object="${user}" method="post">
<label for="name">Name:</label>
<input type="text" th:field="*{name}" id="name"/>
<br/>
<label for="email">Email:</label>
<input type="text" th:field="*{email}" id="email"/>
<br/>
<button type="submit">Submit</button>
</form>
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Result</title>
</head>
<body>
<p>Name: <span th:text="${user.name}"></span></p>
<p>Email: <span th:text="${user.email}"></span></p>
</body>
</html>
通过上述方法,可以有效地在Thymeleaf中显示和处理模型对象,提高开发效率和代码质量。
领取专属 10元无门槛券
手把手带您无忧上云