一个表单同时提交多条记录

问题背景: 
我要在一个表单里同时一次性提交多名乘客的个人信息到SpringMVC,前端HTML和SpringMVC Controller里该如何处理?

  • 第1种方法:表单提交,以字段数组接收;
  • 第2种方法:表单提交,以BeanListModel接收;
  • 第3种方法:将Json对象序列化成Json字符串提交,以List接收;
  • 第4种方法:将表单对象序列化成Json字符串提交,以List接收; 
    第4种方法其实是第3种方法的升级,就是将表单转成Json对象,再转成Json字符串提交; 
    然而,第4种方法还不支持含有多选控件表单的提交,故应该还有第5种加强版的方法。

以上4种方法都共用同一个User实体类,代码如下:

  1. public class User {
  2.  
  3. private Integer id;
  4. private String name;
  5. private String pwd;
  6.  
  7. @Override
  8. public String toString() {
  9. return "User{" +
  10. "id=" + id +
  11. ", name='" + name + '\'' +
  12. ", pwd='" + pwd + '\'' +
  13. '}';
  14. }
  15. // .......后面还有getter、setter方法,省略了
  16. }

第1种方法:表单提交,以字段数组接收 
HTML代码如下:

  1. <form action="/user/submitUserList_1" method="post">
  2. ID:<input type="text" name="id"><br/>
  3. Username:<input type="text" name="name"><br/>
  4. Password:<input type="text" name="pwd"><br/><br/>
  5.  
  6. ID:<input type="text" name="id"><br/>
  7. Username:<input type="text" name="name"><br/>
  8. Password:<input type="text" name="pwd"><br/><br/>
  9. <input type="submit" value="submit">
  10. </form>

Java代码如下:

  1. @RequestMapping(value = "/submitUserList_1", method ={RequestMethod.POST})
  2. @ResponseBody
  3. public String submitUserList_1(HttpServletResponse response,Integer[] id, String[] name, String[] pwd)
  4. throws Exception{
  5. String result = "";
  6. if(id == null || id.length <= 0){ return "No any ID.中文"; }
  7. List<User> userList = new ArrayList<User>();
  8. for (int i = 0; i < id.length; i++ ) {
  9. User user = new User();
  10. user.setId(id[i]);
  11. user.setName(name[i]);
  12. user.setPwd(pwd[i]);
  13. userList.add(user);
  14. }
  15. result = this.showUserList(userList);
  16. return result;
  17. }

第2种方法:表单提交,以BeanListModel接收 
HTML代码如下:

  1. <form action="/user/submitUserList_2" method="post">
  2. ID:<input type="text" name="users[0].id"><br/>
  3. Username:<input type="text" name="users[0].name"><br/>
  4. Password:<input type="text" name="users[0].pwd"><br/><br/>
  5.  
  6. ID:<input type="text" name="users[2].id"><br/>
  7. Username:<input type="text" name="users[2].name"><br/>
  8. Password:<input type="text" name="users[2].pwd"><br/><br/>
  9. <input type="submit" value="Submit">
  10. </form>

Java代码: 
除了刚才公用的User类,还要封装一个User的容器类UserModel:

  1. public class UserModel {
  2. private List<User> users;
  3.  
  4. public List<User> getUsers() {
  5. return users;
  6. }
  7.  
  8. public void setUsers(List<User> users) {
  9. this.users = users;
  10. }
  11.  
  12. public UserModel(List<User> users) {
  13. super();
  14. this.users = users;
  15. }
  16.  
  17. public UserModel() {
  18. super();
  19. }
  20.  
  21. }

SpringMVC Controller方法:

  1. @RequestMapping(value = "/submitUserList_2", method ={RequestMethod.POST})
  2. @ResponseBody
  3. public String submitUserList_2(UserModel users)
  4. throws Exception{
  5. String result = "";
  6. List<User> userList = users.getUsers();
  7. if(userList == null || userList.size() <= 0){ return "No any ID.中文"; }
  8. result = this.showUserList(userList);
  9. return result;
  10. }

第3种方法:将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. }

第4种方法:将表单对象序列化成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. }

总结: 
第1、2种方法其实都有一个共同的BUG:假如提交三条记录时,前面两条记录的某些字段不填值的话,在SpringMVC里接收不准确了。而且,每2种方法在HMTL中需要给name属性添加[下标],如果下标有跨度的话(比如第一组控件下标是0,第二组下标是2),那么SpringMVC里其实的是0到2三个对象的,默认下标是1的那个对象全为null值。 
第3、4种方法最实用。

以上方法参考自以下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/

posted @ 2018-08-30 20:56  华丽D转身  阅读(1840)  评论(1编辑  收藏  举报