使用Spring处理在REST应用程序中映射的模糊处理程序方法
作者:互联网
我尝试使用如下代码:
@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> getBrand(@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)处理.
只是一个提示
作为一种好的做法,请始终使用复数名词作为资源.而不是/品牌,使用/品牌.
标签:rest,spring,path-variables,request-mapping 来源: https://codeday.me/bug/20190715/1465867.html