Spring boot Ambiguous handler

元气小坏坏 提交于 2021-02-17 03:22:30

问题


I use Spring Boot. I created theses two method:

@RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
public UserAppDto getNameByUserId(@PathVariable("userId") Long userId) {
    return userService.getByUserId(userId);
}

@RequestMapping(value = "/user/{username}", method = RequestMethod.GET)
public UserAppDto getNameByUsername(@PathVariable("username") String username) {
    return userService.getNameByUsername(username);
}

When i try to log in the web application, i get:

java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/rest/user/bsmith': {public com.zenar.dto.UserAppDto com.zenar.controller.UserController.getNameByUsername(java.lang.String), public com.zenar.dto.UserAppDto com.zenar.controller.UserController.getNameByUserId(java.lang.Long)}

Seem like, it's not able to do difference on the data type.

So need to modify URL? Any fix in the latest release?


回答1:


According to Spring MVC documentation, when a URL matches multiple patterns, a sort is used to find The Most Specific Match:

A pattern with a lower count of URI variables and wild cards is considered more specific. For example /hotels/{hotel}/* has 1 URI variable and 1 wild card and is considered more specific than /hotels/{hotel}/** which as 1 URI variable and 2 wild cards.

If two patterns have the same count, the one that is longer is considered more specific. For example /foo/bar* is longer and considered more specific than /foo/*.

When two patterns have the same count and length, the pattern with fewer wild cards is considered more specific. For example /hotels/{hotel} is more specific than /hotels/*.

After applying these rules, when Spring MVC couldn't decide which one is more specific, it will throw that exception. One way for fixing this problem is to make one of them More specific:

@RequestMapping(value = "/user/{userId:\\d+}", method = RequestMethod.GET)
public UserAppDto getNameByUserId(@PathVariable("userId") Long userId) {
    return userService.getByUserId(userId);
}


来源:https://stackoverflow.com/questions/36982439/spring-boot-ambiguous-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!