Spring MVC在接收集合请求参数时,需要在Controller方法的集合参数里前添加@RequestBody或者@RequestParam,而@RequestBody默认接收的enctype (MIME编码)是application/json,因此发送POST请求时需要设置请求报文头信息(ajax提交数据时设置提交类型为:contentType : 'application/json;charset=utf-8', //设置请求头信息),否则Spring MVC在解析集合请求参数时不会自动的转换成JSON数据再解析成相应的集合。
本文通过List<Integer>、List<User>、List<Map<String,Object>>、User[]、User(bean里面包含List)几种较为复杂的集合参数示例
eg1:接收List<Integer>集合参数
1、Js代码:
var arr = [1,2,3];
$.jBox.confirm("确定要删除数据吗?", "warning",function () {
$.ajax({
type: 'get',
url: '${base.contextPath}/giving/index/del',
dataType: 'json',
data: {ids: arr},
success: function (result) {
…
},
error: function (result) {
…
}
})
})
2、Controller方法:
@Controller
@RequestMapping("/wxgiving")
public class WxGivingController{
@RequestMapping(value = "/index/del", method = RequestMethod.GET)
@ResponseBody
public ReturnMsg del (@RequestParam(value = "ids[]")List <Integer> ids){
…
}
}
eg2: 接收List<User>、User[]集合参数:
1、js代码
var userList = new Array();
userList.push({name: "张三",pwd: "123"});
userList.push({name: "李四",pwd: "223"});
$.ajax({
type: "POST",
url: "${base.contextPath}/user/index/add",
data: JSON.stringify(userList),//将对象序列化成JSON字符串
dataType:"json",
contentType : 'application/json;charset=utf-8', //设置请求头信息
success: function(result){
…
},
error: function(result){
…
}
});
2、Controller方法:
@Controller
@RequestMapping(value = "/user")
public class UserController(){
@RequestMapping(value = "/index/add", method = RequestMethod.POST)
@ResponseBody
public ReturnMsg addOrEdit(@RequestBody List<User> userList) {
…
}
}
eg3:接收List<Map<String,Object>>集合参数
1、js代码
var userList = new Array();
userList.push({name: "张三",pwd: "123"});
userList.push({name: "李四",pwd: "223"});
$.ajax({
type: "POST",
url: "${base.contextPath}/user/index/add",
data: JSON.stringify(userList),//将对象序列化成JSON字符串
dataType:"json",
contentType : 'application/json;charset=utf-8', //设置请求头信息
success: function(result){
…
},
error: function(result){
…
}
});
2、Controller方法:
@Controller
@RequestMapping(value = "/user")
public class UserController(){
@RequestMapping(value = "/index/add", method = RequestMethod.POST)
@ResponseBody
public ReturnMsg addOrEdit(@RequestBody List<Map<String,Object>> listMap) {
…
}
}
eg4:User实体类
1、js代码
var userArray= new Array();
userArray.push({name: "张三",pwd: "123"});
userArray.push({name: "李四",pwd: "223"});
var user = {};
user.name = "王五";
user.pwd = "888";
user.userList= userArray;
$.ajax({
type: "POST",
url: "${base.contextPath}/user/index/add",
data: JSON.stringify(user),//将对象序列化成JSON字符串
dataType:"json",
contentType : 'application/json;charset=utf-8', //设置请求头信息
success: function(result){
…
},
error: function(result){
…
}
});
2、Controller方法:
@Controller
@RequestMapping(value = "/user")
public class UserController(){
@RequestMapping(value = "/index/add", method = RequestMethod.POST)
@ResponseBody
public ReturnMsg addOrEdit(@RequestBody User user) {
List<User> userList= user.getUserList();