How to resolve request mapping “ambiguous” situation in spring controller?

I have written a spring controller in which I just wanted to use single URL for all methods. Even I am using different method signature int, string, object i am getting error.

@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";
}

Error:

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.

Answer

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";
}

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";
}

Leave a Reply

Your email address will not be published. Required fields are marked *