spring - 使用 Spring 处理 REST 应用程序中映射的不明确处理程序方法

标签 spring rest path-variables request-mapping

我尝试使用如下代码:

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Brand getBrand(@PathVariable Integer id) {
    return brandService.getOne(id);
}

@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public List<Brand> getBrand(@PathVariable String name) {
    return brandService.getSome(name);
}

但是我遇到这样的错误,我该怎么办?

java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/api/brand/1': {public java.util.List com.zangland.controller.BrandController.getBrand(java.lang.String), public com.zangland.entity.Brand com.zangland.controller.BrandController.getBrand(java.lang.Integer)}
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.lookupHandlerMethod(AbstractHandlerMethodMapping.java:375) ~[spring-webmvc-4.2.4.RELEASE.jar:4.2.4.RELEASE]

最佳答案

Spring 无法区分请求 GET http://localhost:8080/api/brand/1 是由 getBrand(Integer) 处理还是由 getBrand(String) 因为您的映射不明确。

尝试使用 getBrand(String) 方法的查询参数。这似乎更合适,因为您正在执行查询:

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Brand getBrand(@PathVariable Integer id) {
    return brandService.getOne(id);
}

@RequestMapping(method = RequestMethod.GET)
public List<Brand> getBrands(@RequestParam(value="name") String name) {
    return brandService.getSome(name);
}

使用上述方法:

  • GET http://localhost:8080/api/brand/1 这样的请求将由 getBrand(Integer) 处理。
  • GET http://localhost:8080/api/brand?name=nike 这样的请求将由 getBrand(String) 处理。
<小时/>

提示:作为一种常见做法,资源集合更喜欢使用复数名词。因此,请使用 /brands,而不是 /brand

关于spring - 使用 Spring 处理 REST 应用程序中映射的不明确处理程序方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35155916/

相关文章:

java - Proguard混淆后如何保留@PathVariable参数名称

java - Spring MVC GET @ModelAttribute java.util.Date 类型带时间戳

json - -d 和 -u 参数的含义(和提供方法)是什么?

java - NPE 在我的休息舱服务中使用带有 Spring 的 Jersey

rest - 使用维基百科的 RecentChanges API 进行实时数据流

python - `哪个`在命令提示符下不起作用

java - Eclipse Spring Boot - 在 TransactionAutoConfiguration 和 Neo4jDataAutoConfiguration 之间检测到自动配置周期

java - CrudRepository 保存方法不会在数据库中保存任何内容

java - 将数组或列表传递给@Pathvariable - Spring/Java

java - 将默认的 Java 路径更改为 FreeBSD 中的其他路径