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

Spring-Thymeleaf页面提交ID为空触发IllegalArgumentException异常求助

解决"The given id must not be null!"异常问题

这个异常的核心原因很明确:你点击按钮提交时,没有把对应行的计算器结果ID传递给后端,导致后端接收的CalculatorResult对象里id为null,调用calculatorRepository.findOne(calcResults.getId())时自然触发了非法参数异常。

我们来拆解下代码里的问题:

前端Thymeleaf的问题

你的整个表格都包裹在一个绑定了th:object="${calcResults}"的form里,但calcResults是后端传过来的列表集合,不是单条CalculatorResult数据。当你点击任意一行的提交按钮时,表单根本没有携带当前行的id值,后端自然拿不到有效ID。

后端控制器的问题

@PostMapping("/show")里用@ModelAttribute(value = "calcResults")接收参数,但这个参数名和你传递的列表名重复了,而且你实际只需要单条数据的ID来查询详情,不需要接收整个列表对象。


解决方案

这里给你两种可行的修改方案,选一种适合你的即可:

方案1:用表单+隐藏域传递ID(保持POST请求)

修改前端页面的表格行部分,给每行单独创建表单,通过隐藏域携带当前行的ID:

<tr th:each = "calc : ${calcResults}">
    <td th:text="${calc.id}"></td>
    <td th:text="${#dates.format(calc.dataWyjazdu, 'dd-MM-yyyy')}"></td>
    <td th:text="${#dates.format(calc.dataPrzyjazdu, 'dd-MM-yyyy')}"></td>
    <td>
        <form th:action="@{/show}" method="post">
            <!-- 隐藏域传递当前行的ID -->
            <input type="hidden" th:name="id" th:value="${calc.id}"/>
            <button type="submit" class="btn btn-success btn-xs">Przelicz</button>
        </form>
    </td>
</tr>

然后修改后端控制器,直接接收ID参数:

@PostMapping("/show")
public String showDetails(@RequestParam("id") Long id, Model model){
    System.out.println(id);
    // 查询单条数据,注意把model属性名改成单数,避免和列表混淆
    model.addAttribute("calcResult", calculatorRepository.findOne(id));
    return "user/show";
}

方案2:用GET请求+URL路径传参(更符合REST语义)

因为只是查询详情,用GET请求更合适,你可以把按钮改成a标签:

<tr th:each = "calc : ${calcResults}">
    <td th:text="${calc.id}"></td>
    <td th:text="${#dates.format(calc.dataWyjazdu, 'dd-MM-yyyy')}"></td>
    <td th:text="${#dates.format(calc.dataPrzyjazdu, 'dd-MM-yyyy')}"></td>
    <td>
        <a th:href="@{/show/{id}(id=${calc.id})}" class="btn btn-success btn-xs">Szczegóły</a>
    </td>
</tr>

后端改成路径变量接收ID:

@GetMapping("/show/{id}")
public String showDetails(@PathVariable("id") Long id, Model model){
    System.out.println(id);
    model.addAttribute("calcResult", calculatorRepository.findOne(id));
    return "user/show";
}

不管选哪种方案,核心都是确保后端能接收到选中行的有效ID,这样就不会再触发id must not be null的异常了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:46:53