Spring MVC requestbody - Spring MVC @RequestBody json example

Spring MVC @RequestBody json example

Posted on

Spring MVC requestbody - 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.

spring mvc request body eclipse - Spring MVC @RequestBody json example

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…

Spring MVC requestbody1 - Spring MVC @RequestBody json example

Download Source code (size: 17.7 Kb without jars)

Source techzoo.org