SpringMvc @RequestMapping原理

讲这个之前,我们得先知道在SpringMvc启动时,会加载所有的Bean类,就是加了@Controller,@Component等组件标识的类,然后会把@RequestMapping的方法也加入到一个集合。放入到上下文环境中。

发起请求后的执行流程是:检查request类型-->获取匹配的Handlemethod-->查找拦截器-->组成HandlerExecutionChain执行链-->获取方法执行链对象的适配器(HandlerAdapter)-->然后反射执行业务方法。

有一个大概的了解之后,开始源码分析:

protected void doDispatch(HttpServletRequest request,HttpServletResponse response) throws Exception {
        HttpServletRequest processedRequest = request;
        HandlerExecutionChain mappedHandler = null;
        boolean multipartRequestParsed = false;

        WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

        try {
            ModelAndView mv = ;
            Exception dispatchException = ;

             {
                processedRequest = checkMultipart(request);
                multipartRequestParsed = processedRequest != request;

                // Determine handler for the current request.
          //获取匹配的执行链
mappedHandler = getHandler(processedRequest); if (mappedHandler == null || mappedHandler.getHandler() == ) { noHandlerFound(processedRequest,response); return; } Determine handler adapter for the current request.
//根据匹配到的执行链对象,获取合适的适配器
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); Process last-modified header,if supported by the handler. String method = request.getMethod(); boolean isGet = "GET".equals(method); if (isGet || "HEAD".equals(method)) { long lastModified = ha.getLastModified(request,mappedHandler.getHandler()); if (logger.isDebugEnabled()) { String requestUri = urlPathHelper.getRequestUri(request); logger.debug("Last-Modified value for [" + requestUri + "] is: " + lastModified); } if (new ServletWebRequest(request,response).checkNotModified(lastModified) && isGet) { ; } } if (!mappedHandler.applyPreHandle(processedRequest,response)) { { Actually invoke the handler.
            //在这里面反射执行业务方法
mv = ha.handle(processedRequest,response,mappedHandler.getHandler()); } finally (asyncManager.isConcurrentHandlingStarted()) { ; } } applyDefaultViewName(request,mv); mappedHandler.applyPostHandle(processedRequest,mv); } catch (Exception ex) { dispatchException = ex; } processDispatchResult(processedRequest,mappedHandler,mv,dispatchException); } (Exception ex) { triggerAfterCompletion(processedRequest,ex); } (Error err) { triggerAfterCompletionWithError(processedRequest,err); } { (asyncManager.isConcurrentHandlingStarted()) { Instead of postHandle and afterCompletion mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest,response); ; } Clean up any resources used by a multipart request. (multipartRequestParsed) { cleanupMultipart(processedRequest); } } }

从标红部分点进去,到AbstractHandlerMethodAdapter类的handle方法-->RequestMappingHandlerAdapter类的handleInternal方法-->RequestMappingHandlerAdapter类的invokeHandleMethod

-->RequestMappingHandlerAdapter类的invokeAndHandle-->ServletInvocableHandlerMethod类的invokeForRequest-->InvocableHandlerMethod类的invokeForRequest。该方法代码如下:

public final Object invokeForRequest(NativeWebRequest request,ModelAndViewContainer mavContainer,Object... providedArgs)  Exception {

        Object[] args = getMethodArgumentValues(request,mavContainer,providedArgs);
         (logger.isTraceEnabled()) {
            StringBuilder sb = new StringBuilder("Invoking [");
            sb.append(this.getBeanType().getSimpleName()).append(".");
            sb.append(getMethod().getName()).append("] method with arguments ");
            sb.append(Arrays.asList(args));
            logger.trace(sb.toString());
        }
     //执行方法 Object returnValue
= invoke(args); (logger.isTraceEnabled()) { logger.trace("Method [" + getMethod().getName() + "] returned [" + returnValue + "]"); } returnValue; }

然后就可以执行方法了。需要注意的是匹配方法时,根据@RequestMapping里面的value路径来匹配的,如果匹配到的有多个,如你配置了通配符,也配置了精确配置,他都会匹配到放在一个集合中,根据规则排序,然后取集合的第一个元素。有兴趣的可以看看这个排序的规则,理论上肯定是路径越精确的会优先,具体代码实现如下:

    protected HandlerMethod lookupHandlerMethod(String lookupPath,HttpServletRequest request)  Exception {
        List<Match> matches = new ArrayList<Match>();

        List<T> directPathMatches = this.urlMap.get(lookupPath);
        if (directPathMatches != ) {
            addMatchingMappings(directPathMatches,matches,request);
        }

         (matches.isEmpty()) {
             No choice but to go through all mappings
            addMatchingMappings(.handlerMethods.keySet(),1)">matches.isEmpty()) {
       //排序规则 Comparator
<Match> comparator = new MatchComparator(getMappingComparator(request));
//进行排序 Collections.sort(matches,comparator);
(logger.isTraceEnabled()) { logger.trace("Found " + matches.size() + " matching mapping(s) for [" + lookupPath + "] : " + matches); } Match bestMatch = matches.get(0); if (matches.size() > 1) { Match secondBestMatch = matches.get(1); if (comparator.compare(bestMatch,secondBestMatch) == 0) { Method m1 = bestMatch.handlerMethod.getMethod(); Method m2 = secondBestMatch.handlerMethod.getMethod(); throw IllegalStateException( "Ambiguous handler methods mapped for HTTP path '" + request.getRequestURL() + "': {" + m1 + "," + m2 + "}"); } } handleMatch(bestMatch.mapping,lookupPath,request); bestMatch.handlerMethod; } else handleNoMatch(handlerMethods.keySet(),request); } }

 

原文地址:https://www.cnblogs.com/javammc

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原理介绍,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。传统事务中回滚点的使...
今天小编给大家分享的是一文解析spring中事务的传播机制,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区别,具有一定借鉴价值,需要的朋友可以参考下。下面就和我一起来看看吧。Spring Cloud Netfli...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。第一步:整合pom文件,在S...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。List 坑列表 = new ArrayList(2);...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓存的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇...
本篇内容主要讲解“Spring中的@Autowired和@Resource注解怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学...
今天小编给大家分享一下SpringSecurity怎么定义多个过滤器链的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家
这篇文章主要介绍“Spring的@Conditional注解怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring的@Con...
这篇文章主要介绍了SpringCloudGateway的熔断限流怎么配置的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringCloud&nb...
今天小编给大家分享一下怎么使用Spring解决循环依赖问题的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考
这篇文章主要介绍“Spring事务及传播机制的原理及应用方法是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Sp...
这篇“SpringCloudAlibaba框架实例应用分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价
本篇内容主要讲解“SpringBoot中怎么使用SpringMVC”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习...
这篇文章主要介绍“SpringMVC适配器模式作用范围是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“SpringMVC
这篇“导入SpringCloud依赖失败如何解决”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家...
这篇文章主要讲解了“SpringMVC核心DispatcherServlet处理流程是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来
今天小编给大家分享一下SpringMVCHttpMessageConverter消息转换器怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以...
这篇文章主要介绍“Spring框架实现依赖注入的原理是什么”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Spring框架...
本篇内容介绍了“Spring单元测试控制Bean注入的方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下