java 如何解决spring控制器中请求Map“二义性”的情况?

txu3uszq  于 2023-03-11  发布在  Java
关注(0)|答案(2)|浏览(136)

我写了一个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.
oxiaedzo

oxiaedzo1#

您可以通过使用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 getTicketStatusByCustomerName(
    @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
) {
    return "Mr." + customerName + " Your Ticket is Work in Progress";
}

@PostMapping(
    value = "problemAPI/ticket"
)
public @ResponseBody String saveTicket(@RequestBody TicketBean bean) {
    return "Mr." + bean.getCustomerName() + " Ticket" +  bean.getTicketNo() + " has been submitted successfuly";
}
bxfogqkk

bxfogqkk2#

https://stackoverflow.com/users/5091346/andrii-abramov提到的答案是正确的,但是RESTful服务的JSR-311规范提到了下面的内容:
这种方法被称为子资源方法,被视为普通的资源方法(参见3.3节),除了该方法仅为与URI模板相匹配的请求URI调用,该URI模板是通过将资源类的URI模板与方法的URI模板连接而创建的。
不过,使用Spring框架我们可以做到这一点。

相关问题