Wednesday 12 June 2013

First example: ValidatingRequestBodyMethodArgumentResolver

 One problem found when implementing a REST server, is that of input validation. Especially for objects, it is common to want to use the JSR-303 @Valid annotation to ensure your input is valid. Spring currently has an open bug, SPR-6709, which states that the @Valid annotation on an @RequestBody parameter does not work. Recent activity indicates it will not be with us much longer, but it is a good example to extend existing functionality.
Below is a class we have implemented to solve this problem. It delegates the translation of the request body to the original class, RequestResponseBodyMethodProcessor, and then validates the result if needed:


In this class, the delegation is clearly visible. The injected dependency to RequestMappingHandlerAdapter seems unfortunate, but it handles the underlying HttpMessageConverter implementations much better than we could do. Finally, the exception class ValidationException translates the JSR-303 constraint violations into a form we want.
Lastly, we need to configure Spring MVC to use our class. We use an XML configuration, which looks like this:



The end result is that @Valid and @RequestBody play nice together. 

No comments: