DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a CRUD Application With Spring and SimpleJdbcMapper
  • How to Marry MDC With Spring Integration
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux

Trending

  • A Hands-On ABAP RESTful Programming Model Guide
  • Building a Skill-Based Agentic Reviewer with Claude Code: A Practical Guide Using Skills.MD, MCP Servers, Tools, and Tasks
  • The Middleware Gap in AI Agent Frameworks
  • Evolving Spring Boot APIs to an Event-Driven Mesh
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring 3.1 + @Valid @RequestBody + Error handling

Spring 3.1 + @Valid @RequestBody + Error handling

By 
Michal Letynski user avatar
Michal Letynski
·
Jun. 25, 12 · Interview
Likes (3)
Comment
Save
Tweet
Share
101.4K Views

Join the DZone community and get the full member experience.

Join For Free

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.
Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Building a CRUD Application With Spring and SimpleJdbcMapper
  • How to Marry MDC With Spring Integration
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook