How to handle Resource validation in REST webservices?

前端 未结 4 1957
悲哀的现实
悲哀的现实 2020-12-24 14:46

I\'m building a REST webservice in Java using Spring, Jersey and Hibernate (JPA).

Now I\'m trying to add support for validation in my resources. JSR-303 (Bean valida

4条回答
  •  感动是毒
    2020-12-24 15:22

    The solution ended up to be subclassing Jackson's JacksonJaxbJsonProvider which implements a JAX-RS MessageBodyReader and MessageBodyWriter. I was inspired by the amazing dropwizard's approach. In this provider we need to somehow Inject a Validator instance (I used Spring for Injection and Hibernate Validator for JSR-303 implementation). If you use Hibernate ORM don't forget to disable entity validation, otherwise you will be validating the same entity twice. It may be what is desired, though.

    Then, in this subclassed MessageBodyReader, I validate the object and throw a custom InvalidEntityException with the errors from the validator. I also created a JAX-RS ExceptionMapper that maps every InvalidEntityException into a proper HTTP response. In my case I returned a Bad Request and a JSON object containing the errors description.

    Notice that this MessageBodyReader checks for @Valid and @Validated annotations. This means that it correctly supports groups. This is important because we probably don’t want to do the same kind of validation across our entire application. An example is when we want to do a partial update (PUT). Or, for example, an id property must be null in a POST request but non-null everywhere else.

    Data Integrity Validations aren't completely dealt with yet. But I'm planning to catch database exceptions and converting them to my own domain exceptions (say a DataIntegrityException) as it seems more efficient and loosely coupled to me.


    UPDATE:

    Since JAX-RS 2, the recommended way to do this is to use its Bean Validation support. Check here: https://jersey.java.net/documentation/latest/bean-validation.html

提交回复
热议问题