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

第1种方法:表单提交,以字段数组接收;

第2种方法:表单提交,以BeanListModel接收;

第3种方法:将Json对象序列化成Json字符串提交,以List接收;

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

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

public class User {

privateInteger id;

privateString name;

privateString pwd;

@Override

publicString toString() {

return "User{" +

"id=" + id +

", name='" + name + '\''+

", pwd='" + pwd+ '\'' +

'}';

}

//.......后面还有getter、setter方法,省略了

}


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

<formaction="/user/submitUserList_1" method="post">

ID:<input type="text" name="id"><br/>

Username:<input type="text" name="name"><br/>

Password:<input type="text" name="pwd"><br/><br/>

ID:<input type="text" name="id"><br/>

Username:<input type="text" name="name"><br/>

Password:<input type="text" name="pwd"><br/><br/>

<input type="submit" value="submit">

</form>

Java代码如下:

@RequestMapping(value = "/submitUserList_1", method={RequestMethod.POST})

@ResponseBody

public String submitUserList_1(HttpServletResponse response,Integer[] id,String[] name, String[] pwd)

throws Exception{

String result = "";

if(id == null || id.length <= 0){ return "No any ID.中文"; }

List<User> userList = new ArrayList<User>();

for (int i = 0; i < id.length; i++ ) {

User user = new User();

user.setId(id[i]);

user.setName(name[i]);

user.setPwd(pwd[i]);

userList.add(user);

}

result = this.showUserList(userList);

return result;

}


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

<formaction="/user/submitUserList_2" method="post">

ID:<input type="text" name="users[0].id"><br/>

Username:<input type="text" name="users[0].name"><br/>

Password:<input type="text"name="users[0].pwd"><br/><br/>

ID:<input type="text" name="users[2].id"><br/>

Username:<input type="text" name="users[2].name"><br/>

Password:<input type="text" name="users[2].pwd"><br/><br/>

<input type="submit" value="Submit">

</form>

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

public class UserModel {

privateList<User> users;

publicList<User> getUsers() {

return users;

}

publicvoid setUsers(List<User> users) {

this.users = users;

}

publicUserModel(List<User> users) {

super();

this.users = users;

}

publicUserModel() {

super();

}

}

SpringMVC Controller方法:

@RequestMapping(value= "/submitUserList_2", method ={RequestMethod.POST})

@ResponseBody

publicString submitUserList_2(UserModel users)

throws Exception{

String result = "";

List<User> userList = users.getUsers();

if(userList == null || userList.size() <= 0){ return "No any ID.中文"; }

result = this.showUserList(userList);

return result;

}


第3种方法:将Json对象序列化成Json字符串提交,以List接收
HTML代码:

<head>

<title>submitUserList_3</title>

<metahttp-equiv="content-type" content="text/html;charset=utf-8">

<scriptlanguage="JavaScript" src="/js/jquery.min.js" ></script>

<scriptlanguage="JavaScript" src="/js/jquery.json.min.js"></script>

<scripttype="text/javascript" language="JavaScript">

function submitUserList_3() {alert("ok");

var customerArray = new Array();

customerArray.push({id: "1", name: "李四",pwd: "123"});

customerArray.push({id: "2", name: "张三",pwd: "332"});

$.ajax({

url: "/user/submitUserList_3",

type: "POST",

contentType : 'application/json;charset=utf-8',//设置请求头信息

dataType:"json",

//data:JSON.stringify(customerArray),    //将Json对象序列化成Json字符串,JSON.stringify()原生态方法

data:$.toJSON(customerArray),            //将Json对象序列化成Json字符串,toJSON()需要引用jquery.json.min.js

success: function(data){

alert(data);

},

error: function(res){

alert(res.responseText);

}

});

}

</script>

</head>

<body>

<h1>submitUserList_3</h1>

<inputid="submit" type="button" value="Submit" onclick="submitUserList_3();">

</body>

Java代码:

@RequestMapping(value= "/submitUserList_3", method ={RequestMethod.POST})

@ResponseBody

publicString submitUserList_3(@RequestBody List<User> users)

throws Exception{

String result = "";

if(users == null || users.size() <= 0){ return "No any ID.中文"; }

result = this.showUserList(users);

return result;

}


第4种方法:将表单对象序列化成Json字符串提交,以List接收
HTML代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>submitUserList_4</title>

<metahttp-equiv="content-type" content="text/html;charset=utf-8">

<scriptlanguage="JavaScript" src="/js/jquery.min.js" ></script>

<scripttype="text/javascript" language="JavaScript">

//将表单序列化成json格式的数据(但不适用于含有控件的表单,例如复选框、多选的select)

(function($){

$.fn.serializeJson = function(){

var jsonData1 = {};

var serializeArray = this.serializeArray();

// 先转换成{"id":["12","14"], "name":["aaa","bbb"],"pwd":["pwd1","pwd2"]}这种形式

$(serializeArray).each(function() {

if (jsonData1[this.name]) {

if($.isArray(jsonData1[this.name])) {

jsonData1[this.name].push(this.value);

} else {

jsonData1[this.name]= [jsonData1[this.name], this.value];

}

} else {

jsonData1[this.name] = this.value;

}

});

// 再转成[{"id":"12", "name": "aaa","pwd":"pwd1"},{"id": "14","name": "bb", "pwd":"pwd2"}]的形式

var vCount = 0;

// 计算json内部的数组最大长度

for(var item in jsonData1){

var tmp =$.isArray(jsonData1[item]) ? jsonData1[item].length : 1;

vCount = (tmp > vCount)? tmp : vCount;

}

if(vCount > 1) {

var jsonData2 = new Array();

for(var i = 0; i <vCount; i++){

var jsonObj = {};

for(var item in jsonData1){

jsonObj[item] =jsonData1[item][i];

}

jsonData2.push(jsonObj);

}

return JSON.stringify(jsonData2);

}else{

return "[" + JSON.stringify(jsonData1)+ "]";

}

};

})(jQuery);

function submitUserList_4() {alert("ok");

var jsonStr = $("#form1").serializeJson();

//console.log("jsonStr:\r\n" + jsonStr);

//alert(jsonStr);

$.ajax({

url: "/user/submitUserList_4",

type: "POST",

contentType : 'application/json;charset=utf-8',//设置请求头信息

dataType:"json",

data: jsonStr,

success: function(data){

alert(data);

},

error: function(res){

alert(res.responseText);

}

});

}

</script>

</head>

<body>

<h1>submitUserList_4</h1>

<formid="form1">

ID:<input type="text" name="id"><br/>

Username:<input type="text" name="name"><br/>

Password:<input type="text" name="pwd"><br/><br/>

ID:<input type="text" name="id"><br/>

Username:<input type="text" name="name"><br/>

Password:<input type="text" name="pwd"><br/><br/>

<input type="button" value="submit" onclick="submitUserList_4();">

</form>

</body>

</html>

Java代码:

@RequestMapping(value= "/submitUserList_4", method ={RequestMethod.POST})

@ResponseBody

publicString submitUserList_4(@RequestBody List<User> users)

throws Exception{

String result = "";

if(users == null || users.size() <= 0){ return "No any ID.中文"; }

result = this.showUserList(users);

return result;

}

总结:
第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/

4种方法让SpringMVC接收多个对象(转:http://blog.csdn.net/lutinghuan/article/details/46820023)的更多相关文章

  1. springboot项目--传入参数校验-----SpringBoot开发详解(五)--Controller接收参数以及参数校验----https://blog.csdn.net/qq_31001665/article/details/71075743

    https://blog.csdn.net/qq_31001665/article/details/71075743 springboot项目--传入参数校验-----SpringBoot开发详解(五 ...

  2. 4种方法让SpringMVC接收多个对象 <转>

    问题背景: 我要在一个表单里同时一次性提交多名乘客的个人信息到SpringMVC,前端HTML和SpringMVC Controller里该如何处理? 第1种方法:表单提交,以字段数组接收: 第2种方 ...

  3. 4种方法让SpringMVC接收多个对象

    问题背景: 我要在一个表单里同一时候一次性提交多名乘客的个人信息到SpringMVC,前端HTML和SpringMVC Controller里该怎样处理? 第1种方法:表单提交,以字段数组接收: 第2 ...

  4. Golang拼接字符串的5种方法及其效率_Chrispink-CSDN博客_golang 字符串拼接效率 https://blog.csdn.net/m0_37422289/article/details/103362740

    Different ways to concatenate two strings in Golang - GeeksforGeeks https://www.geeksforgeeks.org/di ...

  5. 单点登录的三种实现方式 转自: https://blog.csdn.net/python_tty/article/details/53113612

    单点登录SSO(Single Sign On)说得简单点就是在一个多系统共存的环境下,用户在一处登录后,就不用在其他系统中登录,也就是用户的一次登录能得到其他所有系统的信任.单点登录在大型网站里使用得 ...

  6. python 使用函数名的字符串调用函数(4种方法)_black-heart的专栏-CSDN博客 https://blog.csdn.net/mrqingyu/article/details/84403924

    funcs = ['fetch_data_' + i for i in ( 'activities', 'banners', 'server_list')]# from operator import ...

  7. spring加载hibernate映射文件的几种方式。转自:http://blog.csdn.net/huiwenjie168/article/details/7013618

    在Spring的applicationContext.xml中配置映射文件,通常是在<sessionFactory>这个Bean实例中进行的,若配置的映射文件较少时,可以用sessionF ...

  8. 快速掌握 Android Studio 中 Gradle 的使用方法 [转http://blog.csdn.net/feelang/article/details/41783317]

    Gradle是可以用于Android开发的新一代的 Build System, 也是 Android Studio默认的build工具. Gradle脚本是基于一种JVM语言 -- Groovy,再加 ...

  9. <转载> 22种代码味道(Martin Fowler与Kent Beck) http://blog.csdn.net/lovelion/article/details/9301691

    Martin Fowler在Refactoring: Improving the Design of Existing Code(中译名:<重构——改善既有代码的设计>)一书中与Kent ...

随机推荐

  1. env-cmd 从文件读取配置变量

    npm install --registry=https://registry.npm.taobao.org -D env-cmd So.. 这样你在npm run build的时候会发现输出文件里面 ...

  2. OpenResty 操作cookies

    在or中简单的使用cookies 复杂的操作请使用 [lua_resty_cookies](https://github.com/cloudflare/lua-resty-cookie) 基本操作 获 ...

  3. Bootstrap3 栅格系统-实例:流式布局容器

    如何让小屏幕设备上所有列不堆叠在一起,使用针对超小屏幕和中等屏幕设备所定义的类就可以做到,即 .col-xs-* 和 .col-md-*.举例: <!-- Stack the columns o ...

  4. VirtualBox: How to config higher screen resolution

    Issue: Default Screen Resolution in Virtualbox instance is 800*600 which might be too small for gene ...

  5. GitHub Android Librarys Top 100 简介

    GitHub Android Librarys Top 100 简介 本项目主要对目前 GitHub 上排名前 100 的 Android 开源库进行简单的介绍, 至于排名完全是根据GitHub搜索J ...

  6. Python excel 奇怪的通信规则

    直接: for i in range(1,n+1): print(i) if xls.getCell(i,1,1)=='id': res=[] xls.xlBook.Worksheets(i).Nam ...

  7. Redis集群功能预览

    目前Redis Cluster仍处于Beta版本,Redis 3.0将会加入,在此可以先对其主要功能和原理进行一个预览.参考<Redis Cluster - a pragmatic approa ...

  8. Android Studio下多渠道打包

    Android Studio下实现多渠道打包 直接上步骤 步骤 1. 清单文件添加属性(以友盟统计为例) 在application标签下添加meta-data属性 <application -- ...

  9. [线程]Thead 中传参数RuntimeError: thread.__init__() not called

    在写一个多线程类的时候调用报错 RuntimeError: thread.__init__() not called class NotifyTread(threading.Thread): def ...

  10. 剑指Offer——小米+小红书笔试题+知识点总结

    剑指Offer--小米+小红书笔试题+知识点总结 情景回顾 时间:2016.9.23 19:00-21:00 2016.9.24 15:00-17:00 地点:山东省网络环境智能计算技术重点实验室 事 ...