restful api报错:Ambiguous handler methods mapped for ...

问题

最近,为了给大家搭建一个学习环境,开发了几个restful api

在通过id查询用户的时候,会报错

请求为:

报错:通过id查询,也会匹配到通过username查询

{"code":1002,"msg":"请求失败","data":"Ambiguous handler methods mapped for '/qzcsbj/v2/users/4': {public com.qzcsbj.demo.commons.ResultMsg com.qzcsbj.demo.controller.UserRestfulController.findById(java.lang.Integer), public com.qzcsbj.demo.commons.ResultMsg com.qzcsbj.demo.controller.UserRestfulController.findByUsername(java.lang.String)}"}

分析

控制器代码如下:

    // restful api:根据id查
    @ApiOperation(value = "根据id获取用户", notes = "根据id获取用户信息")
    @GetMapping("/users/{id}")
    public ResultMsg findById(@PathVariable("id") Integer id){
        User user = userService.findById(id);
        ......
    }

    // restful api:根据username查
    @ApiOperation(value = "根据username获取用户", notes = "根据username获取用户信息(数据库中username是唯一的)")
    @GetMapping("/users/{username}")
    public ResultMsg findByUsername(@PathVariable("username") String username){
        User user = userService.findByUsername(username);
        ......
    }

restful风格的api,参数可以放到url中,通过@PathVariable获取,

因为上面根据id和根据username的请求方式一样,都是get请求,Spring无法根据传参的类型自动匹配到可以处理的方法,

也就是说,不知道具体访问到哪一个接口,此时访问其中任何一个都会报这个错,其实就是含糊映射

解决方案一

如果依然想使用rest编程风格,则必须改变请求url的格式,这样就不会产生歧义,

可以在变量前面增加参数名的简写:

  @GetMapping("/users/id/{id}")

  @GetMapping("/users/name/{username}")

解决方案二

有歧义的做合并,这里统一改为:@GetMapping("/users")

方法中使用@RequestParam,一个参数是id,一个是username

if判断:

  如果都不为空可以返回引导性提示信息

  哪个不为空就以哪个来查询

  如果都为空,就查所有

参考:https://www.nuomiphp.com/eplan/713714.html

原文已更新:https://www.cnblogs.com/uncleyong/p/17283062.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值