美文网首页
Ambiguous handler methods mapped

Ambiguous handler methods mapped

作者: 顺风飘千里 | 来源:发表于2021-06-21 23:17 被阅读0次

参考

报错信息

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'

问题原因

在创建Restful风格的url的时候,可以直接将参数变量值放入到url中,然后传递到后台,后台自动识别对应的方法。

但是如果我们的接口方法中出现了方法重载的情况,则有可能会出现一些问题,如下:


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

此时则会出现如上错误
此时如果我们依然想使用Restful编程风格,就必须改变请求得url格式,保证url对应的方法不会产生歧义.

解决方法

只要保证一个类中多个方法请求的接口方法不一样就可以了,可以是请求方法,请求参数,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;
    }
 
}

此时就可以正常运行了

相关文章

网友评论

      本文标题:Ambiguous handler methods mapped

      本文链接:https://www.haomeiwen.com/subject/yyguyltx.html