spring thymeleaf - 从 html 表中删除对象并将 id 传递给控制器

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)

我怎样才能使这项工作?或者还有其他方法吗?

谢谢!

Tan*_*dal 7

您可以尝试将 更改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)

  • 使用 method=GET 删除用户,这是一个好习惯吗? (3认同)
  • @user641887 实际上,这里不是通过GET 方法删除用户,而是使用GET 方法传递一个id,删除操作可能是使用某些POST 方法Web 服务执行的。 (2认同)