使用Spring处理在REST应用程序中映射的模糊处理程序方法

mik*_*ang 8 rest spring 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);
}
Run Code Online (Sandbox Code Playgroud)

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

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]
Run Code Online (Sandbox Code Playgroud)

cas*_*lin 19

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> getBrand(@RequestParam(value="name") String name) {
    return brandService.getSome(name);
}
Run Code Online (Sandbox Code Playgroud)

使用上述方法:

  • 类似的请求GET http://localhost:8080/api/brand/1将由getBrand(Integer).处理.
  • 类似的请求GET http://localhost:8080/api/brand?name=nike将由getBrand(String).处理.

只是一个提示

作为一种好的做法,请始终使用复数名词作为资源.而不是/brand,使用/brands.


san*_*thy 8

@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);
}
Run Code Online (Sandbox Code Playgroud)

当您运行应用程序并访问您尝试编码的端点时,您会意识到以下内容,“ http://localhost:8086/brand/1 ”和“ http://localhost:8086/brand/FooBar ”对应相同URL 格式(可以描述为协议+端点+'品牌'+)。因此,SpringBoot 是否应该使用 String 数据类型或 Integer 调用函数“getBrand”,本质上会感到困惑。因此,为了解决这个问题,我建议您使用@cassiomolin 提到的查询参数,或者为两个调用使用单独的路径。这可能违反 REST 原则,但假设您只是在做一个示例应用程序,这是另一种解决方法。

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

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

这对我有用。