gpt4 book ai didi

java - Spring boot 不明确的处理程序

转载 作者:行者123 更新时间:2023-11-29 04:46:17 25 4
gpt4 key购买 nike

我使用 Spring Boot。我创建了这两种方法:

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

当我尝试登录 Web 应用程序时,我得到:

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

看起来,它无法对数据类型进行区分。

所以需要修改URL?最新版本中有任何修复吗?

最佳答案

根据 Spring MVC documentation ,当 URL 匹配多个模式时,将使用排序来查找最具体的匹配:

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/*.

应用这些规则后,当 Spring MVC 无法决定哪一个更具体时,它将抛出该异常。解决此问题的一种方法是使其中一个更具体:

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

关于java - Spring boot 不明确的处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36982439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com