DispatchServlet流程 - 2

当DispatchServlet接到请求时,会先执行FrameWorkServlet类的service()方法,这个方法判断了请求的类型,例如“GET”,“POST"等等;
假设是POST请求,就调用doPost()方法,doPost()调用了processRequest()方法,
processRequest()执行了doServer()方法,开始真正的对 request 进行处理,设置相关对象到request中,核心代码如下:

protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 省略日志输出代码
// Keep a snapshot of the request attributes in case of an include,
// to be able to restore the original attributes after the include.

Map<String, Object> attributesSnapshot = null;    // request快照,后续处理中可以恢复数据
if (WebUtils.isIncludeRequest(request)) {
attributesSnapshot = new HashMap<String, Object>();
Enumeration<?> attrNames = request.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
if (this.cleanupAfterInclude || attrName.startsWith("org.springframework.web.servlet")) {
attributesSnapshot.put(attrName, request.getAttribute(attrName));
}
}
}

// Make framework objects available to handlers and view objects.
                // 封装框架的一些内置对象到 request 域中
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);
}
}
}

}

当相关对象设置到request之后,就会执行doDispatch(),对请求进行处理,所有类型的request都在这里获取对应的controller方法,可以获取request的HandlerMapping和HandlerAdapter,还可以对请求进行interceptor的处理。

DispatchServlet的doDispatch()核心代码:
由于代码太多,对一些不重要的代码进行省略,有兴趣可以自己参考源码
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
   HttpServletRequest processedRequest = request;
   
// 对 handler 的链式封装,可在其中挂载单个 handler 以及多个针对该 handler 的 intercepters
   HandlerExecutionChain mappedHandler = null; 
   boolean multipartRequestParsed = false;    // 标记当前request是否为上传文件请求,默认false
   WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

   try {
      ModelAndView mv = null;
      Exception dispatchException = null;

      try {
         processedRequest = checkMultipart(request);    // 判断请求是否文件请求,如果是,就将请求转换为文件请求,并用文件请求解析器解析请求
         multipartRequestParsed = (processedRequest != request);    // 解析完后返回被转换为文件请求的请求对象

         // Determine handler for the current request.
         mappedHandler = getHandler(processedRequest);    // 使用HandlerMapping处理器映射器根据url找到处理请求的Controller和处理方法
         if (mappedHandler == null || mappedHandler.getHandler() == null) {    // 没有找到对应的处理器映射器,则抛出异常
            noHandlerFound(processedRequest, response);
            return;
         }

         // Determine handler adapter for the current request.
       
 // HandlerAdapter将会根据适配的结果调用真正的处理器的功能处理方法,完成功能处理;并返回一个ModelAndView对象
        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)) {    // 如果是GET请求,则判断lastModified是否被修改,默认返回-1,不使用缓存。
            long lastModified = ha.getLastModified(request, mappedHandler.getHandler());
           // 省略日志输出代码
            if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
               return;
            }
         }

         // 遍历已初始化的拦截器集合,执行pre前置方法,如果返回false,则中断。
         if (!mappedHandler.applyPreHandle(processedRequest, response)) {
            return;
         }

         // Actually invoke the handler.
        // 执行HandlerMethod(处理器),并返回 ModelAndView
         mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

         if (asyncManager.isConcurrentHandlingStarted()) {
            return;
         }

         // 生成需要返回的视图名称
         applyDefaultViewName(request, mv);
         // 执行拦截器的post后置方法 
         mappedHandler.applyPostHandle(processedRequest, response, mv);
      }
      catch (Exception ex) {
         dispatchException = ex;
      }
        // 执行拦截器的after方法
        processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
   }
   // 省略catch块,出现异常也会执行拦截器的after方法
   // 省略finally块,用于释放上传文件的资源

}

可以看到doDispatch()根据request将路径名与所有已注册的路径 map 集合进行匹配,先找出一类路径,再将这类路径进行排序,找到 一个最佳匹配路径,随后获取该路径对应的方法。同时也会将注册了对应 URL 的过滤器挂载到该 chain 中,形成一条方法执行链,然后根据handler获取对应的HandlerAdapter并对请求执行了interceptor的q前置处理,然后调用handle()方法, 调该方法用子类的 handlerInternal() 方法来进行 handler的具体细化处理,并在这里又将 HandlerExecutionChain 强转回 HandlerMethod 对象,用于后续处理。

接下来,探讨handlerInternal()的具体流程。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值