---
title: "jquery(1.3.2)<--json-->spring(3.0)"
author: "yiyu"
date: "2010-04-23T14:09:52Z"
tags: ["Ajax", "Spring", "hprose", "jQuery", "json"]
categories: ["企业架构"]
slug: "jquery-1-3-2-json-spring-3-0"
draft: false
lastmod: "2010-04-23T14:09:52Z"
id: 651227
url: "https://yiyu.iteye.com/blog/651227"
---

发现spring 3已经对ajax支持的很好了，前端可以只使用html+jquery，后端 只使用spring再加上一种orm，两者之间用json交换数据就可以了，现在是放弃 jsp，struts这些已经显得累赘的技术的时候了。 出于这种想法，我做了个小试验，其中之所以选择jquery 1.3.2是因为jquery ui 1.8还不是稳定版，而稳定版1.7是基于jquery 1.3+的。 1. 先从前台提交数据开始，关键代码如下： \[code="javascript"]function save() { var elemUserinfo = $('#customerInfo'); var userinfo = elemUserinfo.serializeObject(); var jsonuserinfo = JSON.stringify(userinfo); jQuery.ajax({ type : 'POST', contentType : 'application/json', url : 'customerInfo/new.do', data : jsonuserinfo, dataType : 'json', success : function(data){ $('div#responseName').text(data.name); $('div#responseAddr').text(data.addr); }, error : failed }); }\[/code] 其中customerInfo是一个form的id，该form包含两个text input，name分别为name和addr， serializeObject是一个网上比较流行的将form数据组装成json对象的juery扩展，代码如下： \[code="javascript"]$.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o\[this.name]) { if (!o\[this.name].push) { o\[this.name] = \[ o\[this.name] ]; } o\[this.name].push(this.value || ''); } else { o\[this.name] = this.value || ''; } }); return o; };\[/code] 将json对象转成String是用的json2（http://www.json.org/js.html）的JSON.stringify，提交 是用的jquery的ajax功能，注意要把contentType设为'application/json'，这是为了后台spring 将其自动转化为vo对象用的。 关于返回值后面再说。 2. 然后说说后台spring的接收。 后台主要的代码如下： \[code="java"]@Controller @RequestMapping("/customerInfo") public class CustomerInfoController { @RequestMapping(value="/new", method = RequestMethod.POST) @ResponseBody public Customer newCustomer(@RequestBody Customer customer) { customer.setName(customer.getName() + "经服务器修改"); customer.setAddr(customer.getAddr() + "经服务器修改"); return customer; } }\[/code] 其中Controller，RequestMapping什么的就不多说了，简单的说就是前提交时指定的url（ customerInfo/new.do）就被spring转到这里来处理了，其中web.xml中spring的设置如下： \[code="xml"] test org.springframework.web.servlet.DispatcherServlet 1 test \*.do \[/code] 注意处理申请的函数的参数直接就是Customer对象（Customer是一个具有属性name和addr的vo）， 而不是json字串，这里的关键是这样的，spring具有将数据转化后再交给controller的功能，spring 3 新增了对json的处理能力，是基于Jackson JSON Processor（http://jackson.codehaus.org/）的， 使用时要配置一下，在这个例子中默认的bean定义文件test-servlet.xml中这样写： \[code="xml"] \[/code] 这样一来，spring在接收contentType为application/json的request时会自动将json字串间转换成期望 的java对象，同样，发送response时，contentType被设为application/json，并且将java对象转为json 字串。 3. 下面该说返回了 上面已经说到，spring自动将response进行json化，所以处理函数直接返回vo对象就可以了。 而在页面端，由于我们指定了dataType为json，所以jquery直接把接收到的json字串转成了javascript 对象，我们可以直接使用data.name的写法取得数据了。 简单吧，这样一来，开发中，可以由设计人员在需求分析的基础上专心用html制作页面，之后交到前端 开发人员手里，前端开发人员添加js代码，实现页面逻辑，后台人员专心于java，spring和orm，前后 端交换json数据就可以了。 欢迎拍砖啊，呵呵。