SpringBoot如何接收数组参数的方法

1.创建一个表单实体类,将数组封装到实体类中(Post提交)
表单类代码:

@Data
public class MyForm {
  private int[] ids;
}

控制器代码:

@Slf4j
@RestController
@RequestMapping("/info")
public class InfoController {
  
  @PostMapping("/test")
  public String test(@RequestBody MyForm form){
    log.info(Arrays.toString(form.getIds()));
    return "success";
  }
}

前端代码:

wx.request({
   url:'http://localhost:8085/info/test',
   data:{
   ids:[1,2,3]
   },
   method:'POST',
   success:function(res){
   console.log(res);
   }
   })

2.通过方法内参数传递,注意!!!SpringBoot方法内接收数组时,数组在前端请求时必须将参数拼接在路径里提交才可以接收到。(Get提交)
后端代码:

@Slf4j
@RestController
@RequestMapping("/info")
public class InfoController {
  
  @GetMapping("/test")
  public String test(int[] ids){
    log.info(Arrays.toString(ids));
    return "success";
  }  
}

Java技术迷
小程序前端代码:参数需拼接到路径里,并且要以GET方式提交

var ids = [1, 2, 3, 4]
  wx.request({
  url: 'http://localhost:8085/info/test?ids='+ids,
  method: 'GET',
  success: function(res){
  console.log(res);
  }
  })

请求头:
vue axios前端代码(注意,数组需要调用encodeURIComponent进行编码):

test() {
 let ary = [1,2,3]
 let params = {
  ids:encodeURIComponent(ary),};
 that.$http.get("http://localhost:8085/info/test",{params}).then(res=>{
  if(res.code==0){
   that.$message.success('查询成功')
  }else {
   that.$message.error(res.message||'查询失败')
  }
 }).catch(error=>{
  that.$message.error('查询失败')
 })
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值