jar包(Maven仓库):
Spring4 jar包(Maven仓库):
在测试过程中我查看了网上的一些教程,但是那些教程都是在Spring3环境下的,Spring3和Spring4解析json需要的jar文件不同.
在这里贴出Sring3解析json需要的jar
Sring3解析json需要的jar
1,页面获取后端数据
jQuery.ajax( { type : "GET", contentType : "application/json", url : "<%=request.getContextPath()%>/easyui/list.do", dataType : "json", success : function(data) { if (data && data.success == "true") { $("#info").html("共" + data.total + "条数据。<br/>"); $.each(data.data, function(i, item) { $("#info").append( "编号:" + item.id + ",姓名:" + item.username + ",年龄:" + item.age); }); } }, error : function() { alert("error") } });
jqunery ajax get 向controller请求数据contentType : "application/json", json格式,url为请求的地址,请求成功之后json数据添加到页面
@RequestMapping(value = "/list", method = RequestMethod.GET,consumes="application/json") @ResponseBody public Map<String, Object> getUserList() { List<UserModel> list = new ArrayList<UserModel>(); UserModel um = new UserModel(); um.setId("1"); um.setUsername("sss"); um.setAge(222); list.add(um); Map<String, Object> modelMap = new HashMap<String, Object>(3); modelMap.put("total", "1"); modelMap.put("data", list); modelMap.put("success", "true"); return modelMap; }
@ResponseBody 表示自动将页面json数据封装进对象只在contentType : "application/json",情况下允许.
2.向后端发送页面数据
//将一个表单的数据返回成JSON字符串 $.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; };
$("#submit").click(function() { var jsonuserinfo = $.toJSON($("#form").serializeObject()); //$.toJSON($("#form")是 jqunery.json.js中的方法
alert(jsonuserinfo); jQuery.ajax( { type : "POST", //contentType: "application/json; charset=utf-8", contentType : 'application/json', url : "<%=request.getContextPath()%>/easyui/add.do", data : jsonuserinfo, dataType : "json", success : function(data) { alert("新增成功!"); }, error : function(data) { alert("error") } }); });
serializeObject()方法将表单内容转换成json字符串,jqunery的json对象和json字符串之间的转换也许需要jqunery插件包
jquery.json-2.2.min.js jquery提供的json包
json2.js json官网提供的json包
var obj = JSON.parse(jsonuserinfo); //字符串转json对象,json2.js中的方法
var c = JSON.stringify(obj); //json对象转字json符串,json2.js中的方法
json对象和字符串的转换有很多种方式,具体的可以看其他的教程.
@RequestMapping(value = "/add", method = RequestMethod.POST,consumes="application/json") @ResponseBody public Map<String, String> addUser(@RequestBody UserModel model) { //System.out.println(123); int s = model.getAge(); String ss = model.getId(); String sss = model.getUsername(); TestUtil.test(s+ss+sss); Map<String, String> map = new HashMap<String, String>(1); map.put("success", "true"); return map; }
@ResponseBody会自动将页面发送的json字符串解析成java对象,其实json对象底层就是map集合对象,java提供了工具可以将map集合转换成json对象,当然json对象和json数组的概念还是需要大家花费一些时间理解的
以下是全部代码:
<%@ page contentType="text/html; charset=utf-8" language="java" import="java.util.*,java.sql.*" errorPage="" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!doctype html> <html> <head> <meta charset="utf-8"> <base href="<%=basePath%>"> <title>Spring MVC</title> <script src="${pageContext.request.contextPath}/static/editormd/examples/js/jquery.min.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery.json-2.2.min.js"></script> <script type="text/javascript"> //将一个表单的数据返回成JSON对象 $.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; }; $(document).ready(function() { jQuery.ajax( { type : "GET", contentType : "application/json", url : "<%=request.getContextPath()%>/easyui/list.do", dataType : "json", success : function(data) { if (data && data.success == "true") { $("#info").html("共" + data.total + "条数据。<br/>"); $.each(data.data, function(i, item) { $("#info").append( "编号:" + item.id + ",姓名:" + item.username + ",年龄:" + item.age); }); } }, error : function() { alert("error") } }); $("#submit").click(function() { var jsonuserinfo = $.toJSON($("#form").serializeObject()); alert(typeof jsonuserinfo); jQuery.ajax( { type : "POST", //contentType: "application/json; charset=utf-8", contentType : 'application/json', url : "<%=request.getContextPath()%>/easyui/add.do", data : jsonuserinfo, dataType : "json", success : function(data) { alert("新增成功!"); }, error : function(data) { alert("error") } }); }); }); </script> </head> <body> <div id="info"></div> <form action="<%=request.getContextPath()%>/easyui/add.do" method="post" id="form"> 编号:<input type="text" name="id" value="12"/> 姓名:<input type="text" name="username" value="走走走"/> 年龄:<input type="text" name="age" value="44"/> <input type="button" value="提交" id="submit"/> </form> </body> </html>
/** * * Spring4 json test start ------------------------------- * @return */ @RequestMapping(value = "/list", method = RequestMethod.GET,consumes="application/json") @ResponseBody public Map<String, Object> getUserList() { TestUtil.test("123"); List<UserModel> list = new ArrayList<UserModel>(); UserModel um = new UserModel(); um.setId("1"); um.setUsername("sss"); um.setAge(222); list.add(um); Map<String, Object> modelMap = new HashMap<String, Object>(3); modelMap.put("total", "1"); modelMap.put("data", list); modelMap.put("success", "true"); return modelMap; } /** * Spring4 json test * @return */ @RequestMapping(value = "/add", method = RequestMethod.POST,consumes="application/json") @ResponseBody public Map<String, String> addUser(@RequestBody UserModel model) { //System.out.println(123); int s = model.getAge(); String ss = model.getId(); String sss = model.getUsername(); TestUtil.test(s+ss+sss); Map<String, String> map = new HashMap<String, String>(1); map.put("success", "true"); return map; }
package com.zlay.pojo; public class UserModel{ /** * * Spring4 json test class * @return */ private String id; private String username; private int age ; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }