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

Spring Boot+Thymeleaf th:each循环内表单提交控制器拿id为null如何解决

问题根因

你原有代码中同时使用th:attr和th:field配置隐藏输入框,th:field会自动生成name、id、value三个属性,你自定义的th:attr="value=..."会被覆盖。同时你的表单绑定的是全局的${laboratorio}对象,如果渲染列表页时该对象没有设置id,th:field读取到的id值默认为空,最终提交给控制器的id就为null。

可行解决方案
  • 方案1:简化表单绑定,移除th:object和th:field,直接指定input的name属性
    把表单部分代码修改为:

    <form th:action="@{/cittadino/selected}" method="post">
        <input class="form-control" type="hidden" name="id" th:value="${element.laboratorio.id}"/>
        <button type="submit">Visualizza</button>
    </form>
    

    控制器无需修改,@ModelAttribute会自动根据input的name="id"匹配Laboratorio类的id属性完成赋值。

  • 方案2:保留th:object绑定,调整绑定对象为当前循环的实验室对象
    把表单部分代码修改为:

    <form th:action="@{/cittadino/selected}" th:object="${element.laboratorio}" th:method="post">
        <input class="form-control" type="hidden" th:field="*{id}"/>
        <button type="submit">Visualizza</button>
    </form>
    

    直接绑定循环中当前的element.laboratorio作为表单对象,th:field会自动读取该对象的id值,无需额外设置value。

  • 方案3:改用GET请求实现跳转(更适合详情页跳转场景)
    无需写form表单,直接用a标签传递id,代码更简洁:

    <a th:href="@{/cittadino/selected/{id}(id=${element.laboratorio.id})}" class="btn">Visualizza</a>
    

    对应修改控制器代码:

    @GetMapping("selected/{id}")
    public String laboratorioSelezionato(@PathVariable Long id, Model model) {
        Laboratorio lab1 = laboratorioRepository.getById(id);
        model.addAttribute("laboratorio",lab1);
        return "laboratorio/indexForUtente";
    }
    

    该方案符合REST接口规范,也避免了表单提交的相关问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:45:01