cmp*_*x96 5 html spring thymeleaf spring-boot
我将一个包含对象的列表从我的控制器传递到我的 html 并且 thymeleaf 为列表中的每个对象创建一个。
我想通过按钮删除一个条目并将对象 id 传递给我的控制器,以便从数据库中删除它。
但是,当我在控制器中处理 post 请求时,id 属性为 emtpy。
带有 Thymeleaf 的 HTML:
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.personId}"></td>
<td th:text="${user.firstName}"></td>
<td th:text="${user.lastName}"></td>
<td>
<form th:action="@{delete_user}" method="post" th:object="${user}">
<input type="hidden" th:field="${user.personId}"/>
<button type="submit" value="Submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)
控制器:
@RequestMapping(value = "/delete_user", method = RequestMethod.POST)
public String handleDeleteUser(@ModelAttribute("user") User user) {
System.out.println(user.getPersonId());
System.out.println("test");
return "redirect:/external";
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能使这项工作?或者还有其他方法吗?
谢谢!
您可以尝试将 更改th:action="@{delete_user}"为th:action="@{/delete_user}"。或者您可以使用路径变量/查询字符串并使用 get 方法传递 id。例如 html:
<a th:href="|@{/delete_user/${user.personId}}|" class="btn btn-danger">Delete</a>
Run Code Online (Sandbox Code Playgroud)
控制器:
@RequestMapping(value = "/delete_user/{personId}", method = RequestMethod.GET)
public String handleDeleteUser(@PathVariable String personId) {
System.out.println(personId);
System.out.println("test");
return "redirect:/external";
}
Run Code Online (Sandbox Code Playgroud)
或者
html:
<a th:href="@{/delete_user(personId=${user.personId})}" class="btn btn-danger">Delete</a>
Run Code Online (Sandbox Code Playgroud)
控制器:
@RequestMapping(value = "/delete_user", method = RequestMethod.GET)
public String handleDeleteUser(@RequestParam(name="personId")String personId) {
System.out.println(personId);
System.out.println("test");
return "redirect:/external";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17279 次 |
| 最近记录: |