Spring mvc接收復雜資料型別
阿新 • • 發佈:2018-12-08
**前言:**Spring MVC在接收集合請求引數時,需要在Controller方法的集合引數裡前新增@RequestBody,而@RequestBody預設接收的enctype (MIME編碼)是application/json,因此傳送POST請求時需要設定請求報文頭資訊,否則Spring MVC在解析集合請求引數時不會自動的轉換成JSON資料再解析成相應的集合。以下列舉接收List、List、List<Map<String,Object>>、User[]、User(bean裡面包含List)幾種較為複雜的集合引數示例:
- 接收List集合引數:
js程式碼
var idList = new Array(); idList.push(“1”); idList.push(“2”); idList.push(“3”); var isBatch = false; $.ajax({ type: "POST", url: "<%=path%>/catalog.do?fn=deleteCatalogSchemes", dataType: 'json', data: {"idList":idList,"isBatch":isBatch}, success: function(data){ … }, error: function(res){ … } });
controller程式碼
@Controller @RequestMapping("/catalog.do") public class CatalogController { @RequestMapping(params = "fn=deleteCatalogSchemes") @ResponseBody public AjaxJson deleteCatalogSchemes(@RequestParam("idList[]") List<String> idList,Boolean isBatch) { … } }
- 接收List、User[]集合引數:
實體類
js程式碼:
var userList = new Array();
userList.push({name: "李四",pwd: "123"});
userList.push({name: "張三",pwd: "332"});
$.ajax({
type: "POST",
url: "<%=path%>/catalog.do?fn=saveUsers",
data: JSON.stringify(userList),//將物件序列化成JSON字串
dataType:"json",
contentType : 'application/json;charset=utf-8', //設定請求頭資訊
success: function(data){
…
},
error: function(res){
…
}
});
controller
@Controller
@RequestMapping("/catalog.do")
public class CatalogController {
@RequestMapping(params = "fn=saveUsers")
@ResponseBody
public AjaxJson saveUsers(@RequestBody List<User> userList) {
…
}
}
- 接收List<Map<String,Object>>集合引數
頁面js程式碼
var userList = new Array();
userList.push({name: "李四",pwd: "123"});
userList.push({name: "張三",pwd: "332"});
$.ajax({
type: "POST",
url: "<%=path%>/catalog.do?fn=saveUsers",
data: JSON.stringify(userList),//將物件序列化成JSON字串
dataType:"json",
contentType : 'application/json;charset=utf-8', //設定請求頭資訊
success: function(data){
…
},
error: function(res){
…
}
});
controller
@Controller
@RequestMapping("/catalog.do")
public class CatalogController {
@RequestMapping(params = "fn=saveUsers")
@ResponseBody
public AjaxJson saveUsers(@RequestBody List<Map<String,Object>> listMap) {
…
}
}
- 接收User(bean裡面包含List)集合引數
js頁面
var customerArray = new Array();
customerArray.push({name: "李四",pwd: "123"});
customerArray.push({name: "張三",pwd: "332"});
var user = {};
user.name = "李剛";
user.pwd = "888";
user. customers = customerArray;
$.ajax({
type: "POST",
url: "<%=path%>/catalog.do?fn=saveUsers",
data: JSON.stringify(user),//將物件序列化成JSON字串
dataType:"json",
contentType : 'application/json;charset=utf-8', //設定請求頭資訊
success: function(data){
…
},
error: function(res){
…
}
});
controller
@Controller
@RequestMapping("/catalog.do")
public class CatalogController {
@RequestMapping(params = "fn=saveUsers")
@ResponseBody
public AjaxJson saveUsers(@RequestBody User user) {
List<User> customers = user.getCustomers();
…
}
}