Spring MVC @RequestBody json example

If you are developing a Rich Internet application using any of modern JavaScript MVC framework (like ExtJS etc) then you usually send an Asynchronous request to server and get the request processed. If you send an Ajax request with some parameter, on server side you will get that parameter values by request.getParameter() method. Sending multiple parameter may need to invoke getParameter method multiple times to get the param values.

Fortunately, SpringMVC comes with a very handy annotation @RequestBody which can be used to convert your incoming Json request to Model object. You just need to add @RequestBody annotation with your controller method and Spring will automatically convert all incoming Json request (application/json) into Model object defined in controller method. Optionally we can use @Valid or @Validate annotation to invoke automatic validation. In such a case Spring automatically performs the validation and in case of error MethodArgumentNotValidException is thrown.

Let me show you today how we can send a Json request to SpringMVC and use @RequestBody annotation to convert Json request into Domain model. Spring v3.x uses MappingJackson2HttpMessageConverter class as an Implementation of HttpMessageConverter that can read and write JSON using Jackson 2.x’s ObjectMapper. Please make sure you need Jackson-all-xx.jar library into classpath to make it happens.

I am using XML-Free approach to create this example.

First, create a Bootstrap class which implements WebApplicationInitializer interface.

Now, Controller configuration class.

Now we need a Request and Response Body Class as Follows.

Generic ResponseVO class used to capture response returning from Controller method.

Spring Controller used to handle Request-Response flow.

And Now ExtJS Login Window.

The Output will look similar to following…

Download Source code (size: ~17.7 Kb without jars)

About the Author

has written 69 posts.

I Love Coding, Analyzing, Designing and doing it the right way. I am obsessed about learn anything new daily and sharing what I have learn each Day. This Blog is journey of my Zeal, going through step by step to the mountain of desire to become prefect. Google Wanna Hire me ?

Copyright © 2020 http://www.techzoo.org. All rights reserved.
Proudly powered by WordPress. Developed by 7Tech Solutions