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.