我是 Thymeleaf 的新手。我正在尝试创建简单的 CRUD 应用程序。我正在尝试通过删除按钮删除客户类的对象。如何使用 Thymeleaf 将参数(例如 - id)设置为调用 deleteUser 的方法。这是我的控制器。
package controllers;
//imports
@Controller
public class WebController extends WebMvcConfigurerAdapter {
@Autowired
private CustomerDAO customerDAO;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
//show all users
@RequestMapping(value="/users", method=RequestMethod.GET)
public String contacts(Model model) {
model.addAttribute("users",customerDAO.findAll());
return "list";
}
//show form
@RequestMapping(value="/users/add", method=RequestMethod.GET)
public String showForm(Customer customer) {
return "form";
}
//add user
@RequestMapping(value="/users/doAdd", method=RequestMethod.POST)
public String addUser(@RequestParam("firstName") String firstName,
@RequestParam("lastName") String lastName,
@RequestParam("lastName") String email) {
customerDAO.save(new Customer(firstName, lastName, email));
return "redirect:/users";
}
//delete user
@RequestMapping(value="users/doDelete/{id}", method = RequestMethod.POST)
public String deleteUser (@PathVariable Long id) {
customerDAO.delete(id);
return "redirect:/users";
}
}
这是我的观点。
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
List of users
<a href="users/add">Add new user</a>
<table>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Action</th>
</tr>
<tr th:each="user : ${users}">
<td th:text="${user.id}">Id</td>
<td th:text="${user.firstName}">First name</td>
<td th:text="${user.lastName}">Last Name</td>
<td th:text="${user.email}">Email</td>
<td>
<form th:action="@{/users/doDelete/}" th:object="${customer}" method="post">
<button type="submit">Delete</button>
</form>
</td>
</tr>
</table>
</body>
</html>
您不需要表格来执行此操作:
<td>
<a th:href="@{'/users/doDelete/' + ${user.id}}">
<span>Delete</span>
</a>
</td>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)