@RequestParam传递数组 @PathVariable传递数组


今天新来的小伙伴问我前端传数组后端怎么接收的问题 

今天新来的小伙伴问我关于前端传数组,后端怎么接收的问题,简单:

@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接收,或者使用一个数组都可以。

至于能否接收对象答案是不可以的。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM