Head of R&D and Java Architect in ConSol MENA. Specialized in web technologies with the six-year experience in commercial projects. Michal has posted 2 posts at DZone. You can read more from them at their website. View Full User Profile

Spring 3.1 + @Valid @RequestBody + Error handling

06.25.2012
| 7521 views |
  • submit to reddit

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.
AttachmentSize
spring311.tar_.gz37.49 KB
Published at DZone with permission of its author, Michal Letynski.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Membrane Kash replied on Tue, 2013/04/23 - 12:42pm

I know its old post. But I just tried this. @Valid does not seem to be kicking in. But the binding works. Any ideas?

Thiago Henrique... replied on Tue, 2013/05/21 - 7:39am

wow,Condolences, very good post, where I can complete the project? this file that the information provided is broken, even managing to open it fails to understand the configuration, is to post here, or available on github?Thanks, pending!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.