说到SpringMVC接受List参数,可能有人会说这个是个坑!下面我来跟大家说怎么补这个坑。下面我分几种情况来讲:
一、只接收一个List
1、form表单提交
controller代码:
@ResponseBody
@RequestMapping("test")
public void test(@RequestParam(value="list",required = false) List<Integer> list) {for (Integer integer : list) {System.out.println(integer);}}
postman:
2、提交json对象
controller代码:
@ResponseBody
@RequestMapping("test")public void test(@RequestBody List<Integer> list) {for (Integer integer : list) {System.out.println(integer);}}
postman:
请求头设置:Content-Type application/json
总结一下:
controller 的区别在接收参数注解不一样,form表单提交是@RequestParam,接收json对象是@RequestBody
二、同时接收List和String,Interger等其他参数
1、form表单提交
controller代码:
@ResponseBody@RequestMapping("test")public void test(@RequestParam(value="list",required = false) List<Integer> list,@RequestParam(value="test",required = false) String test) {for (Integer integer : list) {System.out.println(integer);}System.out.println(test);}
postman:
2、接收json对象
controller代码:
@ResponseBody@RequestMapping("test")public void test(@RequestBody TestList testList) {for (Integer integer : testList.getList()) {System.out.println(integer);}System.out.println(testList.getTest());}
TestList 是自己写的接收对象:
public class TestList {private List<Integer> list;private String test;public List<Integer> getList() {return list;}public void setList(List<Integer> list) {this.list = list;}public String getTest() {return test;}public void setTest(String test) {this.test = test;}
}
postman:
请求Headers和之前一样
三、同时接收List、Map、String/Interger参数
controller代码:
@ResponseBody
@RequestMapping("test")
public void test(@RequestBody TestList testList) {for (Integer integer : testList.getList()) {System.out.println(integer);}System.out.println(testList.getTest());System.out.println(testList.getMap());
}
pojo对象:
public class TestList {private List<Integer> list;private String test;private Map<String, String> map;public Map<String, String> getMap() {return map;}public void setMap(Map<String, String> map) {this.map = map;}public List<Integer> getList() {return list;}public void setList(List<Integer> list) {this.list = list;}public String getTest() {return test;}public void setTest(String test) {this.test = test;}
}
postman:
接收成功!
注:POJO的传递和Map是一样的,把“map”改成你的对象名称,“ggg”这些换成对象的成员名称就可以了
四、接收List
controller:
@ResponseBody@RequestMapping("test")public void test(@RequestBody List<PojoList> list) {for (PojoList pojoList : list) {System.out.println(pojoList.getTest1());System.out.println(pojoList.getTest2());}}
pojo:
public class PojoList {private String test1;private Integer test2;public String getTest1() {return test1;}public void setTest1(String test1) {this.test1 = test1;}public Integer getTest2() {return test2;}public void setTest2(Integer test2) {this.test2 = test2;}
}
postman:
总结一下:如果是单个List或者List带一些其他简单参数,form表单提交和Json对象提交都差不多,但是如果是比较复杂的数据,组合,个人建议建一个pojo去组合这些参数,然后再去接收。希望能帮到大家,如果有哪里不正确,希望指正,谢谢!!!