码迷,mamicode.com
首页 > 编程语言 > 详细

spring-mvc-and-ajax-with-json

时间:2014-05-25 05:38:40      阅读:450      评论:0      收藏:0      [点我收藏+]

标签: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. bubuko.com,布布扣

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!


本文出自 “六度空间” 博客,请务必保留此出处http://jasonwalker.blog.51cto.com/7020143/1416721

spring-mvc-and-ajax-with-json,布布扣,bubuko.com

spring-mvc-and-ajax-with-json

标签:spring-mvc-and-ajax-with-json

原文地址:http://jasonwalker.blog.51cto.com/7020143/1416721

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!