Ambiguous handler methods mapped for '/user/1'

绝地灬酷狼 2022-03-30 13:52 243阅读 0赞

使用rest编程风格时,可以直接将变量值放入到url中,传递到后台,后台自动识别对应的方法,方便很多。

但若出现方法重载的情况,则可能会出问题,如下

  1. @RestController
  2. @RequestMapping("/user")
  3. public class UserController {
  4. @Resource
  5. private UserService us;
  6. @ResponseBody
  7. @GetMapping("/{username}")
  8. public User getUser(@PathVariable("username")String username) {
  9. return us.getUser(username);
  10. }
  11. @ResponseBody
  12. @GetMapping("/{id}")
  13. public User getUser(@PathVariable("id")Integer id) {
  14. return us.findUserById(id);
  15. }
  16. }

在浏览器地址栏访问 http://localhost:8080/user/1 或 http://localhost:8080/user/lucy 时均会出现如下错误

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L21hZ2kxMjAx_size_16_color_FFFFFF_t_70

Ambiguous handler methods mapped for ‘/user/lucy’ ,字面含义,模棱两可的处理方法对于’/user/lucy’ ,有两个或以上的方法对于’/user/lucy’,这里说明,spring无法根据传参的类型自动匹配处理的方法。

此时,如果依然想使用rest编程风格,则必须改变请求url的格式,必须时url对应的方法不产生歧义

针对上面的例子,可以给变量前面增加参数的类型简写,这样就可以匹配到不同的方法

  1. @ResponseBody
  2. @GetMapping("/s/{username}")
  3. public User getUser(@PathVariable("username")String username) {
  4. return us.getUser(username);
  5. }
  6. @ResponseBody
  7. @GetMapping("/i/{id}")
  8. public User getUser(@PathVariable("id")Integer id) {
  9. return us.findUserById(id);
  10. }

再到浏览器地址栏通过 http://localhost:8080/user/s/lucy 或 http://localhost:8080/user/i/1 来请求

均可以正常访问到后台对象内容

20190106144856291.png

发表评论

表情:
评论列表 (有 0 条评论,243人围观)

还没有评论,来说两句吧...

相关阅读