Spring Security集成Thymeleaf注册报错rawPassword cannot be null如何解决?
问题根因
本次报错和@RestController、@Controller的注解差异无直接关联,核心是@ModelAttribute的参数绑定规则和@RequestBody不同,常见触发原因如下:
- @ModelAttribute默认通过Setter方法注入属性值,你仅确认了RegistrationRequest存在Getter方法,大概率缺失对应属性的Setter方法:之前@RequestBody接收JSON参数时,Jackson序列化框架可通过反射直接给属性赋值,无需Setter也能正常运行,替换为@ModelAttribute后没有Setter就会导致属性绑定失败,password属性为null。
- 表单配置错误:密码输入框的
th:field属性值和RegistrationRequest的password属性名大小写不匹配、表单未声明method="post"、错误设置了multipart/form-data类型的enctype都会导致参数解析失败。 - GET请求返回注册页时未给Model注入空的RegistrationRequest对象,导致Thymeleaf的
th:object绑定失效,表单提交的参数无法正常映射到实体类。
修复方案
按优先级依次排查修复即可:
- 给RegistrationRequest类的所有属性补全Setter方法,也可直接加Lombok的
@Data注解一键生成Getter、Setter、toString等通用方法,这是最高概率的修复方案。 - 确认GET注册页接口正常注入空实体对象,示例代码:
@GetMapping("/register") public String getRegisterPage(Model model) { model.addAttribute("registrationRequest", new RegistrationRequest()); return "register"; // 对应你的注册页视图名 }
- 检查Thymeleaf注册表单的配置,确保参数绑定正确,示例结构:
<form th:action="@{/register}" th:object="${registrationRequest}" method="post"> <div> <label>餐厅名称:</label> <input type="text" th:field="*{restaurantName}"> </div> <div> <label>邮箱:</label> <input type="email" th:field="*{email}"> </div> <div> <label>密码:</label> <input type="password" th:field="*{password}"> </div> <button type="submit">提交注册</button> </form>
- 临时加日志调试:在Post注册接口的第一行打印RegistrationRequest的所有属性值,确认是只有password为null还是所有属性都为空,进一步缩小排查范围。
内容的提问来源于stack exchange,提问作者Bronwyn Young
相关产品推荐
相关产品推荐

