简体   繁体   中英

bean validation together with Spring

Tomcat application, and I use Spring for dependency injection. I also use Jersey for rest calls, now I need to do some bean validation. I found examples that it is easy to to if I were using Spring MVC @RequestMapping for rest calls. But using Jersey and hibernate validator together things got ugly.

@POST
@Path("/addSomething")
public void addSomething(Something something) {

    Set<ConstraintViolation<Something>> violations = validator.validate(something);
    if(violations.size()>0){
        throw new BadRequestException("illegal input");
    }

   ..
}

This works, but I need to repeat this for every post request. Which is ugly.

Is there a way to neatly handle bean validation here?

You could improve it a bit by having a generic validate method that takes an Object as parameter, eg:

public static void validateBean(Object object) {
    Set<ConstraintViolation<Object>> violations = validator.validate(object);
    if(violations.size()>0){
        throw new BadRequestException("illegal input");
    }
}

Then you just have to call validateBean(someObject); at the beginning of each post method.

What about use also contrainst groups XD.

public void validateEntity(final Object object, final Class<? extends Default>... classes)
        throws IllegalArgumentException {
    final Set<ConstraintViolation<Object>> errors = validator.validate(object, classes);
    if (!errors.isEmpty()) {
        throw new IllegalArgumentException(returnErrors(errors));
    }
}


public String returnErrors(final Set<ConstraintViolation<Object>> errors) {
    final StringBuilder builder = new StringBuilder();
    for (final ConstraintViolation<Object> error : errors) {
        builder.append(error.getMessage());
    }
    return builder.toString();
}

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