本文转自
https://blog.csdn.net/wabiaozia/article/details/50803581
这位大拿解释的很清楚,
方法一:post请求封装好一个集合List<User>,后台获取时得先建立一个bean PersonList,其有一个属性为List<User> userList,这样可以在后台直接获取List<user> userList = PersonList.getUserList()。
前台页面:
<form id="form" action="test/test.do" method="post">
<input type="text" name="personList[0].username" value="zhangsan"/>
<input type="text" name="personList[0].age" value="55"/><br/>
<input type="text" name="personList[1].username" value="lisi"/>
<input type="text" name="personList[1].age" value="21"/><br/>
<input type="submit">
<form>
方法二:使用@RequestParam注解,直接提交表单
jsp页面
- <form .....method="post"..............>
- 姓名1:<input type="text" name="id" value="">
- 年龄1:<input type="text" name="age" value="">
- 地址1:<input type="text" name="address" value="">
- 姓名2:<input type="text" name="id" value="">
- 年龄2:<input type="text" name="age" value="">
- 地址2:<input type="text" name="address" value=""><pre code_snippet_id="1597573" snippet_file_name="blog_20160304_1_2164278" name="code" class="html"></form>
- controller
- @RequestMapping("/...........")
- public String update(Export export, @RequestParam("id")String[] ids,
- @RequestParam("age")String[] ages,
- @RequestParam("address")String[] address,
- Model model){
- //ids,ages,addres接收进来的是什么样的数据呢?
- //接收的数据类型是ids[111,222,333],ages[222,333,444],address[sss,ddd,yyy]
- //拓展:若用@RequestParam("id")String ids接收,则传进来的是一个个String字符串,用逗号分隔。例如ids:“abc,cde,def”
- //批量增加
- for(int i=0,len=ids.length;i<len;i++){
- User user=new User();
- user.setId(ids[i]);
- user.setAge(ages[i]);
- user.setAddress(address[i]);
- userDao.isnert(user);
- }
- }
- 这种方案适合特别修改删除,而且相比用js拼接数据有个好处,不用在前端拼接参数。
方法三:json传递
客户端post 的json格式
{
"userList": [
{
"user_name": "zhangsan",
"password": "111"
},
{
"user_name": "lisi",
"password": "222"
}
]
}
服务端spring mvc处理
@RequestMapping(value = "test/uppost", method = RequestMethod.POST)
@ResponseBody
public void uploadTest(@RequestBody UserList userList) {}
UserList类如下
public class UserList {
private List<UserBean> userList;
public List<UserBean> getUserList() {
return userList;
}
public void setUserList(List<UserBean> userList) {
this.userList = userList;
}
}
UserBean类如下
public class UserBean {
private String user_name;
private String password;
//get set ......
}