问题
Lets say I define a POJO with parameters that is passed to a REST call
class MyVO {
@NotNull
@PathParam("name")
private String name;
@NotNull
@PathParam("age")
private Integer age;
// getters and setters
}
public class RESTclass {
public postData( @Form MyVO vo ) {
}
}
It automatically binds the objects in MyVO. But where do I get the validation errors? Does it trigger the validation during binding? If not, how to trigger the validations?
Spring does all these well. It has BindingResult parameter that you can inject. What is the equivalent here?
Any idea?
回答1:
RestEasy Versions Prior to 3.0.1.Final
For bean validation 1.0, Resteasy has a custom validation provider that uses hibernate's bean validator implementation under the covers.
In order to get validation up and running in Resteasy you need to do the following:
Add the
resteasy-hibernatevalidator-provider
dependency to your project. Here is the maven pom entry if you are using maven:<dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-hibernatevalidator-provider</artifactId> <version>${resteasy.version}</version> </dependency>
Annotate your resource classes where you want validation to occur with the
@ValidateRequest
annotation.@Named @Path("/users") @ValidateRequest public class UserResource extends BaseResource { @POST @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) public Response createUser(@Valid User user) { //Do Something Here } }
Resteasy will automatically detect the
HibernateValidatorAdapter
on the classpath and begin invoking bean validation.Create an
ExceptionMapper<MethodConstraintViolationException>
implementation to handle the validation errors.Unlike in Spring where you have to check the BindingResult, when validation errors are encountered in Resteasy the hibernate validator will throw a
MethodConstraintViolationException
. TheMethodConstraintViolationException
will contain all of the validation errors within it.@Provider public class MethodConstraintViolationExceptionMapper extends MyBaseExceptionMapper implements ExceptionMapper<MethodConstraintViolationException> { @Override public Response toResponse(MethodConstraintViolationException exception) { //Do Something with the errors here and create a response. } }
RestEasy Version 3.0.1.Final
The latest version of Resteasy is now supporting bean validation spec 1.1 and has changed the api and exceptions thrown.
Instead of the
resteasy-hibernatevalidator-provider
you are going to need theresteasy-validator-provider-11
dependency.You will not need to add
@ValidateRequest
to your resource classes as validation testing is turned on by default withresteasy-validator-provider-11
.Instead of throwing a
MethodConstraintViolationException
when violations are detected, an instance ofRESTEasyViolationException
will be thrown.
Documentation: 3.0.1.Final Validation Documentation
来源:https://stackoverflow.com/questions/17435544/resteasy-parameters-binding-validation-and-errors-ejb