spring-mvc-and-ajax-with-json

reference:http://json-lib.sourceforge.net/apidocs/jdk15/index.html

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

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

pom.xml file:
<!-- Jackson for AJAX -->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib-ext-spring</artifactId>
            <version>1.0.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>log4j</artifactId>
                    <groupId>log4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>

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>

or
<bean id="jsonView" class="net.sf.json.spring.web.servlet.view.JsonView">
        <property name="contentType" value="application/json; charset=UTF-8" />
</bean>

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>    

or
<bean class="org.springframework.web.servlet.view.XmlViewResolver" p:order="0"
    p:location="/WEB-INF/ajaxviewresolver.xml" />

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

     

}


project sample1:
@RequestMapping(value = "/ajax/getCustomerDetailsById", method = RequestMethod.POST)
public String getCustomerDetailsById(@RequestParam("id") Integer customerInternalKey, final ModelMap model) {
CustomerOrganizationSite customerSite = customerOrganizationService
.retrieveSingleCustomerOrganizationSiteByCustomerOrganizationSiteId(1,
assessmentAuthInfo.getApplicationId(), customerInternalKey);
model.addAttribute("customerSite", customerSite);
return JSON_VIEW;
}

project sample2:
try {    
    JSONObject jsonObject = new JSONObject();    
    jsonObject.put("validateResult", validateResult);    
    jsonObject.put("errorMessage", errorMessage);    
    response.getWriter().println(jsonObject.toString());
} catch (IOException e) {    
    logger.error("IO exception happened");
}


Happy coding!


你可能感兴趣的:(spring-mvc,ajax-with-json)