假設有一個bean名叫TestPOJO。javascript
一、使用ajax從前臺傳遞一個對象數組/集合到後臺。java
前臺ajax寫法:ajax
var testPOJO=new Array(); //這裏組裝testPOJO數組 $.ajax({ url:「testController/testPOJOs」, data:JSON.stringify(testPOJO), type:"post", dataType:"json", contentType:"application/json", success:function (res) { }, error:function(msg){ } });
後臺接收方法:json
@RestController @RequestMapping("testController") public class testController { @RequestMapping("/testPOJOs") //若是類的註解是@Controller,那麼方法上面還須要加@ResponseBody,由於@ResTController=@Controller+@ResponseBody public String testPOJOs (@RequestBody TestPOJO [] testPOJO) { //操做 } //或者下面這個 //@RequestMapping("/testPOJOs") //public String testPOJOs (@RequestBody List<TestPOJO> testPOJO) { //操做 //} }
不管是幾維數組,先後臺保持一致就好了。數組
二、傳遞Mapapp
前臺ajax寫法:post
var testMap={ "a":"aaa", "b":[1,2,3] }; $.ajax({ url:「testController/testMap」, data:JSON.stringify(testMap), type:"post", dataType:"json", contentType:"application/json", success:function (res) { }, error:function(msg){ } });
後臺接收方法:編碼
@RestController @RequestMapping("testController") public class testController { @RequestMapping("/testMap") public String testMap (@RequestBody Map<String,Object> map) { String a = (String) map.get("a"); List<Integer> b = (List<Integer>) map.get("b"); ... } }
三、除了傳遞對象集合,還須要傳遞其餘字段。url
前臺ajax寫法:spa
var testPOJO=new Array();
//這裏組裝testPOJO數組
$.ajax({
url:「testController/testPOJOs」,
data:{
「strs」: JSON.stringify(testPOJO),
「others」,」…」
},
type:"post",
dataType:"json",
success:function (res) {
},
error:function(msg){
}
});
後臺接收方法:
@RestController
@RequestMapping("testController ")
public class testController {
@RequestMapping("/testPOJOs")
public String testPOJOs (String strs,String others) {
//操做使用fastjson進行字符串對象轉換
List<TestPOJO> list=new ArrayList<>();
JSONObject json =new JSONObject();
JSONArray jsonArray= JSONArray.parseArray(strs);
for(int i=0;i<jsonArray.size();i++){
JSONObject jsonResult = jsonArray.getJSONObject(i);
TestPOJO testPOJO=JSONObject.toJavaObject(jsonResult,TestPOJO.class);
list.add(testPOJO);
}
//其餘操做
}
}
或者直接把others和testPOJO數組從新組合一個新數組var arr=[testPOJO,」others的內容」],「strs」: JSON.stringify(arr),只傳遞一個strs字段就能夠,而後後臺轉換。
四、傳遞一個數組
前臺ajax寫法:
$.ajax({ url: 'testController/listByxxx', data: { "xxxs":xs//xs是一個數組 }, type: "post", dataType: "json", success: function (res) {} });
後臺接收方法:
@RestController @RequestMapping("testController") public class testController { @RequestMapping("/listByxxx") public String listByxxx(@RequestParam(value = "xxxs[]")String[] xxxs){ //操做 } }
@RequestBody通常用來處理非Content-Type: application/x-www-form-urlencoded編碼格式的數據。在GET請求中,不能使用@RequestBody。在POST請求,能夠使用@RequestBody和@RequestParam。