You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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()方法,OrderInterface Repository接口已定义findById、save方法
  • 如果要使用PUT方法提交,需要在application.properties中开启HiddenHttpMethodFilter配置:spring.mvc.hiddenmethod.filter.enabled=true
  • 提交按钮增加了th:disabled属性,已交付的订单无法重复点击提交,避免无效请求

内容的提问来源于stack exchange,提问作者Peetkovski

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 19:06:03