SpringMVC源码 3.3 DispatchServlet逻辑处理

SpringMVC源码 3.3 DispatchServlet逻辑处理


FramewServlet请求引导
我们知道在HttpServlet中提供了相应的服务方法,他们是doDelete、doGet、doPost、doPut、doOption、doTrace,他们根据请求的不同形式引导至相应的函数进行处理。我们最常用的无非是doGet和doPost两个方法。
在FrameworkServlet对HttpServlet的各个do方法进行了重写。一下是doGet和doPost在FrameworkServlet中的实现。
在不同的方法中,Spring并没有做特殊处理,而是将程序再次统一引导至processRequest(request, response);方法
FrameworkServlet.doGet/doPost()
@Override
protected final void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
      processRequest(request, response);
}
@Override
protected final void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
     processRequest(request, response);
}

FramewServlet和DispatchServlet对请求准备工作
在processRequest方法中,开始对请求做了一些处理,主要是一些准备工作,具体的细节继续封装到可doService函数中。主要做了以下的一些准备工作。
(1)为了保证当前的线程中的LocaleContext和RequestAttribute这两个属性在当前请求之后还能够被恢复,所以先提取这两个属性保存起来
(2)根据当前Request创建对应的LocaleContext和RequestAttribute,并绑定到当前线程
(3)将请求委托给doService函数,继续进行处理
(4)请求处理结束后,恢复线程到原始状态
(5)请求处理结束后无论成功与否都发布事件通知。
FrameworkServlet.processRequest()
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {

     long startTime = System.currentTimeMillis();
     Throwable failureCause = null;

     LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
     LocaleContext localeContext = buildLocaleContext(request);

     RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
     ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

     WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
     asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

     initContextHolders(request, localeContext, requestAttributes);

     try {
            doService(request, response);
     }catch (ServletException ex) {
           failureCause = ex;
           throw ex;
     }catch (IOException ex) {
           failureCause = ex;
           throw ex;
     }catch (Throwable ex) {
           failureCause = ex;
           throw new NestedServletException("Request processing failed", ex);
     }

     finally {
           resetContextHolders(request, previousLocaleContext, previousAttributes);
           if (requestAttributes != null) {
                requestAttributes.requestCompleted();
           }
           if (logger.isDebugEnabled()) {
                if (failureCause != null) {
                     this.logger.debug("Could not complete request", failureCause);
                }else {
                     if (asyncManager.isConcurrentHandlingStarted()) {
                           logger.debug("Leaving response open for concurrent processing");
                     }else {
                           this.logger.debug("Successfully completed request");
                     }
                }
           }

           publishRequestHandledEvent(request, response, startTime, failureCause);
     }
}

在DispatchServlet.doService()中,仍然没有对Handler之类的处理。依旧是一些准备工作。
(1)将DispatchServlet初始化中创建的组件,添加到Request属性中,这些属性在接下来对Request的处理中使用。
(2)进入doDispatch函数,也就是真正的请求处理逻辑

DispatchServlet.doService()
protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
     if (logger.isDebugEnabled()) {
           .....
     }

     .......

      // Make framework objects available to handlers and view objects.
     request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, getWebApplicationContext());
     request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
     request.setAttribute(THEME_RESOLVER_ATTRIBUTE, this.themeResolver);
     request.setAttribute(THEME_SOURCE_ATTRIBUTE, getThemeSource());
     FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(request, response);
     if (inputFlashMap != null) {
           request.setAttribute(INPUT_FLASH_MAP_ATTRIBUTE, Collections.unmodifiableMap(inputFlashMap));
     }
     request.setAttribute(OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
     request.setAttribute(FLASH_MAP_MANAGER_ATTRIBUTE, this.flashMapManager);

     try {
            doDispatch(request, response);
     } finally {
           if (!WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
                // Restore the original attribute snapshot, in case of an include.
                if (attributesSnapshot != null) {
                     restoreAttributesAfterInclude(request, attributesSnapshot);
                }
           }
     }
}


DispatchServlet真正的逻辑处理 doDispatch()
在doDispatch函数中开始了真正处理请求的逻辑。主要分成以下几个步骤:
(1)检查是否存在MultipartResolver组件、是否为Multipart类型的Request。如果是的话返回MultipartHttpServletRequest
(2)通过request信息寻找可用的Handler
(3)已经获得了Handler的情况下,根据Handler匹配对应的HandlerAdapter
(4)调用Handler,返回视图
(5)对于视图的处理
DispatchServlet.doDispatch()
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 = null;
           Exception dispatchException = null;

           try {
               //判断是否存在MultipartResolver组件、判断是否为Multipart类型的Request,如果通过返回MultipartHttpServletRequest,不通过返回原来的request。
                 processedRequest = checkMultipart(request);
                multipartRequestParsed = (processedRequest != request);

                // Determine handler for the current request.
                // 根据request信息寻找可用的Handler。
                 mappedHandler = getHandler(processedRequest);
                if (mappedHandler == null || mappedHandler.getHandler() == null) {
                     //如果没有可以匹配的Handler则通过response返回错误信息
                     noHandlerFound(processedRequest, response);
                     return;
                }

                // Determine handler adapter for the current request.
                //根据当前可用的Handler寻找对应的HandlerAdapter
                 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()) {
                           logger.debug("Last-Modified value for [" + getRequestUri(request) + "] is: " + lastModified);
                     }
                     if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                           return;
                     }
                }

                if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                     return;
                }

                // Actually invoke the handler.
                // 真正调用handler,并返回视图
                 mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

                if (asyncManager.isConcurrentHandlingStarted()) {
                     return;
                }
                applyDefaultViewName(request, mv);
                mappedHandler.applyPostHandle(processedRequest, response, mv);
           } catch (Exception ex) {
                dispatchException = ex;
           }
           processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
     } catch (Exception ex) {
           triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
     } catch (Error err) {
           triggerAfterCompletionWithError(processedRequest, response, mappedHandler, err);
     } finally {
           if (asyncManager.isConcurrentHandlingStarted()) {
                // Instead of postHandle and afterCompletion
                if (mappedHandler != null) {
                     mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
                }
           } else {
                // Clean up any resources used by a multipart request.
                if (multipartRequestParsed) {
                     cleanupMultipart(processedRequest);
                }
           }
     }
}



遍历HandlerMapping获取匹配Request的Handler
在getHandler函数中,遍历了DispatchServlet中初始化的HandlerMappings数组,顺序如下: RequestMappingHandlerMapping ,BeanNameUrlHandlerMapping, SimpleUrlHandlerMapping。
调用hm.getHandler,看是否能返回匹配的HandlerExecutionChain。hm.getHandler是定义在AbstractHandlerMapping中的。

其实在匹配过程中并不需要匹配HandlerMapping,只需要遍历HandlerMapping,然后去用这个HandlerMapping根据Request匹配出Handler,能匹配出Handler就可以了,然后通过HandlerExecutionChain返回
DispatchServlet.getHandler()
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
     for (HandlerMapping hm : this.handlerMappings) {
           if (logger.isTraceEnabled()) {
                logger.trace("Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
           }
           HandlerExecutionChain handler = hm.getHandler(request);
           if (handler != null) {  return handler;  }
     }
     return null;
}


函数首先或调用getHandlerInternal函数,根据request获取对应的Handler.如果没有找到对应的Handler则会去匹配默认的Handler,还是没有找到默认的handler就会返回null。要是找到的Handler是String类型的时候,那就意味着返回的是配置的bean的名称,需要更具bean的名称在容器中找到对应的bean。最后通过getHandlerExecutionChain方法对Handler进行封装。
AbstractHandlerMapping .getHandler()
public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
      Object handler = getHandlerInternal(request);
     if (handler == null) {
           handler = getDefaultHandler();
     }
     if (handler == null) {
           return null;
     }
     // Bean name or resolved handler?
     if (handler instanceof String) {
           String handlerName = (String) handler;
           handler = getApplicationContext().getBean(handlerName);
     }
     return getHandlerExecutionChain(handler, request);
}

在AbstractHandlerMethodMapping和AbstractURLHandlerMapping中对getHandlerInternal(request)有具体的实现。也是从HandlerMapping中匹配出Handler具体逻辑。
AbstractHandlerMapping
----AbstractHandlerMethodMapping<T>
--------RequestMappingInfoHandlerMapping extends AbstractHandlerMethodMapping<RequestMappingInfo>
------------RequestMappingHandlerMapping (代替了原来的DefaultAnnotationHandlerMapping)
----AbstractURLHandlerMapping
--------BeanNameUrlHandlerMapping
--------SimpleUrlHandlerMapping
--------DefaultAnnotationHandlerMapping(废弃)


(1)首先根据request信息获取对应的request路径lookupPath
(2)通过lookupPath在RequestMappingInfoHandlerMapping.urlMap中匹配出对应的RequestMappingInfo。
MultiValueMap<String, > urlMap = new LinkedMultiValueMap<String, RequestMappingInfo >();
(3)已经获取了requestUri对应的RequestMappingInfo,然后根据RequestMappingInfo从RequestMappingInfoHandlerMapping.handlerMethods中获取HandlerMethod
Map<RequestMappingInfo , HandlerMethod> handlerMethods = new LinkedHashMap<RequestMappingInfo , HandlerMethod>();
(4)将HandlerMethod封装为HandlerExecutionXChain

额外:
urlMap, handlerMethods这两个RequestMappingHandlerMapping中的属性,是在初始化的时候加载的。加载了@Controller和@RequestMapping注解的类和函数
afterPropertiesSet() -> initHandlerMethods() -> detectHandlerMethods(String beanName); 中查看源代码。
(1)在ApplicationContext中获取所有的bean的name。String[] beanNames = getApplicationContext().getBeanNamesForType(Object.class)
(2)遍历beanNames,判断是不是RequestMappingHandlerMapping需要的Handler。
protected boolean isHandler(Class<?> beanType) {
      return ((AnnotationUtils.findAnnotation(beanType, Controller.class) != null) ||
            (AnnotationUtils.findAnnotation(beanType, RequestMapping.class) != null));
}
(3)根据匹配出来的bean,然后从中@RequestMapping定义的uri和对应的方法MethodHandler组成对应

AbstractHandlerMethodMapping.gethandlerInternal()
AbstractHandlerMethodMapping.lookupHandlerMethod()
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
     //根据request获取对应的路径,  请求路径为/captchaService/v1/getCaptcha,lookupPath为/v1/getCaptcha,去掉了ContentPath,留下了RequestUri
     String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
     if (logger.isDebugEnabled()) {
           logger.debug("Looking up handler method for path " + lookupPath);
     }
     //匹配需要的Handler
      HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
     if (logger.isDebugEnabled()) {
           ........
     }
     return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
}
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
     List<Match> matches = new ArrayList<Match>();
      List< RequestMappingInfo > directPathMatches = this.urlMap.get(lookupPath);
     if (directPathMatches != null) {
            addMatchingMappings(directPathMatches, matches, request);
     }
     if (matches.isEmpty()) {
           // No choice but to go through all mappings...
           addMatchingMappings(this.handlerMethods.keySet(), matches, request);
     }

     if (!matches.isEmpty()) {
           Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
           Collections.sort(matches, comparator);
           if (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 new IllegalStateException(
                                "Ambiguous handler methods mapped for HTTP path '" + request.getRequestURL() + "': {" +
                                m1 + ", " + m2 + "}");
                }
           }
           handleMatch(bestMatch.mapping, lookupPath, request);
            return bestMatch.handlerMethod;
     }
     else {
           return handleNoMatch(handlerMethods.keySet(), lookupPath, request);
     }
}
private void addMatchingMappings(Collection<RequestMappingInfo> mappings, List<Match> matches, HttpServletRequest request) {
     for (RequestMappingInfo mapping : mappings) {
           RequestMappingInfo match = getMatchingMapping(mapping, request);
           if (match != null) {
                 matches.add(new Match(match, this.handlerMethods.get(mapping)));
           }
     }
}


根据获取到Handler匹配合适的HandlerAdapter

遍历HandlerAdapter,然后匹配当前hanler是否满足要求,如果满足则返回这个HandlerAdapter
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
     for (HandlerAdapter ha : this.handlerAdapters) {
           if (logger.isTraceEnabled()) {
                logger.trace("Testing handler adapter [" + ha + "]");
           }
           if ( ha.supports(handler) ) {
                return ha;
           }
     }
     throw new ServletException("No adapter for handler [" + handler +
                "]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}

HttpRequestHandlerAdapter
public boolean supports(Object handler) {
     return (handler instanceof HttpRequestHandler);
}
SimpleControllerHandlerAdapter
public boolean supports(Object handler) {
     return (handler instanceof Controller);
}
AbstractHandlerMethodAdapter
public final boolean supports(Object handler) {
     return (handler instanceof HandlerMethod && true);
}


使用HandlerAdapter处理Handler,获取请求结果















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值