今天新來的小伙伴問我前端傳數組后端怎么接收的問題
今天新來的小伙伴問我關於前端傳數組,后端怎么接收的問題,簡單:
@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接收,或者使用一個數組都可以。
至於能否接收對象答案是不可以的。

