美文网首页
Tomcat和Servlet和Spring

Tomcat和Servlet和Spring

作者: yang2yang | 来源:发表于2016-11-27 23:17 被阅读2682次

无聊在家看源码,虽然没看懂多少,但是还是想纪录一下,埋下一颗种子。

有时候,一些问题,我总是想要追根寻底,一直搞的Web开发,但是却每次只能在Controller层去编写代码,调试代码,感觉心里总有些(其实是很)不爽,所以擅自超出自己的能力范围,去看了看TomcatServletSpring的源码,果然如我所料,的确是非常难,所以,只能记下一些关键点,为以后留下点东西。

看了好久,直到最后,才发现这个关键点,如下图所示。

Paste_Image.png

发现没有,这里是三个包之间的交互点,从这三条堆栈的运行来看,就可以看到这三个关键点之间是如何交互的。

那么一个一个函数来看。

    private synchronized void initServlet(Servlet servlet) throws ServletException {
        if(!this.instanceInitialized || this.singleThreadModel) {
            try {
                this.instanceSupport.fireInstanceEvent("beforeInit", servlet);
                if(Globals.IS_SECURITY_ENABLED) {
                    boolean f = false;

                    try {
                        Object[] args = new Object[]{this.facade};
                        SecurityUtil.doAsPrivilege("init", servlet, classType, args);
                        f = true;
                    } finally {
                        if(!f) {
                            SecurityUtil.remove(servlet);
                        }

                    }
                } else {
                    servlet.init(this.facade);
                }

                this.instanceInitialized = true;
                this.instanceSupport.fireInstanceEvent("afterInit", servlet);
            } catch (UnavailableException var10) {
                this.instanceSupport.fireInstanceEvent("afterInit", servlet, var10);
                this.unavailable(var10);
                throw var10;
            } catch (ServletException var11) {
                this.instanceSupport.fireInstanceEvent("afterInit", servlet, var11);
                throw var11;
            } catch (Throwable var12) {
                ExceptionUtils.handleThrowable(var12);
                this.getServletContext().log("StandardWrapper.Throwable", var12);
                this.instanceSupport.fireInstanceEvent("afterInit", servlet, var12);
                throw new ServletException(sm.getString("standardWrapper.initException", new Object[]{this.getName()}), var12);
            }
        }
    }

这个就是Tomcat的那条堆栈的函数。看到很多blog都很空泛的说,Web容器会加载web.xml的内容,然后加载里面定义的Servlet,之后会调用init()的内容,但是都没有代码级别的示例,这让我着实心痒。所以想尽办法来窥的一丝一毫。

这里函数里面其实已经加载好了Servlet,如果在Idea里面把鼠标移动到Servlet上面可以看到类型就是我在web.xml里面配置的DispatherServlet的实例。

关键代码就是Servlet.init(this.facade)。也就是这里Tomcat调用Servletinit()函数。这边也应该要注意到的是参数this.facade,没错,这个就是Servlet接口中的init(ServletConfig config)config参数,里面最重要的就是给了Servlet一个ServletContext的引用,这样每个Servlet就可以访问到唯一的一个ServletContext

下面的是Servlet的接口源代码。

package javax.servlet;

import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
    private static final long serialVersionUID = 1L;
    private transient ServletConfig config;

    public GenericServlet() {
    }

    public void destroy() {
    }

    public ServletConfig getServletConfig() {
        return this.config;
    }

    public ServletContext getServletContext() {
        return this.getServletConfig().getServletContext();
    }

    public String getServletInfo() {
        return "";
    }

    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }

    public void init() throws ServletException {
    }
    
    public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

}

从接口中可以更加明显的看到config赋值行为。之后又接着调用了没有参数的init()函数。之后就是Spring的有个HttpServletBean的类进行了init()函数的实现。具体源代码如下。

public final void init() throws ServletException {
    if(this.logger.isDebugEnabled()) {
        this.logger.debug("Initializing servlet \'" + this.getServletName() + "\'");
    }

    try {
        HttpServletBean.ServletConfigPropertyValues ex = new HttpServletBean.ServletConfigPropertyValues(this.getServletConfig(), this.requiredProperties);
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
        ServletContextResourceLoader resourceLoader = new ServletContextResourceLoader(this.getServletContext());
        bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.getEnvironment()));
        this.initBeanWrapper(bw);
        bw.setPropertyValues(ex, true);
    } catch (BeansException var4) {
        this.logger.error("Failed to set bean properties on servlet \'" + this.getServletName() + "\'", var4);
        throw var4;
    }

    this.initServletBean();
    if(this.logger.isDebugEnabled()) {
        this.logger.debug("Servlet \'" + this.getServletName() + "\' configured successfully");
    }

}

从这个函数开始就没有Tomcat的什么事情了,就开始进入到Spring的管理中来了。

好的,下面虽然看的不是很懂了,但是能走几步就走几步。

按照调用栈的过程,可以看到之后是FrameworkServletinitServletBean的调用。这回先上代码。

protected final void initServletBean() throws ServletException {
    this.getServletContext().log("Initializing Spring FrameworkServlet \'" + this.getServletName() + "\'");
    if(this.logger.isInfoEnabled()) {
        this.logger.info("FrameworkServlet \'" + this.getServletName() + "\': initialization started");
    }

    long startTime = System.currentTimeMillis();

    try {
        //开始初始化前端控制器自己的Bean容器
        this.webApplicationContext = this.initWebApplicationContext();
        this.initFrameworkServlet();
    } catch (ServletException var5) {
        this.logger.error("Context initialization failed", var5);
        throw var5;
    } catch (RuntimeException var6) {
        this.logger.error("Context initialization failed", var6);
        throw var6;
    }

    if(this.logger.isInfoEnabled()) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        this.logger.info("FrameworkServlet \'" + this.getServletName() + "\': initialization completed in " + elapsedTime + " ms");
    }

}

从代码中可以看到最先做的事情是初始化了DispatherServlet自己的Bean容器,好,在进入这个初始的代码看看,又做了一些什么事情呢。

protected WebApplicationContext initWebApplicationContext() {
    //先尝试从ServletContext中获得全局的Spring容器
    //全局的Spring容器是通过监听器获得的,但是我这里没有配置
    //所以返回的是个null,rootContext=null
    WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    WebApplicationContext wac = null;
    //分为两种情况,一种是Bean容器已存在(什么情况下会这样呢?)
    if(this.webApplicationContext != null) {
        wac = this.webApplicationContext;
        if(wac instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext attrName = (ConfigurableWebApplicationContext)wac;
            if(!attrName.isActive()) {
                if(attrName.getParent() == null) {
                    attrName.setParent(rootContext);
                }
                //最后调用这个配置和刷新Bean容器
                //如果是下面一个创建的分支的话,最后也是会执行这个函数的
                this.configureAndRefreshWebApplicationContext(attrName);
            }
        }
    }
    //如果没有初始化,第一次进来的时候一定是没有初始化的
    //找一下?怎么找?
    if(wac == null) {
        wac = this.findWebApplicationContext();
    }
    //找不到就造一个,实例化一个
    if(wac == null) {
        wac = this.createWebApplicationContext(rootContext);
    }

    if(!this.refreshEventReceived) {
        this.onRefresh(wac);
    }

    if(this.publishContext) {
        String attrName1 = this.getServletContextAttributeName();
        this.getServletContext().setAttribute(attrName1, wac);
        if(this.logger.isDebugEnabled()) {
            this.logger.debug("Published WebApplicationContext of servlet \'" + this.getServletName() + "\' as ServletContext attribute with name [" + attrName1 + "]");
        }
    }

    return wac;
}

在走两步到FrameServletcreateWebApplicationContext这里。有个关键一个是把从ServletContext中获得原始的Bean容器作为了DispatherServlet自己的父容器了。

protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
    Class contextClass = this.getContextClass();
    if(this.logger.isDebugEnabled()) {
        this.logger.debug("Servlet with name \'" + this.getServletName() + "\' will try to create custom WebApplicationContext context of class \'" + contextClass.getName() + "\'" + ", using parent context [" + parent + "]");
    }

    if(!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
        throw new ApplicationContextException("Fatal initialization error in servlet with name \'" + this.getServletName() + "\': custom WebApplicationContext class [" + contextClass.getName() + "] is not of type ConfigurableWebApplicationContext");
    } else {
        ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
        wac.setEnvironment(this.getEnvironment());
        //将从监听器获得的Spring容器作为父容器
        wac.setParent(parent);
        wac.setConfigLocation(this.getContextConfigLocation());
        //调用这个配置和刷新Web应用上下文的函数  
        this.configureAndRefreshWebApplicationContext(wac);
        return wac;
    }
}

好,接着看。

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
    if(ObjectUtils.identityToString(wac).equals(wac.getId())) {
        if(this.contextId != null) {
            wac.setId(this.contextId);
        } else {
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(this.getServletContext().getContextPath()) + "/" + this.getServletName());
        }
    }

    wac.setServletContext(this.getServletContext());
    wac.setServletConfig(this.getServletConfig());
    wac.setNamespace(this.getNamespace());
    wac.addApplicationListener(new SourceFilteringListener(wac, new FrameworkServlet.ContextRefreshListener(null)));
    ConfigurableEnvironment env = wac.getEnvironment();
    if(env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment)env).initPropertySources(this.getServletContext(), this.getServletConfig());
    }

    this.postProcessWebApplicationContext(wac);
    this.applyInitializers(wac);
    //上面都是把一些ServletContext和ServletConfig之类的设置进入Web应用上下,下面是refresh()
    wac.refresh();
}

再进入到refresh()函数中,md,完全没看懂,逃...

public void refresh() throws BeansException, IllegalStateException {
    Object var1 = this.startupShutdownMonitor;
    synchronized(this.startupShutdownMonitor) {
        this.prepareRefresh();
        ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
        this.prepareBeanFactory(beanFactory);

        try {
            this.postProcessBeanFactory(beanFactory);
            this.invokeBeanFactoryPostProcessors(beanFactory);
            this.registerBeanPostProcessors(beanFactory);
            this.initMessageSource();
            this.initApplicationEventMulticaster();
            this.onRefresh();
            this.registerListeners();
            this.finishBeanFactoryInitialization(beanFactory);
           //以上都不知道在干啥了 
           this.finishRefresh();
        } catch (BeansException var5) {
            this.destroyBeans();
            this.cancelRefresh(var5);
            throw var5;
        }

    }
}

中间跳过无数看不懂的东西,好像是一些事件传递,监听,委托之类的,最后终于调用了DispatherServletonRefresh函数和initStrategies函数。但是其实在DispatherServletTomcat初始化的时候会先调用DiapatherServlet的静态区块,之后才是无参构造函数。

protected void onRefresh(ApplicationContext context) {
    this.initStrategies(context);
}

protected void initStrategies(ApplicationContext context) {
    this.initMultipartResolver(context);
    this.initLocaleResolver(context);
    this.initThemeResolver(context);
    this.initHandlerMappings(context);
    this.initHandlerAdapters(context);
    this.initHandlerExceptionResolvers(context);
    this.initRequestToViewNameTranslator(context);
    this.initViewResolvers(context);
    this.initFlashMapManager(context);
}

再补上我这个Debug项目的web.xml文件。

<?xml version="1.0" encoding="UTF-8" ?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
        <servlet-name>spitter</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--<init-param>-->
            <!--<param-name>spring</param-name>-->
            <!--<param-value>classpath:/spring/demo_produce.xml</param-value>-->
        <!--</init-param>-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spitter</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>spitter</servlet-name>
        <url-pattern>*.service</url-pattern>
    </servlet-mapping>

</web-app>

以及本次的Debug的环境是Tomcat8.0Spring4.0.6版本,不同的版本之间应该会有一些出入,所以纪录一下版本,想要调试的源代码版本是Github上面的AllDemodemo_producer612dd1316d4d762c166901698ba1818f1b18bfca版本。

还得补一张完整堆栈图。


Paste_Image.png

看了那么多,小结一下,DispatcherServlet继承了FrameWorkServlet,这个类里面其实帮助初始化了Web上下文,最后才是核心控制器的东西。

相关文章

网友评论

      本文标题:Tomcat和Servlet和Spring

      本文链接:https://www.haomeiwen.com/subject/zzpnpttx.html