I use Resteasy in combination with Google Guice using Resteasy-Guice. I have been looking for ways to validate my request bodies. I want to do for example:
public static class MyPojo {
@NotEmpty private String contents;
}
And then use in my resource
@POST
@ValidateRequest
public void doPost(@Valid MyPojo myPojo) {
// use myPojo only if valid
}
I have been working with the resteasy-hibernate-validator-provider. But since I switched to newer versions, this introduced the (unwanted?) dependency to EJB. See also: RESTEASY-1056. In the comments is stated that you should switch to the newer validator-11 instead:
Switch to resteasy-validator-provider-11, which implements the newer Bean Validation 1.1 specification.
The docs say:
Validation is turned on by default (assuming resteasy-validator-provider-11-.jar is available), though parameter and return value validation can be turned off or modified in the validation.xml configuration file. See the Hibernate Validator documentation for the details.
I however do not manage to get this working to my configuration, because I find myself including dependencies like hibernate-validator
, javax.el-api
, javax.el
and hibernate-validator-cdi
and annotations like ValidateOnExecution
. I however do not find any of this being instantiated or invalid requests being rejected.
What is the preferred, lightweight, and working way to do validation with Resteasy?
You do not have to specify any annotation on the resource itself or do additional configuration. Just the constraint annotations on POJOs are enough get it working.
My setup is as follows:
The resource method:
@POST
public void doPost(@Valid MyPojo myPojo) {
// use myPojo only if valid
}
The POJO:
public static class MyPojo {
@NotEmpty private String contents;
}
Tested with the following dependencies:
javax.validation
version 1.1.0.Final
resteasy-validator-provider-11
version 3.0.11.Final
hibernate-validator
version 5.0.0.Final
and 5.0.1.Final