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
相关产品推荐
相关产品推荐

