今天新来的小伙伴问我前端传数组后端怎么接收的问题
今天新来的小伙伴问我关于前端传数组,后端怎么接收的问题,简单:
@RequestParam 接普通数组
let test01 = () => {
let arr = [1, 2, 3, 4]; $.ajax({ url: "/controller/test01", async: true, data: { name: arr }, success: function (res) { console.log(res) }, type: "post", dataType: "json" }) }
接收参数
@RequestMapping("test01")
public void test01(@RequestParam("name[]") String[] name) { System.out.println(name); for (int i = 0; i < name.length; i++) { System.out.println(name[i]); } }
这种方法接收成功,并且发现前端传的数字,后端使用String也可以接受,因为在网络传输时都是字符串,但是使用Int也完全可以。
list 一样成功
@RequestMapping("test01")
public void test01(@RequestParam("name[]") List<String> name) { System.out.println(name); for (int i = 0; i < name.size(); i++) { System.out.println(name.get(i)); } }
@RequestParam 接对象数组
let test01 = () => { let arro = [ {id: 1, username: "1"}, {id: 2, username: "2"} ]; $.ajax({ url: "/controller/test01", async: true, data: { name: arro }, success: function (res) { console.log(res) }, type: "post", dataType: "json" }) }
@RequestMapping("test01")
public void test01(@RequestParam("name[]") List<TestUser> name) { System.out.println(name); for (int i = 0; i < name.size(); i++) { System.out.println(name.get(i)); } }
这种方式无法映射不管是数组还是list都无法映射,原因就在开头贴的博客里,与springmvc的formdata接收参数的格式不符。复杂对象映射还是推荐 @RequestBody
@PathVariable 数组传递
let test02 = () => {
let arr = [1, 2, 3, 4]; $.ajax({ url: "/controller/test02/" + arr, async: true, data: {}, success: function (res) { console.log(res) }, type: "post", dataType: "json" }) }
java代码
@RequestMapping("test02/{name}")
public void test02(@PathVariable List<String> name) { System.out.println(name); for (int i = 0; i < name.size(); i++) { System.out.println(name.get(i)); } }
@RequestMapping("test02/{name}")
public void test02(@PathVariable String[] name) { System.out.println(name); for (int i = 0; i < name.length; i++) { System.out.println(name[i]); }
}
ajax将数组参数拼接成了字符串用逗号分隔
所以使用单个String接收,或者使用一个数组都可以。
至于能否接收对象答案是不可以的。