簡體   English   中英

如何解決spring控制器中請求映射“不明確”的情況?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM