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

Spring Boot+Thymeleaf好友系统:第二个隐藏参数无法被@RequestParam获取

问题原因分析

你遇到的MissingServletRequestParameterException是因为Thymeleaf表单中的第二个隐藏字段未正确生成并提交参数,核心问题有两点:

  1. 表单设置了th:object="${friend}",即表单绑定对象为friend,但第二个隐藏字段使用th:field="${customer.id}"时,customer并非当前表单绑定对象,Thymeleaf无法解析该表达式,导致字段的name和value无法正确渲染。
  2. th:field会自动生成name属性,你额外添加的th:attr="name='xxx'"虽能覆盖friend.id对应的name,但对customer.id字段来说,因对象不匹配,th:field本身已失效,最终该字段未被正确提交到后端。
解决方案

方案1:直接用th:name和th:value生成隐藏字段(推荐)

放弃th:field,手动指定字段的name和value,避开表单对象绑定限制:

<form action="#" th:action="@{/home/addFriend}" method="post">
    <input type="hidden" th:name="friendId" th:value="${friend.id}" />
    <input type="hidden" th:name="customerId" th:value="${customer.id}" />
    <input type="submit" value="Add Friend" class="btn btn-primary flex-grow-1" />
</form>

方案2:优化后端逻辑,避免从表单传递当前用户ID(更安全)

当前用户ID可通过@AuthenticationPrincipal直接获取,无需从表单提交,既能避免参数篡改风险,又能简化表单:

修改后端PostMapping代码

@PostMapping("/addFriend")
public String getPost(@RequestParam("friendId") int friendId, @AuthenticationPrincipal MyUserDetails user) {
    Customer friendCustomer = customerService.findById(friendId);
    Customer currCustomer = customerService.findById(user.getCustomer().getId());
    
    System.out.println(currCustomer.getFirstName());
    System.out.println(friendCustomer.getFirstName());
    
    return "redirect:/home";
}

对应简化后的表单代码

<form action="#" th:action="@{/home/addFriend}" method="post">
    <input type="hidden" th:name="friendId" th:value="${friend.id}" />
    <input type="submit" value="Add Friend" class="btn btn-primary flex-grow-1" />
</form>
验证方法

修改后,可通过浏览器开发者工具(F12)查看表单提交的参数,确认friendId和customerId(若保留)均被正确包含在请求中,后端即可正常获取参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:50:37