Spring MVC+Thymeleaf表单验证失效,提交报HTTP 400错误求助
表单验证失效与HTTP 400错误的问题分析及修复
以下是你代码中导致验证失效和400错误的核心问题:
1. BindingResult参数顺序错误
Spring MVC要求**@Valid标注的对象必须紧跟在BindingResult参数之前**,否则Spring无法将验证错误绑定到BindingResult,会直接抛出400错误。
错误代码:
public String postForm( @Valid @ModelAttribute("createForm") StoreDto form, @PathVariable String channelCode, Authentication authentication, BindingResult result, RedirectAttributes redirectAttributes)
修正后:
public String postForm( @Valid @ModelAttribute("createForm") StoreDto form, BindingResult result, @PathVariable String channelCode, Authentication authentication, RedirectAttributes redirectAttributes)
2. FlashAttribute中BindingResult的名称不匹配
你在重定向时存储的BindingResult名称是createRuleSettingForm,但Model中的表单对象名称是createForm,这会导致Thymeleaf无法读取验证错误信息。
错误代码:
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.createRuleSettingForm", result);
修正后:
redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.createForm", result);
3. 实体字段与表单控件名称不匹配(isActive)
StoreDto中的字段是isActive,但表单checkbox的name是active,Thymeleaf绑定会失败,导致参数解析错误(400)。
错误代码(StoreDto):
private boolean isActive=false;
修正后(二选一):
- 方案1:修改StoreDto字段名,保持与表单一致:
private boolean active = false;
- 方案2:修改表单checkbox的绑定:
<input type="checkbox" id="active" name="isActive" th:checked="*{isActive}">
4. Thymeleaf字段绑定冲突(th:field与th:value同时使用)
th:field会自动生成name、value属性并完成数据绑定,同时使用th:value会覆盖绑定值,导致验证错误无法回显,甚至绑定失败。
错误代码:
<input type="text" id="name" name="storeName" required="required" class="form-control col-md-7 col-xs-12" th:field="*{storeName}" th:value="*{storeName}">
修正后:
<input type="text" id="name" required="required" class="form-control col-md-7 col-xs-12" th:field="*{storeName}">
(注:所有其他使用th:value的字段都应该去掉th:value,改用th:field完成绑定,比如storeCode、courierName等字段)
5. 缺少验证依赖(可选)
如果你的项目是Spring Boot,确保已经引入spring-boot-starter-validation依赖,否则@Size等验证注解不会生效:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
内容的提问来源于stack exchange,提问作者Ernest Daniel
相关产品推荐
相关产品推荐

