(Spring4 json入門)Spring4+SpringMVC+頁面資料發送與接收(json格式),spring4json

來源:互聯網
上載者:User

(Spring4 json入門)Spring4+SpringMVC+頁面資料發送與接收(json格式),spring4json

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> 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類

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.