java BindingResult始终返回0个错误Hibernate验证器

fumotvh3  于 2022-12-10  发布在  Java
关注(0)|答案(2)|浏览(186)

我在使用Hibernate验证器时遇到了问题,或者更准确地说,是BindingResult和method .hasError()出现了问题。即使对象为空,它也总是返回true。请在此处查看我的代码:https://github.com/jeddyn/spring-mvc-demo

Customer: null customer first name: null
bindingresult: org.springframework.validation.BeanPropertyBindingResult: 0 errors
Customer: null customer first name: null
bindingresult: org.springframework.validation.BeanPropertyBindingResult: 0 errors
h9a6wy2h

h9a6wy2h1#

尝试在pom.xml中添加以下依赖项

<dependency>
     <groupId>javax.validation</groupId>
     <artifactId>validation-api</artifactId>
     <version>1.0.0.GA</version> 
</dependency>

您可以更改与Hibernate验证器兼容的版本。
@Valid放在@ModelAttribute之前,改变顺序,如下所示,很奇怪,但它的工作。

public String processForm(
            @Valid @ModelAttribute("customer") Customer customer,
            BindingResult theBindingResult)

参考this

tct7dpnv

tct7dpnv2#

对我来说,它是这样工作的:

@PostMapping("/registration/post")
    public String processRegistrationForm(@ModelAttribute("registrationForm") @Valid RegistrationForm registrationForm, BindingResult bindingResult, HttpServletRequest request, RedirectAttributes redirectAt) {...}

bindingResult之前总是0,因为我忘了在pom.xml中添加spring-boot-starter-validation

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

相关问题