使用 Spring 处理映射在 REST 应用程序中的模糊处理程序方法 [英] Handling ambiguous handler methods mapped in REST application with Spring

查看:42
本文介绍了使用 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);
}

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

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> 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) 处理.
  • 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).

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

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

这篇关于使用 Spring 处理映射在 REST 应用程序中的模糊处理程序方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆