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

你可能感兴趣的:(DispatcherServlet源码笔记)