報錯信息
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;
}
}
此時就可以正常運行了