DispatcherServlet源码笔记

开始

假设已经云配好了web.xml

web服务器在启动的时候会加载web.xml文件,则会调用配置在web.xml里的DispatcherServlet.init(),前提load-on-startup为正整数。

初始化

GenericServlet的init

public void init(ServletConfig config) throws ServletException {
    this.config = config;
    //空方法,由HttpServletBean实现
    this.init();
}
public void init() throws ServletException {}

HttpServletBean的init

public final void init() throws ServletException {
        PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
        if (!pvs.isEmpty()) {
            try {
                //将DispatcherServlet构造成BeanWrapper以便后续操作参数
                BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
                ResourceLoader resourceLoader = ...;
                bw.registerCustomEditor(...);
                //空方法,由子类实现
                initBeanWrapper(bw);
                bw.setPropertyValues(pvs, true);
            }
            catch (BeansException ex) {
                ...
            }
        }
        //空方法,由FrameworkServlet实现
        initServletBean();
    }

这里稍微看下PropertyAccessorFactory,其中有两个静态方法:

public static BeanWrapper forBeanPropertyAccess(Object target) {
    //基于java自审机制
    //在BeanWrapperImpl定义了BeanPropertyHandler内部类,持有PropertyDescriptor
    return new BeanWrapperImpl(target);
}
public static ConfigurablePropertyAccessor forDirectFieldAccess(Object target) {
    //直接操作Field
    //在DirectFieldAccessor定义了FieldPropertyHandler内部类,持有一个Field
    return new DirectFieldAccessor(target);
}

FrameworkServlet的initServletBean

protected final void initServletBean() throws ServletException {
    ...
    try {
        //初始化springMVC的ioc容器(子容器)
        //spring ioc根容器已经在ContextLoadListener中创建并初始化完毕
        this.webApplicationContext = initWebApplicationContext();
        //空方法
        initFrameworkServlet();
    } catch (ServletException | RuntimeException ex) {
        ...
    }
    ...
}

FrameworkServlet的initWebApplicationContext

protected WebApplicationContext initWebApplicationContext() {
    //从名称就知道,获取跟上下文,即ContextLoadListener创建初始化的ioc容器上下文
    WebApplicationContext rootContext =
                WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    //springMVC的上下文引用
    WebApplicationContext wac = null;
    if (this.webApplicationContext != null) {
        wac = this.webApplicationContext;
        if (wac instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
            if (!cwac.isActive()) {
                if (cwac.getParent() == null) {
                    //将spring的根容器设置为mvc容器的父容器
                    cwac.setParent(rootContext);
                }
                //配置刷新mvc容器
                configureAndRefreshWebApplicationContext(cwac);
            }
        }
    }
    if (wac == null) {
        //从servletContext中查找mvc容器
        wac = findWebApplicationContext();
    }
    if (wac == null) {
        //创建一个mvc容器并且调用configureAndRefreshWebApplicationContext进行初始化
        wac = createWebApplicationContext(rootContext);
    }
    if (!this.refreshEventReceived) {
        synchronized (this.onRefreshMonitor) {
            //模板方法,调用DispatcherServlet的onRefresh
            onRefresh(wac);
        }
    }
    if (this.publishContext) {
        String attrName = getServletContextAttributeName();
        //将mvc容器设置到servlet上下文中
        getServletContext().setAttribute(attrName, wac);
    }
    return wac;
}

FrameworkServlet的configureAndRefreshWebApplicationContext

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
    if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
        ...
    }
    wac.setServletContext(getServletContext());
    wac.setServletConfig(getServletConfig());
    wac.setNamespace(getNamespace());
    //添加监听器,容器会在某个事件完成时,发布一个Event,之后会执行已注册的监听器的方法
    //观察者模式
    wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
    ConfigurableEnvironment env = wac.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
    }
    //空方法
    postProcessWebApplicationContext(wac);
    //执行配置的ApplicationContextInitializer,在容器创建初始化之前执行
    applyInitializers(wac);
    //ioc容器的创建初始化
    wac.refresh();
}

DispatcherServlet的onRefresh实际调用的initStrategies

protected void initStrategies(ApplicationContext context) {
    //逻辑都差不多,从context中获取,没有则创建一个默认的,这里不讨论各组件的创建过程
    initMultipartResolver(context);
    initLocaleResolver(context);
    initThemeResolver(context);
    initHandlerMappings(context);
    initHandlerAdapters(context);
    initHandlerExceptionResolvers(context);
    initRequestToViewNameTranslator(context);
    initViewResolvers(context);
    initFlashMapManager(context);
}

处理请求

DispatcherServlet在web.xml中一般配置了拦截所有请求,会走doGet或doPost,最终调用FrameworkServlet的processRequest.

protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    long startTime = System.currentTimeMillis();
    Throwable failureCause = null;
    //从ThreadLocal中获取LocaleContext
    LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
    //创建一个新的LocaleContext
    LocaleContext localeContext = buildLocaleContext(request);
    //从ThreadLocal中获取RequestAttributes
    RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
    //创建一个新的ServletRequestAttributes
    ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
    //从ServletRequest中获取WebAsyncManager,如果为null,则创建一个并且设置进ServletRequest
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    //注册RequestBindingInterceptor
    //在异步调用之前,在ThreadLocal中设置LocaleContext和RequestAttributes
    //在异步调用之后,调用ThreadLoca.remove()
    asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());
    //将之前创建的LocaleContext和RequestAttributes设置到ThreadLocal中
    initContextHolders(request, localeContext, requestAttributes);
    try {
        //执行DispatcherServlet的doService
        doService(request, response);
    }
    catch (ServletException | IOException ex) {
        ...
    }
    finally {
        //重置 LocaleContext和requestAttributes,解除关联
        resetContextHolders(request, previousLocaleContext, previousAttributes);
        if (requestAttributes != null) {
            requestAttributes.requestCompleted();
        }
        logResult(request, response, failureCause, asyncManager);
        //发布ServletRequestHandledEvent事件
        publishRequestHandledEvent(request, response, startTime, failureCause);
    }
}

DispatcherServlet.doService()主要是设置一些request属性,并调用doDispatch()方法进行请求分发处理

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpServletRequest processedRequest = request;
    HandlerExecutionChain mappedHandler = null;
    boolean multipartRequestParsed = false;
    //从ServletRequest中获取WebAsyncManager,如果为null,则创建一个并且设置进ServletRequest
    WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
    try {
        ModelAndView mv = null;
        Exception dispatchException = null;
        try {
            //检查是否有Multipart(文件上传),如果有则将请求包转换为MultipartHttpServletRequest请求
            processedRequest = checkMultipart(request);
            multipartRequestParsed = (processedRequest != request);
            //迭代所有HandlerMapping,找到HandlerMapping并与HandlerInterceptor封装成HandlerExecutionChain
            //有一个返回HandlerExecutionChain就结束查找,否则直到返回null
            mappedHandler = getHandler(processedRequest);
            if (mappedHandler == null) {
                noHandlerFound(processedRequest, response);
                return;
            }
            //迭代所有HandlerAdapter,通过HandlerMapping找到HandlerAdapter
            //主要调用HandlerAdpater.supports(HandlerMapping)
            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 (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) {
                    return;
                }
            }
            //执行所有拦截器的preHandle方法,interceptorIndex(拦截器数组的下标)递增记录执行到哪个拦截器的下标
            //如果有任意一个返回false,则调用执行过(interceptorIndex递减)的拦截器的afterCompletion方法,并且直接返回
            if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                return;
            }
            //执行HandlerAdapter处理请求,并且返回一个ModelAndView
            mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
            //判断当前请求是否开启了异步请求,如果开启,则直接返回,之后调用finally里的方法
            //故不执行接下来的拦截器的postHandle和afterCompletion方法
            if (asyncManager.isConcurrentHandlingStarted()) {
                return;
            }
            //没有视图名称则配置一个默认的
            applyDefaultViewName(processedRequest, mv);
            //执行所有拦截器的postHandle,因为到这一步说明所有拦截器的返回的true
            mappedHandler.applyPostHandle(processedRequest, response, mv);
        }
        catch (Exception ex) {
            ...
        }
        //调用DispatcherServlet的processDispatchResult
        processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
    }
    catch (Exception ex) {
        //出任何异常,都回执行拦截器的afterCompletion方法
        triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
    }
    finally {
        if (asyncManager.isConcurrentHandlingStarted()) {
            if (mappedHandler != null) {
                //迭代执行所有AsyncHandlerInterceptor的afterConcurrentHandlingStarted方法
                mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
            }
        }
        else {
            if (multipartRequestParsed) {
                cleanupMultipart(processedRequest);
            }
        }
    }
}
private void processDispatchResult(HttpServletRequest request, HttpServletResponse response,
        @Nullable HandlerExecutionChain mappedHandler, @Nullable ModelAndView mv,
        @Nullable Exception exception) throws Exception {
    boolean errorView = false;
    if (exception != null) {
        if (exception instanceof ModelAndViewDefiningException) {
            logger.debug("ModelAndViewDefiningException encountered", exception);
            mv = ((ModelAndViewDefiningException) exception).getModelAndView();
        } else {
            //如果异常不是ModelAndViewDefiningException类型,则用异常解析器解析获取ModelAndView
            Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
            mv = processHandlerException(request, response, handler, exception);
            errorView = (mv != null);
        }
    }
    if (mv != null && !mv.wasCleared()) {
        //视图渲染
        render(mv, request, response);
        if (errorView) {
            WebUtils.clearErrorRequestAttributes(request);
        }
    } else {
        if (logger.isTraceEnabled()) {
            logger.trace("No view rendering, null ModelAndView returned.");
        }
    }
    //判断当前请求是否开启了异步请求,如果是则直接返回,不执行下面的逻辑
    if (WebAsyncUtils.getAsyncManager(request).isConcurrentHandlingStarted()) {
        return;
    }
    //执行所有拦截器的afterCompletion方法
    if (mappedHandler != null) {
        mappedHandler.triggerAfterCompletion(request, response, null);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,525评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,203评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,862评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,728评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,743评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,590评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,330评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,244评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,693评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,885评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,001评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,723评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,343评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,919评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,042评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,191评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,955评论 2 355

推荐阅读更多精彩内容