使用Spring处理REST应用程序中映射的模棱两可的处理程序方法 [英] Handling ambiguous handler methods mapped in REST application with Spring
问题描述
我尝试使用如下代码:
@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);
}
但是我遇到这样的错误,我该怎么办?
But I got error like this, how can I do?
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)
处理.
Spring can't distinguish if the request GET http://localhost:8080/api/brand/1
will be handled by getBrand(Integer)
or by getBrand(String)
because your mapping is ambiguous.
尝试对getBrand(String)
方法使用查询参数.似乎更合适,因为您正在执行查询:
Try using a query parameter for the getBrand(String)
method. It seems more appropriate, since you are performing a query:
@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)
处理.
- Requests like
GET http://localhost:8080/api/brand/1
will be handled bygetBrand(Integer)
. - Requests like
GET http://localhost:8080/api/brand?name=nike
will be handled bygetBrand(String)
.
只是一个提示:通常的做法是,在资源集合中首选复数名词.因此,请使用/brands
代替/brand
.
Just a hint: As a common practice, prefer plural nouns for collections of resources. So instead of /brand
, use /brands
.
这篇关于使用Spring处理REST应用程序中映射的模棱两可的处理程序方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!