jar包(Maven倉庫):
Spring4 jar包(Maven倉庫):在測試過程中我查看了網上的一些教程,但是那些教程都是在Spring3環境下的,Spring3和Spring4解析json需要的jar文件不同.
在這裡貼出Sring3解析json需要的jar
Sring3解析json需要的jar1,頁面獲取後端數據
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> 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; } Java代碼 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; } } UserModel類
以下是全部代碼: