Spring Thymeleaf 是一个用于 Web 开发的框架组合,其中 Spring 是一个全面的 Java 应用程序框架,而 Thymeleaf 是一个现代的服务器端 Java 模板引擎,用于 Web 和独立环境。Thymeleaf 的模板语法非常简单,并且它允许开发者使用自然的 HTML 格式来编写模板。
Html 表单是 Web 开发中常用的元素,用于收集用户输入的数据。Crud 操作(Create, Read, Update, Delete)是数据库操作的基本操作,用于管理数据。
适用于任何需要通过 Web 界面进行数据管理的应用,例如:
以下是一个简单的 Spring Thymeleaf Html 表单 + Crud 操作的示例:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public String listUsers(Model model) {
model.addAttribute("users", userRepository.findAll());
return "user/list";
}
@GetMapping("/new")
public String newUser(Model model) {
model.addAttribute("user", new User());
return "user/form";
}
@PostMapping
public String saveUser(@ModelAttribute User user) {
userRepository.save(user);
return "redirect:/users";
}
@GetMapping("/{id}/edit")
public String editUser(@PathVariable Long id, Model model) {
model.addAttribute("user", userRepository.findById(id).orElse(null));
return "user/form";
}
@GetMapping("/{id}/delete")
public String deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
return "redirect:/users";
}
}
list.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User List</title>
</head>
<body>
<h1>User List</h1>
<a th:href="@{/users/new}">Add New User</a>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
<td>
<a th:href="@{/users/{id}/edit(id=${user.id})}">Edit</a>
<a th:href="@{/users/{id}/delete(id=${user.id})}">Delete</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
form.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Form</title>
</head>
<body>
<h1>User Form</h1>
<form th:action="@{/users}" method="post" th:object="${user}">
<input type="hidden" th:field="*{id}" />
<label for="name">Name:</label>
<input type="text" th:field="*{name}" id="name" />
<label for="email">Email:</label>
<input type="email" th:field="*{email}" id="email" />
<button type="submit">Save</button>
</form>
</body>
</html>
原因:可能是控制器中的保存逻辑有误,或者数据库连接配置有问题。
解决方法:
原因:可能是表单字段验证规则设置不正确,或者验证逻辑有误。
解决方法:
原因:可能是 Thymeleaf 模板语法错误,或者模板文件路径配置有误。
解决方法:
希望以上信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云