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

Thymeleaf表单POST提交如何将选中导师ID传递到Spring Controller

问题原因

你遇到的参数传递失败问题是由两个核心错误导致的:

  1. 参数名不匹配:表单提交的隐藏字段是导师的id,但Controller POST方法接收的参数名是mentorid,SpringMVC无法匹配到对应参数就会报错。
  2. 表单绑定逻辑冗余:你在循环渲染导师列表时用了全局的空User对象作为绑定目标,没有正确使用当前遍历的导师对象属性。

修复步骤

1. 修改HTML页面的表单逻辑

直接去掉无用的th:object绑定,显式指定参数名和值,和Controller接收参数对应即可:

<tbody>
    <tr th:each="mentor : ${listUsers}">
        <td th:text="${mentor.firstName}">First Name</td>
        <td th:text="${mentor.lastName}">Last Name</td>
        <td th:text="${mentor.age}">Age</td>
        <td th:text="${mentor.email}">Email</td>
        <td>
            <form th:action="@{/trainers/choose}" method="post">
                <!-- 直接给隐藏域指定参数名mentorid,值为当前遍历导师的id -->
                <input type="hidden" name="mentorid" th:value="${mentor.id}" />
                <button type="submit">选择</button> 
            </form>
        </td>
    </tr>
</tbody>

没用的getUser AJAX方法可以直接删掉,避免逻辑干扰。

2. 清理GET接口冗余代码

渲染页面时添加的空User对象完全没用,直接删除即可:

@GetMapping("/trainers")
public String listTrainers(Model model) {
    List<User> listUsers = userRepo.findAllByRole(userRoleRepo.findByName("ROLE_MENTOR"));
    model.addAttribute("listUsers", listUsers); 
    return "trainers";
}

3. 完善POST接口逻辑

如果需要关联当前登录的普通用户,可以直接从Spring Security上下文获取当前登录用户id,更新其mentorid字段即可:

@PostMapping("/trainers/choose")
public String processTrainersChoose (@RequestParam Long mentorid) {
    // 示例逻辑:获取当前登录普通用户→更新其导师id→保存到数据库
    User currentUser = // 从Security上下文获取当前登录用户
    currentUser.setMentorid(mentorid);
    userRepo.save(currentUser);
    return "redirect:/personal-center"; // 跳转至个人中心或成功页
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 09:57:03