Ambiguous handler methods mapped for 'xxx'問題記錄

參考

報錯信息

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Ambiguous handler methods mapped for '/mbOrder/01': {public java.util.List com.qf.controller.MybatisStuController.findByName(java.lang.String), public com.qf.javaBean.Order com.qf.controller.MybatisStuController.findOrderById(java.lang.String)}] with root cause
java.lang.IllegalStateException: Ambiguous handler methods mapped for '/mbOrder/01'

問題原因

在創(chuàng)建Restful風(fēng)格的url的時候,可以直接將參數(shù)變量值放入到url中,然后傳遞到后臺,后臺自動識別對應(yīng)的方法。

但是如果我們的接口方法中出現(xiàn)了方法重載的情況,則有可能會出現(xiàn)一些問題,如下:


public class ElasticController {
 
    @Autowired
    private BookService bookService;
 
    @RequestMapping("/book/{id}")
    public Book getBookById(@PathVariable String id) {
        Optional<Book> opt = bookService.findById(id);
        Book book = opt.get();
        log.warn(book.toString());
        return book;
    }
 
    @RequestMapping("/book/{title}")
    public Page<Book> getBookByTitleHighLight(@PathVariable("title") String title) {
        Page<Book> books = bookService.findByTitle(title, 1, 10);
        log.warn(books.toString());
        return books;
    }
 
}

此時則會出現(xiàn)如上錯誤
此時如果我們依然想使用Restful編程風(fēng)格,就必須改變請求得url格式,保證url對應(yīng)的方法不會產(chǎn)生歧義.

解決方法

只要保證一個類中多個方法請求的接口方法不一樣就可以了,可以是請求方法,請求參數(shù),url等不同,這樣就可以匹配到不同的方法.

public class ElasticController {
 
    @Autowired
    private BookService bookService;
 
    @RequestMapping("/book/id/{id}")
    public Book getBookById(@PathVariable String id) {
        Optional<Book> opt = bookService.findById(id);
        Book book = opt.get();
        log.warn(book.toString());
        return book;
    }
 
    @RequestMapping("/book/title/{title}")
    public Page<Book> getBookByTitleHighLight(@PathVariable("title") String title) {
        Page<Book> books = bookService.findByTitle(title, 1, 10);
        log.warn(books.toString());
        return books;
    }
 
}

此時就可以正常運行了

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容