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

新手上路,请多包涵

我将一个包含对象的列表从我的控制器传递到我的 html,thymeleaf 为列表中的每个对象创建一个。

我想通过一个按钮删除一个条目并将对象 ID 传递给我的控制器以便从数据库中删除它。

但是,当我在控制器中处理发布请求时,id 属性为空。

带有 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>

控制器:

 @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";
}

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

谢谢!

原文由 cmplx96 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 428
2 个回答

您可以尝试将 th:action="@{delete_user}" 更改为 th:action="@{/delete_user}" 。或者您可以使用路径变量/查询字符串并使用 get 方法传递 id。例如 html:

 <a th:href="|@{/delete_user/${user.personId}}|" class="btn btn-danger">Delete</a>

控制器:

 @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";
}

要么

HTML:

 <a th:href="@{/delete_user(personId=${user.personId})}" class="btn btn-danger">Delete</a>

控制器:

 @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";
}

原文由 Tanmoy Mandal 发布,翻译遵循 CC BY-SA 3.0 许可协议

下面是视图部分。

 <tbody>
<tr th:each="income : ${incomes}">
<td th:text="${income.createDate}"></td>
<td th:text="${income.name}"></td>
<td th:text="${income.description}"></td>
<td th:text="${income.amount}"></td>
<td><a th:href="@{/income/edit/{id}(id=${income.id})}" class="btn btn-primary"><i class="fas fa-user-edit ml-2"></i></a></td>
<td><a th:href="@{/income/delete/{id}(id=${income.id})}" class="btn btn-primary"><i class="fas fa-user-times ml-2"></i></a></td>
</tr>
</tbody>

下面是控制器

@GetMapping("/delete/{id}")
public String deleteIncome(@PathVariable(value = "id") Long id,Model model) {
    Income note = incomeRepo.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException("Income", "id", id));
    incomeRepo.delete(note);
    model.addAttribute("incomes",incomeRepo.findAll());
    return "viewIncome";
}

在上面视图部分的代码中,我将 id 传递给控制器。然后在controller中通过查找id,删除相关记录。

原文由 Senthuran 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题