Is it possible to make effective use of JSR303 (Bean Validation) annotations on JAX-RS resources?
So for example, if I have a resource member that I've annotated @NotEmpty, generate an error back to the client if this constraint is not met?
This seems like the obvious thing to do, but also happy to be told better ways (I don't want to move the validation down to the ORM/database level)
Do you really mean validating the resource members? Usually the resource members are injected in this way or another (it's either contexts, or entity, or path/query/matrix params), as long as the JAX-RS framework works you'll get these members properly injected.
Personally I think it makes more sense to validate the entity since it has arrived by the wire, filled by a MessageBodyReader and basically you have no idea what's inside, right?
So if you decide to validate the entities, there are several approaches that you can take:
AFAIK, Apache Wink does not support built-in validations. You can implement a handler. See DeploymentConfiguration.initRequestHandlersChain()
. It supports adding user handlers. In your handler you can perform any validations. I even think that the Wink community will be glad if you contribute this code.
The only problem with this approach - it's bound to the Apache Wink. It won't work if you decide to move to a different JAX-RS framework.
Another approach is to make this validation in your own MessageBodyReader
. All you need to do is registering a special reader for your entities and validate the entity inside. You can still take advantage of standard MessageBodyReaders (like JAXB or Jackson) by using @Context Providers.getMessageBodyReader()
. The good part of this approach that it's standard JAX-RS. The bad that you use MessageBodyReaders for something they were not designed to.
The simplest approach is to validate the entity in first line of each resource method. It will create some code duplication, but sometimes simplicity wins.
One solution - as I'm using Spring 2.5.x, I can create a wrapper class that implements InitializingBean and delegates to Hibernate's validator. It works - is there a better solution?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With