Platinum Partner
java,spring,error handling,tips and tricks,valid,requestbody

Spring 3.1 + @Valid @RequestBody + Error handling

In Spring 3.1 there is a nice new feature:  "@Valid On @RequestBody Controller Method Arguments"

From the documentation:

"An @RequestBody method argument can be annotated with @Valid to invoke automatic validation similar to the support for @ModelAttribute method arguments. A resulting MethodArgumentNotValidException is handled in the DefaultHandlerExceptionResolver and results in a 400 response code."

http://static.springsource.org/spring/docs/current/spring-framework-reference/html/new-in-3.1.html#d0e1654

Based on this new feature I am able to send objects in JSON format, validate them and check for possible errors. Before this feature was introduced my controller looked like this:

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(method=RequestMethod.POST)
    public ResponseEntity create(@Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            //parse errors and send back to user
        }
    ...
}
But data wasn't sent as a JSON object. It came from simple HTML form. Let's play with Spring 3.1. I've updated my maven depedency to use version 3.1.1.RELEASE and added the Jackson dependency to be able to use the MappingJacksonHttpMessageConverter.
	
     
    <dependency> <!-- Required for @Configuration -->
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.7</version>
</dependency>

All other configuration is placed in java class instead of xml:

@Configuration
@EnableWebMvc
public class WebappConfig {
	
    @Bean
    public UserController userController() {
        return new UserController();
    }
	
    @Bean
    public MappingJacksonJsonView mappingJacksonJsonView() {
        return new MappingJacksonJsonView();
    }
	
    @Bean
    public ContentNegotiatingViewResolver contentNegotiatingViewResolver() {
        final ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();
        contentNegotiatingViewResolver.setDefaultContentType(MediaType.APPLICATION_JSON);
        final ArrayList defaultViews = new ArrayList();
        defaultViews.add(mappingJacksonJsonView());
        contentNegotiatingViewResolver.setDefaultViews(defaultViews);
        return contentNegotiatingViewResolver;
    }
}

 After that I've changed my create method to:

@RequestMapping(method=RequestMethod.POST, consumes = "application/json")
public ResponseEntity create(@Valid @RequestBody User user, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        //parse errors and send back to user
    }
...

Now I've sent a JSON object but received the following error:

"An Errors/BindingResult argument is expected to be immediately after the model attribute argument in the controller method signature" According to the documentation "BindingResult is supported only after @ModelAttribute arguments"

After removing BindingResult from my method's arguments it worked. But how to get the errors now ? According to the documentation a MethodArgumentNotValidException will be thrown. So let's declare the necessary ExceptionHandler.

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity handleMethodArgumentNotValidException( MethodArgumentNotValidException error ) {
   return parseErrors(error.getBindingResult());
}

...
And that's all, I'm attaching the full source code as a working example.
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}