Saturday, 2 March 2013

Posting & Processing JSON with jQuery & Spring MVC

Consider an HTML form containing numerous input fields. When the user clicks on the form's submit button, the fields need to be sent as JSON to a service that under the hood is implemented in Spring MVC.

A jQuery function transforms and posts the form's inputs:

Through the $('form').submit(...) function (line 61), jQuery intercepts any click on the submit button and posts the form with the $.ajax(...) function (line 63). Before sending the data, jQuery transforms the form's inputs to JSON using JSON.stringify($(this).serializeArray()) (line 66). This function outputs a JSON string consisting of a list of key-value pairs:

On the service side, I have the controller to process the form:

getCreateClientForm() returns the HTML form to the user. The more interesting method is processSubmitCreateClient(...).

The headers annotation attribute tells Spring that processSubmitCreateClient(...) should be invoked only if the HTTP request header Content-Type is set to application/json. Furthermore, @RequestBody tells Spring to bind the JSON data to the client paramater which is a list of maps. processSubmitCreateClient(...) iterates through each element to merge the individuals maps into a single map to facilitate processing.

I  added the Jackson library to the project's POM since Spring requires a JSON deserializer to perform the data binding:

You can grab the complete example from GitHub and run it from the project root directory using the following command:

From your browser, enter "http://localhost:8080/jq-springmvc-json/create-client.html" to access the form.


  1. thanks to you, I can get request parameters for List\ type!

  2. HI,
    Thanks for this tutorial, but when I submit the form I only got this error :

    HTTP Status 415 -


    type Status report


    description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.


    Apache Tomcat/7.0.47

  3. Hi -- Thanks so much for posting this! It helped me with an issue that had me stuck for a couple days.