如何解决请求映射"模糊"春季控制器的情况?

时间:2017-06-08 07:45:34

标签: java spring spring-mvc

我编写了一个弹簧控制器,我只想在所有方法中使用单个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.

3 个答案:

答案 0 :(得分:5)

您可以通过使用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";
}

答案 1 :(得分:0)

https://stackoverflow.com/users/5091346/andrii-abramov 提到的答案似乎没问题,只是因为一种方法采用 int 类型的查询参数,而另一种方法采用 String 类型的查询参数。如果两个查询参数的数据类型相同,上述方法仍然会失败,抛出模糊映射错误。正确的方法是重新设计您的 API,这意味着不同的输入有不同的端点。

答案 2 :(得分:0)

https://stackoverflow.com/users/5091346/andrii-abramov 提到的答案是正确的。但是,RESTful 服务的 JSR-311 规范提到了以下内容:

此类方法称为子资源方法,被视为普通资源方法(请参阅第 3.3 节),只是该方法仅针对与通过将资源类的 URI 模板与方法的 URI 模板。

不过,使用 spring 框架我们可以实现这一点。