How to turn on annotation driven validation in Spring 4?

后端 未结 2 965
耶瑟儿~
耶瑟儿~ 2020-12-10 21:10

I am using the annotation validation as below:

    public String processRegistration(@Valid Spitter spitter, Errors errors,
            Model model) {
               


        
相关标签:
2条回答
  • 2020-12-10 21:38

    I see two points in your code that may cause de problem.

    1) Instead of <annotation-driven /> use the correct namespace <mvc:annotation-driven/>.

    2) On your @Controller change your functions parameters from:

       public String processRegistration(@Valid Spitter spitter, Errors errors,
            Model model) {
        if (errors.hasErrors()) {
            return "registerForm";
        }
        ...
    

    To:

    public String processRegistration(@ModelAttribute("spitter") @Valid Spitter spitter, BindingResult result) {
    
        if (result.hasErrors()) {
            return "registerForm";
        }
        ...
    

    Try it! ;)

    0 讨论(0)
  • 2020-12-10 21:49

    Judging from your explanation and the following error java.lang.ClassNotFoundException: javax.validation.Validator Spring doesn't see the classes and as such doesn't enable JSF-303 validation.

    Make sure that the correct jars are on the classpath and that you have an implementation as well. When using maven adding something like the following should do the trick.

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.1.3.Final</version>
    </dependency>
    

    This will add the needed jars to the WEB-INF/lib directory which in turn lets Spring Web MVC detect it and configure the appropriate bean.

    For an explanations of the different annotations you might want to check In Hibernate Validator 4.1+, what is the difference between @NotNull, @NotEmpty, and @NotBlank?.

    0 讨论(0)
提交回复
热议问题