Spring MVC Json Request Example

In the previous post we have seen how we can get the JSON data from the Controllers using the @ResponseBody. Similarly posting JSON data/objects to the Controllers from views is also easy in Spring MVC. JSON data can be posted to Spring MVC controllers using the @RequestBody annotation. We will see the Spring MVC Json request example using the @RequestBody.

In the steps below we will be doing the following
a. Display a Form to user to fill in Employee data
b. Use JQuery to get the data and using Ajax post it to the Spring Controller as JSON data
c. In Controllers use the @RequestBody to get the data
d. Process the data and then send it back using @ResponseBody
e. On Jsp display back the processed data.

Now lets the code to achieve it.

1. Employee Model

2. Controller

In the controller we are getting the Employee data, Adding 1000 to the Salary and then again returning the Employee object as JSON.

3. JSP View to get and display data

In the View first we get the data from User. On Submit send the data to controller.
Once data is processed and returned back we display it as JSON in a new DIV.

Output

spring mvc json request example using @RequestBody

As you can see we had entered Salary = 3500, but since we are adding 1000 to Salary in the Controller, the returned data shows Salary as 4500.

spring mvc json request example using @RequestBody

Download Full Code – SpringMVCJsonPost.zip

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn