简体   繁体   中英

Spring 4.2.3 with Hibernate validator 5.2.2.Final does not work

I am trying to integration Spring 4.2.3 with hibernate validator v.5.2.2.Final to validate input JSON data expose with REST Controller. I don't see any compile time or running time exception but at the same time it does not validate input data.

Pom.xml

 <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.2.3.RELEASE</version>
        <scope>compile</scope>
    </dependency>
    <!-- jsr303 validation dependencies -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.2.2.Final</version>
    </dependency>
    <dependency>
        <groupId>javax.el</groupId>
        <artifactId>javax.el-api</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>javax.el</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator-cdi</artifactId>
        <version>5.2.2.Final</version>
    </dependency>

Pojo java class:

    public class RequestVO {    

    @NotEmpty
    private String testValidation;

    @NotNull
    private String testNull;

    @NotBlank
    private String testBlank;

   .... getters and setters .....
}

    @Controller
    @RequestMapping("/login")
    public class LoginController {

    @RequestMapping(method=RequestMethod.POST, value="/user")
    public @ResponseBody  ResponseVO getLoginResponse(@Valid @RequestBody RequestVO request, Errors error) {

            ResponseVO response = new ResponseVO ();


    if (error.hasErrors()) {
            System.err.println("Success");
        }

        return response;
    }
}

In your dependency list there's a comment saying ...jsr303 validation dependencies... . Note the bean validation has an updated specification ( JSR-349 ), and this can very well be your issue.

You should align your dependencies in the following manner

hibernate-validator-5.x.x 
validation-api-1.1.x

which implement JSR-349

OR

hibernate-validator-4.x.x
validation-api-1.0.x.

which implements JSR-303

If you mix the dependencies, the validation will simply not kick-in. As a solution suggestion, add

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

and make sure that you remove any dependency to validation-api-1.0 jar

I think is interest to take a look at this link

and if you to remove the validation just remove @Valid from method and you're ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM