问题背景:
要在一个表单里同时一次性提交多名乘客的个人信息到SpringMVC,前端HTML和SpringMVC Controller里该如何处理?
- 第1种方法:将Json对象序列化成Json字符串提交,以List接收;
- 第2种方法:将表单对象序列化成Json字符串提交,以List接收;第2种方法其实是第1种方法的升级,就是将表单转成Json对象,再转成Json字符串提交。
以上2种方法都共用同一个User实体类,代码如下:
1 public class User { 2 private Integer id; 3 private String name; 4 private String pwd; 5 6 @Override 7 public String toString() { 8 return "User{" + 9 "id=" + id + 10 ", name='" + name + '\'' + 11 ", pwd='" + pwd + '\'' + 12 '}'; 13 } 14 // .......后面还有getter、setter方法,省略了 15 }
第1种方法:将Json对象序列化成Json字符串提交,以List接收
HTML代码:
1 <head> 2 <title>submitUserList_3</title> 3 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 4 <script language="JavaScript" src="/js/jquery.min.js" ></script> 5 <script language="JavaScript" src="/js/jquery.json.min.js" ></script> 6 <script type="text/javascript" language="JavaScript"> 7 function submitUserList_3() {alert("ok"); 8 var customerArray = new Array(); 9 customerArray.push({id: "1", name: "李四", pwd: "123"}); 10 customerArray.push({id: "2", name: "张三", pwd: "332"}); 11 $.ajax({ 12 url: "/user/submitUserList_3", 13 type: "POST", 14 contentType : 'application/json;charset=utf-8', //设置请求头信息 15 dataType:"json", 16 //data: JSON.stringify(customerArray), //将Json对象序列化成Json字符串,JSON.stringify()原生态方法 17 data: $.toJSON(customerArray), //将Json对象序列化成Json字符串,toJSON()需要引用jquery.json.min.js 18 success: function(data){ 19 alert(data); 20 }, 21 error: function(res){ 22 alert(res.responseText); 23 } 24 }); 25 } 26 </script> 27 </head> 28 29 <body> 30 <h1>submitUserList_3</h1> 31 <input id="submit" type="button" value="Submit" onclick="submitUserList_3();"> 32 </body>
Java代码:
1 @RequestMapping(value = "/submitUserList_3", method ={RequestMethod.POST}) 2 @ResponseBody 3 public String submitUserList_3(@RequestBody List<User> users) 4 throws Exception{ 5 String result = ""; 6 if(users == null || users.size() <= 0){ return "No any ID.中文"; } 7 result = this.showUserList(users); 8 return result; 9 }
第2种方法:将表单对象序列化成Json字符串提交,以List接收
HTML代码:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 2 "http://www.w3.org/TR/html4/loose.dtd"> 3 <html> 4 <head> 5 <title>submitUserList_4</title> 6 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 7 <script language="JavaScript" src="/js/jquery.min.js" ></script> 8 <script type="text/javascript" language="JavaScript"> 9 //将表单序列化成json格式的数据(但不适用于含有控件的表单,例如复选框、多选的select) 10 (function($){ 11 $.fn.serializeJson = function(){ 12 var jsonData1 = {}; 13 var serializeArray = this.serializeArray(); 14 // 先转换成{"id": ["12","14"], "name": ["aaa","bbb"], "pwd":["pwd1","pwd2"]}这种形式 15 $(serializeArray).each(function () { 16 if (jsonData1[this.name]) { 17 if ($.isArray(jsonData1[this.name])) { 18 jsonData1[this.name].push(this.value); 19 } else { 20 jsonData1[this.name] = [jsonData1[this.name], this.value]; 21 } 22 } else { 23 jsonData1[this.name] = this.value; 24 } 25 }); 26 // 再转成[{"id": "12", "name": "aaa", "pwd":"pwd1"},{"id": "14", "name": "bb", "pwd":"pwd2"}]的形式 27 var vCount = 0; 28 // 计算json内部的数组最大长度 29 for(var item in jsonData1){ 30 var tmp = $.isArray(jsonData1[item]) ? jsonData1[item].length : 1; 31 vCount = (tmp > vCount) ? tmp : vCount; 32 } 33 34 if(vCount > 1) { 35 var jsonData2 = new Array(); 36 for(var i = 0; i < vCount; i++){ 37 var jsonObj = {}; 38 for(var item in jsonData1) { 39 jsonObj[item] = jsonData1[item][i]; 40 } 41 jsonData2.push(jsonObj); 42 } 43 return JSON.stringify(jsonData2); 44 }else{ 45 return "[" + JSON.stringify(jsonData1) + "]"; 46 } 47 }; 48 })(jQuery); 49 50 function submitUserList_4() {alert("ok"); 51 var jsonStr = $("#form1").serializeJson(); 52 //console.log("jsonStr:\r\n" + jsonStr); 53 //alert(jsonStr); 54 $.ajax({ 55 url: "/user/submitUserList_4", 56 type: "POST", 57 contentType : 'application/json;charset=utf-8', //设置请求头信息 58 dataType:"json", 59 data: jsonStr, 60 success: function(data){ 61 alert(data); 62 }, 63 error: function(res){ 64 alert(res.responseText); 65 } 66 }); 67 } 68 </script> 69 </head> 70 71 <body> 72 <h1>submitUserList_4</h1> 73 <form id="form1"> 74 ID:<input type="text" name="id"><br/> 75 Username:<input type="text" name="name"><br/> 76 Password:<input type="text" name="pwd"><br/><br/> 77 78 ID:<input type="text" name="id"><br/> 79 Username:<input type="text" name="name"><br/> 80 Password:<input type="text" name="pwd"><br/><br/> 81 <input type="button" value="submit" onclick="submitUserList_4();"> 82 </form> 83 </body> 84 </html>
Java代码:
1 @RequestMapping(value = "/submitUserList_4", method ={RequestMethod.POST}) 2 @ResponseBody 3 public String submitUserList_4(@RequestBody List<User> users) 4 throws Exception{ 5 String result = ""; 6 if(users == null || users.size() <= 0){ return "No any ID.中文"; } 7 result = this.showUserList(users); 8 return result; 9 }
以上方法参考自以下URL:
http://www.cnblogs.com/wsw0515/p/3582627.html
http://www.oschina.net/question/917732_106601
http://jxd-zxf.iteye.com/blog/2072300
http://www.tashan10.com/jquery-jiang-biao-dan-xu-lie-hua-wei-jsondui-xiang