【SpringMvc执行流程】SpringMvc从Servlet到DispatcherServlet(一)

DispatcherServlet最主要的功能函数是onRefreshdoService

  • onRefresh

    @Override
    protected void onRefresh(ApplicationContext context) {
      initStrategies(context);
    }
  • doService

    @Override
    protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
      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());
      doDispatch(request, response);
    }

    下面讲述spring是如何调用这俩个函数的。

    Servlet

    从jsr规范中,可以看出

A servlet is managed through a well defined life cycle that defines how it is loaded
and instantiated, is initialized, handles requests from clients, and is taken out of
service. This life cycle is expressed in the API by the init, service, and destroy
methods of the javax.servlet.Servlet interface that all servlets must implement
directly or indirectly through the GenericServlet or HttpServlet abstract classes.

我们想要使用Servlet,就必须实现这个两个类,而spring也是如此

public abstract class HttpServletBean extends HttpServlet implements EnvironmentCapable {
}

HttpServlet中有个init方法,当一个请求来时,会触发servlet的生命周期并调用init方法进行初始化。而spring重写了init方法

public final void init() throws ServletException {


    /**
     * 把web.xml中的init-param中的key value拿到
     */
    PropertyValues pvs = new MyServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
    /**
     * 当<servlet>没有参数不走此if</servlet>
     */
    if (!pvs.isEmpty()) {
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
        ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
        bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
        initBeanWrapper(bw);
        bw.setPropertyValues(pvs, true);
    }

    initServletBean();
}
  • BeanWrapper是对contextConfigLocation进行处理。关键在initServletBean中。
    进入initServletBean中查看
    protected final void initServletBean() throws ServletException {
      //...
      this.webApplicationContext = initWebApplicationContext();
      //...
    }
    初始化bean的关键是初始化WebApplicationContext
    而WebApplicationContext又做了如下事情
    protected WebApplicationContext initWebApplicationContext() {
      WebApplicationContext rootContext =
           WebApplicationContextUtils.getWebApplicationContext(getServletContext()); //null
      WebApplicationContext wac = null;
    if (wac == null) {
    wac = createWebApplicationContext(rootContext);
    }
    }
    首次加载显然不可能有rootContext的,所以这里还要深入createWebApplicationContext中。
    protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
    return createWebApplicationContext((ApplicationContext) parent);
    }
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
/**
 * 获取加载方式,默认为{@link XmlWebApplicationContext}
 */
Class<?> contextClass = getContextClass();

ConfigurableWebApplicationContext wac =
        (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

/**
 * 获取环境 {@link StandardEnvironment}
 */
wac.setEnvironment(getEnvironment());  //StandardServletEnvironment
wac.setParent(parent);            //null
String configLocation = getContextConfigLocation();  //null
if (configLocation != null) {
    wac.setConfigLocation(configLocation);
}
configureAndRefreshWebApplicationContext(wac);

return wac;
}

可见这个WebApplicationContext默认使用的是XmlWebApplicationContext。使用此上下文进行web解析。

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));//添加一个事件监听器
    wac.refresh();
}

这里终于看到refresh()的影子,我们继续往下走,发现来到了AbstractApplicationContext中,一大堆代码springbean代码,无从下手。

@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        prepareRefresh();
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
        prepareBeanFactory(beanFactory);
        try {
            postProcessBeanFactory(beanFactory);
            invokeBeanFactoryPostProcessors(beanFactory);
            registerBeanPostProcessors(beanFactory);
            initMessageSource();
            initApplicationEventMulticaster();
            onRefresh();

            registerListeners();

            finishBeanFactoryInitialization(beanFactory);

            finishRefresh();
        }

这里利用断点的形式来逆向查看代码执行过程。发现在finishRefresh中执行了事件发布publishEvent(new ContextRefreshedEvent(this));而这个发布对象是我们在configureAndRefreshWebApplicationContext中添加的事件监听器。所以执行完后会回调ContextRefreshListener中的onApplicationEvent方法

private class ContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        FrameworkServlet.this.onApplicationEvent(event);
    }
}

onApplicationEvent中调用的则是我们朝思暮想的onRefresh函数。

public void onApplicationEvent(ContextRefreshedEvent event) {
    this.refreshEventReceived = true;
    onRefresh(event.getApplicationContext());
}

doService的来历

所有的请求tomcat会路有转发到Servlet的service方法。
spring则在FrameworkServlet中重写了service方法。

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
         processRequest(request, response);
}

对service请求近一步处理

protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        doService(request, response);
}        

doServiceDispatcherServlet重写。到这里doService就回被调用,进行对应的请求处理。


文章作者: Ciwei
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Ciwei !
 上一篇
【SpringMvc执行流程】SpringMvc初始化handlerMapping(二) 【SpringMvc执行流程】SpringMvc初始化handlerMapping(二)
前面我们分析了spring如何接入Servlet,执行onRefresh方法,而HandlerMapping的初始化就在OnRefresh中调用。 protected void onRefresh(ApplicationCont
2019-07-20
下一篇 
【SpringCloud学习】Zuul2.0实现微服务网关(Greenwich版) 【SpringCloud学习】Zuul2.0实现微服务网关(Greenwich版)
Zuul2.0实现微服务网关zuul简介路由是微服务架构不可或缺的一部分。例如,/可以映射到您的Web应用程序,/api/users映射到用户服务并/api/shop映射到商店服务。 Zuul是Netflix的基于JVM的路由器和服务器端负
2019-07-20
  目录