问题
最近,为了给大家搭建一个学习环境,开发了几个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
- Ambiguous restful handler methods mappedambiguous restful handler methods ambiguous ambiguousmatchexception reflection ambiguous 39 builderexception collection ambiguous overloaded ambiguous mathfunc double configdaoimpl constructor ambiguous call overloaded ambiguous property illegal byte ambiguous问题17 文号valueerror ambiguous python handler