Spring MVC and AJAX with JSON

February 15, 2010 | By

spring json loiane Spring MVC and AJAX with JSONThis 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. icon smile Spring MVC and AJAX with JSON

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"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation= "http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd


http://www.springframework.org/schema/util


http://www.springframework.org/schema/util/spring-util-2.5.xsd">

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

</beans>

Add this config to you spring configuration file:

<!-- json -->
<bean id="xmlFileViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver">
	<property name="location">
		<value>/WEB-INF/views.xml</value>
	</property>
	<property name="order">
		<value>1</value>
	</property>
</bean>     

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!

Filed in: JSON, Spring | Tags: , , , ,

Comments (32)

Links to this Post

  1. JavaPins | January 8, 2012
  1. Thai Dang Vu

    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. aries satriana

    prefer use XStream and jettison :).
    Anyway good article .

    Rgds,
    AR

  3. Very good article. Thanks for taking the time for doing this.

  4. Mark R

    Hi,

    May I know, what does the

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

    service.generateColumns() looks like?

  5. Pavel Kral

    There is also GSON library,http://code.google.com/p/google-gson/ which give you more control for (de)serialization of objects (it help to tune json manipulation if you use inheritance etc.) Personally I prefer this library.

  6. 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 ?

  7. Ona

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

  8. gaurav

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

  9. Vinay

    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

  10. mm_newtoJson

    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”);

  11. mm_newtoJson

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

    Somehow the above text was missing from my previous posting.

  12. mm_newtoJson

    any ideas why spring is adding “JSONObject” in the response when I return ModelAndView from my controller?
    {“JSONObject”:{“custDetails”:{“customerId”:”11″,”customerName”:”CustName”,”addressLine1″:”Andover”,”city”:”LA”,”state”:”CA”}}}

    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.

  13. rajnish

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

  14. Shilpi

    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.

    • Loiane

      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.

  15. jaspreet

    Please provide example using extjs to design form and spring as framework

  16. Rupali Giri

    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.

    net.sf.json-lib
    json-lib-ext-spring
    1.0.2

  17. Sam

    Hello Loiane, how do I add the jar as a dependency in the pom.xml?

  18. Sam

    i answer myself:

      net.sf.json-lib  json-lib-ext-spring  1.0.2

  19. Lisa Johnston

    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:
    $(‘#appForm”‘).ajaxForm(
    {
    type: ‘POST’,
    target: ‘/app/testSubmit.json’
    }
    );

    Here is my controller:

    @RequestMapping(“/testSubmit.json”)
    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 ?
    Thanks,
    Lisa

    • Loiane

      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.

  20. Lisa Johnston

    Sorry I forgot to paste the views.xml

  21. Lisa Johnston

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

  22. I want to use the JSON object in jsp’s for each loop
    e.g.
    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

  23. Lisa Johnston

    Thanks a million Loiane, that worked a treat ! :)
    I better read up more on JQuery.

    Lisa

  24. Nagesh

    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({
    root:’formats’
    },
    [{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',
    //onTriggerClick:function()
    //{
    //getFormat(formatStore);
    //},
    forceSelection: false ,
    selectOnFocus:true
    })
    ]

    @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(“Formats==”+modelMap.get(“formats”));
    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..

  25. Chandana

    Thanks for this post. It helped me a lot..  strait to the point… 

  26. Regards for sharing the information with us on loianegroner.com. wish you luck!