@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