[英]How to resolve ambiguous mapping with Spring Rest Controllers?
[英]How to resolve request mapping “ambiguous” situation in spring controller?
我编写了一个 spring 控制器,其中我只想对所有方法使用单个 URL。 即使我使用不同的方法签名int、string、object我也收到错误。
@RequestMapping(value="problemAPI/ticket", method = RequestMethod.GET )
public @ResponseBody String getTicketData(@RequestParam("customerId") int customerId) {
return "customer Id: "+customerId+" has active Ticket:1010101";
}
@RequestMapping(value="problemAPI/ticket", method = RequestMethod.GET )
public @ResponseBody String getTicketStatusByCustname(@RequestParam("customerName") String customerName) {
return "Mr." + customerName + " Your Ticket is Work in Progress";
}
@RequestMapping(value="problemAPI/ticket", method = RequestMethod.POST )
public @ResponseBody String saveTicket(@RequestBody TicketBean bean) {
return "Mr." + bean.getCustomerName() + " Ticket" + bean.getTicketNo() + " has been submitted successfuly";
}
错误:
java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'problemTicketController' bean method
public String com.nm.controller.webservice.ticket.problem.ProblemTicketController.getTicketData(int)
to {[/problemAPI/ticket],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'problemTicketController' bean method
public java.lang.String com.nm.controller.webservice.ticket.problem.ProblemTicketController.getTicketByCustname(int) mapped.
您可以通过使用params
注释属性显式指定查询参数来实现此目的:
@RequestMapping(
value = "problemAPI/ticket",
params = "customerId",
method = RequestMethod.GET
)
public @ResponseBody String getTicketData(@RequestParam("customerId") int customerId){
return "customer Id: " + customerId + " has active Ticket:1010101";
}
@RequestMapping(
value = "problemAPI/ticket",
params = "customerName",
method = RequestMethod.GET
)
public @ResponseBody String getTicketStatusByCustname(@RequestParam("customerName") String customerName){
return "Mr." + customerName + " Your Ticket is Work in Progress";
}
为了使它更干净,您可以使用别名注释,如@GetMapping
和@PostMapping
:
@GetMapping(
value = "problemAPI/ticket",
params = "customerName"
)
public @ResponseBody String getTicketStatusByCustname(@RequestParam("customerName") String customerName) {
}
@PostMapping(
value = "problemAPI/ticket"
)
public @ResponseBody String saveTicket(@RequestBody TicketBean bean) {
return "Mr." + bean.getCustomerName() + " Ticket" + bean.getTicketNo() + " has been submitted successfuly";
}
https://stackoverflow.com/users/5091346/andrii-abramov提到的答案是正确的。 然而,RESTful 服务的 JSR-311 规范提到了以下内容:
此类方法称为子资源方法,被视为普通资源方法(参见第 3.3 节),除了该方法仅针对与通过将资源类的 URI 模板与 URI 模板连接而创建的 URI 模板匹配的请求 URI 调用的方法。
不过,使用 spring 框架我们可以实现这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.