今天,我将向大家介绍SpringController中如何定义List类型的参数,以及前端如何向后端接口传递这种参数。让我们开始吧。
在SpringController中传入List类型的参数,有以下几种方法:
一、使用RequestParam直接使用
RequestParam注解接收List类型的参数。例如:RequestMapping("/test")publicStringtest(RequestParam("roleIds")ListIntegerroleIds){//处理roleIdsreturn"success";}这种方法要求前端传递的参数名和后端接收的参数名一致,且参数值可以用逗号分隔。例如:
/test?roleIds=1,2,二、使用
ModelAttribute使用
ModelAttribute注解接收一个包含List属性的对象。例如:publicclassUser{privateStringname;privateListIntegerroleIds;//省略getter和setter}
RequestMapping("/test")publicStringtest(ModelAttributeUseruser){//处理user.getRoleIds()return"success";}这种方法要求前端传递的参数名和后端对象的属性名一致,且参数值可以用逗号分隔。例如:
/test?name=TomroleIds=1,2,三、使用
RequestBody使用
RequestBody注解接收一个JSON格式的数组。例如:RequestMapping("/test")publicStringtest(RequestBodyListIntegerroleIds){//处理roleIdsreturn"success";}这种方法要求前端使用POST方法,并设置请求头为application/json,请求体为JSON格式的数组。例如:
[1,2,]总结
以上是三种在SpringController定义List类型参数以及前端调用这类参数的技巧,希望对你的工作有所帮助。