-------------------------------------------------------------------
源文地址: http://www.cnblogs.com/yunlei0821/p/7760189.html ,轉載請務必保留此出處。
在使用SpringMVC時,我們需要傳遞數組類型,SpringMVC對數組傳遞有些限制:
支持一維數組的參數傳遞,不支持多維數組的參數傳遞。
當我們需要傳遞多維數組時有以下幾種方法:
1、將多維數組拆成一維數組;
2、將多維數組改為集合傳遞;
3、或者改為字符串,接收時間處理一下等等,
4、或者將所有數組中的值拼接傳遞。(例如:arr=1&arr=2&arr=3,代表三個數組的值)
參數傳遞注意事項:
傳遞數組類型時,需要在@requestParam()中添加value,否則會出現HTTP Status 400 - Required String[] parameter 'data' is not present錯誤。
例如: @RequestParam(value = "data[]") String[] data
前端請求:
var arr= new Array(); for(var i = 0; i < 10; i++){ arr.push(i); } $.ajax({ url : "req/arrParam", data : {"arr" : arr}, dataType : "json", async : false, success : function(data) {
console.log(data);//打印出arr數組的長度10 //請求成功數據處理 } });
后端代碼:
1 package com.axhu.edu.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestParam; 6 import org.springframework.web.bind.annotation.ResponseBody; 7 8 /** 9 * 創建時間:2017-10-31午09:52:00 10 * 11 * @author yunlei0821 12 */ 13 @Controller 14 @RequestMapping("/req") 15 public class ReqController { 16 17 @RequestMapping("/arrParam") 18 @ResponseBody 19 public int arrParam(@RequestParam(value = "arr[]") int[] newArr) { 20 return newArr.length; //10 21 } 22 }