如何解决弹簧控制器中的请求映射“模糊”情况?

Rus*_*iye 4 java spring spring-mvc

我编写了一个spring控制器,在其中我只想对所有方法使用单个URL。即使我使用不同的方法签名int,字符串,对象,我也遇到了错误。

@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";
}
Run Code Online (Sandbox Code Playgroud)

错误:

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.
Run Code Online (Sandbox Code Playgroud)

And*_*mov 7

You can achieve this by explicitly specifying query parameters with params annotation property:

@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";
}
Run Code Online (Sandbox Code Playgroud)

To make it cleaner you can use alias annotations like @GetMapping and @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";
}
Run Code Online (Sandbox Code Playgroud)