简体   繁体   中英

Spring boot Ambiguous handler

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM