Spring MVC and AJAX with JSON

This tutorial will walk through how to configure Spring MVC to return a JSON object to client browser.

One of the main decisions to be taken while developing AJAX applications is the format of messages passed by the server to the client browser. There are many options to choose from including plain text, XML, CSV etc. One of the more popular choices today is the JavaScript Object Notation (JSON). JSON provides a nice name-value pair data format that is easy to generate and parse.

How to do it?

You can use json-lib-ext-spring. There are other libs, this is the one I found. If you know or use another one, please leave a comment with the library name. :)

Do not forget to download Json-lib and its dependencies.

Now you have to configure your XML files:

Create a views.xml file under WEB-INF folder and paste the following code into it:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation= "http://www.springframework.org/schema/beans

 <bean name="jsonView" class="net.sf.json.spring.web.servlet.view.JsonView" />


Add this config to you spring configuration file:

<!-- json -->
<bean id="xmlFileViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
	<property name="location">
	<property name="order">

Make sure to set the order if you are using any other view resolvers.

Now you just have to use “jsonView” as the viewname and the model will be converted to JSONbefore being sent back to the client:

return new ModelAndView("jsonView", modelMap);

Here is an example:

	public ModelAndView getColumnsJson(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String,Object> modelMap = new HashMap<String,Object>(2);
		modelMap.put("rows", service.generateColumns());
		return new ModelAndView("jsonView", modelMap);

Happy coding!

32 thoughts on “Spring MVC and AJAX with JSON

  1. I never use json-lib so I cannot tell about it. But I used flexjson and jackson.

    flexjson: AFAIK, flexjson is only a one-way java object to json string transformation. If you use flexjson, your json string will also contain information that you rarely need (e.g. you json string will contain the class name of your java object).

    jackson: 2-way java object json string. So you can send a javascript object to the server and have the information in that javascript object populated to the java object. And your json string doesn’t have the class name inside :) How to create a json string from the browser? Just use JSON.stringify(a_js_object). Jackson is used in Spring 3.0. So I pick jackson over json-lib (I think Spring chose the best json library for them).

  2. Hi,

    May I know, what does the

    [modelMap.put(“rows”, service.generateColumns());]

    service.generateColumns() looks like?

  3. Thanks for this post I was able to fix my problem using your post. One question regarding this why cant we directly add the jsonView bean in the main configuration file ?

  4. Excellent. I was looking for something to simple to get started. Do you have the complete project for distribution? Thanks.

  5. I am getting some exception while doing this
    java.lang.ClassNotFoundException: net.sf.json.spring.web.servlet.view.JsonView
    Please reply it’s urgent

  6. You need json lib also depencies file like

    •jakarta commons-lang 2.5
    •jakarta commons-beanutils 1.8.0
    •jakarta commons-collections 3.2.1
    •jakarta commons-logging 1.1.1
    •ezmorph 1.0.6

  7. to resolve the jsonView you can add the following to applicationContext

    When you instantiate ModelAndView in the controller you can do
    ModelAndView  modelAndView = new ModelAndView(“jsonView”);

  8. bean name=”jsonView” class=”org.springframework.web.servlet.view.json.JsonView”

    Somehow the above text was missing from my previous posting.

  9. any ideas why spring is adding “JSONObject” in the response when I return ModelAndView from my controller?

    Iam adding my jsonObject to the ModelAndView and returing it.
    modelAndView.addObject(cust.toJsonObject()); The json structure is changing because of this and Im not able to traverse properly in the java script.

  10. thanks a lot for this example. Its really really helpful
    don’t forget to download all jar file in total 7 jars are there.

  11. Hi Loiane…your posts regarding extjs and Spring are really helpful..I am trying to create a small project where I take request input in the form of Extjs Form , submit it to Spring 3 Controller and send a JSON response back in the form of Extjs Grid. Values submitted through the Extjs Form successfully reaches the Controller , but the return view does not get redirected to Extjs Grid and at the FE it gets stuck at the Form Submit button with the Wait message of extjs Form page.Kindly help.

    1. Hi Shilpi,
      You have to return a JSON from the controller with a success atribute so you can return something to the form. Don’t return a simple view, just a json.

  12. Thanks …it was great help. Also , would like to metion that for Spring 2.5 version , with maven below is required to get jsonView working.


  13. Hi Loiane,

    I’m having some trouble with jsonView.

    My problem is the browser is attempting to open the json results as a file, rather than calling the JQuery success function.

    I am new to JQuery and JsonView – so I’m not sure if i’m missing something.

    Here is my ajax call:
    type: ‘POST’,
    target: ‘/app/testSubmit.json’

    Here is my controller:

    public ModelAndView testSubmit(HttpServletRequest request,
    HttpServletResponse response, AppCommand command)
    throws ServletException, IOException {

    Map model = new HashMap();
    model.put(“success”, true);
    return new ModelAndView(“jsonView”, model);


    Here is my views.xml:

    So basically it goes into the correct method in the controller, and then returns a jsonView which in turn attempts to open the result as a json file with the correct model data within the browser.

    Any tips where I’m going wrong ?

    1. Hi Lisa,
      In JQuery, you have ot use the function $.getJSON to receive a JSON form the server.
      This way JQuery knows you are expecting a JSON object.

  14. Actually the website won’t allow me to submit with the braces:
    bean name=”jsonView” class=”org.springframework.web.servlet.view.json.JsonView”/

  15. I want to use the JSON object in jsp’s for each loop
    success: function(data) {

    var returnGraphData = JSON.parse(data.graphDataMap);


    and data has the department , graphDataMap list

    know how to set department list to jsp’s for each loop

  16. I am trying to populate the combo box values dynamically through spring 3 mvc controller in extjs
    But in store of combox ,results are not uploading.

    var formatStore = new Ext.data.Store({
    proxy: new Ext.data.HttpProxy({
    url: ‘selectAllFormats.html’,method:’GET’
    reader: new Ext.data.JsonReader({
    [{name: ‘formatId’},
    {name: ‘formatDcscription’}

    items: [
    xtype: ‘label’,
    width: 160,
    text: ‘Format:’
    new Ext.form.ComboBox(
    id: ‘formatCombo’,
    waitMsgTarget: true,
    name: ‘formatList’,
    valueField: ‘formatId’,
    displayField: ‘formatDcscription’,
    store: formatStore,
    editable: false,
    typeAhead: true,
    //hiddenName : ‘formatType’,
    mode: ‘remote’,
    anchor: ‘100%’,
    //allowBlank: false,
    //multiSelect: true,
    //renderTo: ‘multiSelectCombo’,

    // autoLoad:true,
    emptyText:’Select a format…’,
    //triggerAction: ‘all’,
    forceSelection: false ,

    @RequestMapping(value=”/selectAllFormats.html”, method = RequestMethod.GET)
    public @ResponseBody Map loadFormats() {

    HashMap<String, List> modelMap = new HashMap<String,List>();
    modelMap.put(“formats”, formatJsonService.getAllformats());
    System.out.println(“Model Map==”+modelMap);
    System.out.println(“Format Id==”+modelMap.get(“formats”).get(1).getFormatId());

    return modelMap;

    the above is the flow..please revert back to me..with the solution..

  17. Pingback: JavaPins

Comments are closed.