Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling ambiguous handler methods mapped in REST application with Spring

Tags:

I tried to use some code as below:

@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] 
like image 467
mikezang Avatar asked Feb 02 '16 14:02

mikezang


1 Answers

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.

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> getBrands(@RequestParam(value="name") String name) {     return brandService.getSome(name); } 

Using the approach described above:

  • Requests like GET http://localhost:8080/api/brand/1 will be handled by getBrand(Integer).
  • Requests like GET http://localhost:8080/api/brand?name=nike will be handled by getBrand(String).

Just a hint: As a common practice, prefer plural nouns for collections of resources. So instead of /brand, use /brands.

like image 118
cassiomolin Avatar answered Sep 26 '22 13:09

cassiomolin