Thymeleaf项目点击按钮按ID更新数据库status字段为1的实现方案咨询
解决方案
完全可以通过点击按钮触发实现该需求,你现有代码的核心问题有两个:
- 全局仅包裹了一个form表单,提交时无法传递当前行对应的订单ID
- 表单提交路径与Controller定义的接口路径不匹配,且原生HTML form默认不支持PUT方法,需要额外配置适配
1. 修改后的HTML代码
删除全局的form标签,改为每行操作列单独绑定对应订单的提交表单:
<table> <tr th:each="p : ${GetOrder}"> <td th:text="${p.getName()}"></td> <td th:text="${p.getSecondName()}"></td> <td th:text="${p.getAddress()}"></td> <td th:text="${p.getApartment()}"></td> <td th:text="${p.getPhoneNumber()}"></td> <td th:text="${p.getOrderPrice()}"></td> <td th:text="${p.getCity()}"></td> <td> <span style="color: green" th:if="${p.getStatus() == '1'}">Delivered</span> <span style="color: red" th:if="${p.getStatus() == '0'}">Not Delivered</span> </td> <td> <!-- 每个订单对应单独表单,传递当前订单ID --> <form th:action="@{/managment/order/{id}(id=${p.getId()})}" method="post"> <!-- 如果要使用PUT方法提交,保留下面的隐藏域,需要额外开启Spring配置 --> <!-- <input type="hidden" name="_method" value="put"> --> <input type="submit" value="✓" th:disabled="${p.getStatus() == '1'}"/> </form> </td> </tr> </table>
2. 修改后的Controller代码
补全更新业务逻辑,提交后重定向回列表页刷新数据,避免重复提交:
@Controller @RequestMapping("/managment") public class Managment { @Autowired private PurchaseDataService purchaseDataService; @Autowired private OrderInterface orderInterface; @GetMapping("/order") public String goToOrderList(Model model){ List<Purchases> allStats = purchaseDataService.getAllStats(); model.addAttribute("GetOrder", allStats); return "OrderManagment"; } // 如使用PUT方法,将@PostMapping改为@PutMapping即可 @PostMapping("/order/{id}") public String updateInfo(@PathVariable(value = "id") Integer orderId){ // 按ID查询对应订单 Purchases order = orderInterface.findById(orderId) .orElseThrow(() -> new IllegalArgumentException("无效订单ID:" + orderId)); // 更新status字段为1 order.setStatus("1"); // 保存更新后的数据 orderInterface.save(order); // 重定向到列表页刷新最新状态 return "redirect:/managment/order"; } }
注意事项
- 确保
Purchases实体类存在getId()、setStatus()方法,OrderInterfaceRepository接口已定义findById、save方法 - 如果要使用PUT方法提交,需要在
application.properties中开启HiddenHttpMethodFilter配置:spring.mvc.hiddenmethod.filter.enabled=true - 提交按钮增加了
th:disabled属性,已交付的订单无法重复点击提交,避免无效请求
内容的提问来源于stack exchange,提问作者Peetkovski
相关产品推荐
相关产品推荐

