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

Spring Boot中Thymeleaf跨方法传值出现Null值的问题求助

问题分析与解决方案

问题根源

  • model.addAttribute("email", email) 将数据存入请求作用域,仅用于渲染当前的NewPass页面;当提交表单发起新的POST请求到/newpass时,原请求作用域的参数不会自动传递。
  • Thymeleaf表单中未包含email的输入字段,提交表单时不会把email值发送到后端,导致@ModelAttribute("email") String email获取到null。

修复步骤

1. 在Thymeleaf表单中添加隐藏字段传递email

修改NewPass页面的表单,增加隐藏输入框,将email作为表单参数一起提交:

<form th:action="@{/newpass}" method="post" >
    <h2 class="text-center">New Password</h2>
    <div class="alert alert-success text-center" th:text="${email}"></div>
    <div class="alert alert-danger text-center"></div>
    <!-- 新增隐藏字段传递email -->
    <input type="hidden" th:value="${email}" name="email">
    <div class="form-group">
        <input class="form-control" type="password" name="password" placeholder="Create new password" required th:field="*{pass}">
    </div>
    <div class="form-group">
        <input class="form-control" type="password" name="cpassword" placeholder="Confirm your password" required>
    </div>
    <div class="form-group">
        <input class="form-control button" type="submit" name="change-password" value="Change">
    </div>
</form>

2. 调整Controller参数接收方式

改用@RequestParam接收表单提交的参数(参数名需与表单中name属性一致):

@PostMapping("/newpass")
public String newPass(@RequestParam("email") String email, @RequestParam("password") String pass ){
    userServices.updatePass(email,pass);
    return "Home";
}

额外优化建议

创建专门的重置密码DTO类,规范参数绑定:

public class ResetPasswordDTO {
    private String email;
    private String password;
    private String confirmPassword;
    
    // 生成getter、setter方法
}

Controller方法调整为:

@PostMapping("/newpass")
public String newPass(@ModelAttribute ResetPasswordDTO resetPasswordDTO){
    // 可先校验password与confirmPassword是否一致
    userServices.updatePass(resetPasswordDTO.getEmail(), resetPasswordDTO.getPassword());
    return "Home";
}

Thymeleaf表单对应修改:

<input class="form-control" type="password" placeholder="Create new password" required th:field="*{password}">
<input class="form-control" type="password" placeholder="Confirm your password" required th:field="*{confirmPassword}">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 23:31:23