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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

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

  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Using Python Libraries in Java
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  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.9K 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!