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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Docker Model Runner: Streamlining AI Deployment for Developers
  • Create Your Own AI-Powered Virtual Tutor: An Easy Tutorial
  • Fixing Common Oracle Database Problems
  • Subtitles: The Good, the Bad, and the Resource-Heavy
  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
100.8K 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

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!