Tomcat和Servlet和Spring

無聊在家看源碼,雖然沒看懂多少亡嫌,但是還是想紀(jì)錄一下嚎于,埋下一顆種子掘而。

有時(shí)候,一些問題于购,我總是想要追根尋底袍睡,一直搞的Web開發(fā),但是卻每次只能在Controller層去編寫代碼肋僧,調(diào)試代碼斑胜,感覺心里總有些(其實(shí)是很)不爽,所以擅自超出自己的能力范圍嫌吠,去看了看TomcatServletSpring的源碼止潘,果然如我所料,的確是非常難居兆,所以覆山,只能記下一些關(guān)鍵點(diǎn),為以后留下點(diǎn)東西泥栖。

看了好久簇宽,直到最后,才發(fā)現(xiàn)這個(gè)關(guān)鍵點(diǎn)吧享,如下圖所示魏割。

Paste_Image.png

發(fā)現(xiàn)沒有,這里是三個(gè)包之間的交互點(diǎn)钢颂,從這三條堆棧的運(yùn)行來看钞它,就可以看到這三個(gè)關(guān)鍵點(diǎn)之間是如何交互的。

那么一個(gè)一個(gè)函數(shù)來看殊鞭。

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

這個(gè)就是Tomcat的那條堆棧的函數(shù)遭垛。看到很多blog都很空泛的說操灿,Web容器會(huì)加載web.xml的內(nèi)容锯仪,然后加載里面定義的Servlet,之后會(huì)調(diào)用init()的內(nèi)容,但是都沒有代碼級別的示例趾盐,這讓我著實(shí)心癢庶喜。所以想盡辦法來窺的一絲一毫。

這里函數(shù)里面其實(shí)已經(jīng)加載好了Servlet,如果在Idea里面把鼠標(biāo)移動(dòng)到Servlet上面可以看到類型就是我在web.xml里面配置的DispatherServlet的實(shí)例救鲤。

關(guān)鍵代碼就是Servlet.init(this.facade)久窟。也就是這里Tomcat調(diào)用Servletinit()函數(shù)。這邊也應(yīng)該要注意到的是參數(shù)this.facade本缠,沒錯(cuò),這個(gè)就是Servlet接口中的init(ServletConfig config)config參數(shù)斥扛,里面最重要的就是給了Servlet一個(gè)ServletContext的引用,這樣每個(gè)Servlet就可以訪問到唯一的一個(gè)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賦值行為队他。之后又接著調(diào)用了沒有參數(shù)的init()函數(shù)。之后就是Spring的有個(gè)HttpServletBean的類進(jìn)行了init()函數(shù)的實(shí)現(xiàn)峻村。具體源代碼如下。

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

}

從這個(gè)函數(shù)開始就沒有Tomcat的什么事情了锡凝,就開始進(jìn)入到Spring的管理中來了粘昨。

好的,下面雖然看的不是很懂了窜锯,但是能走幾步就走幾步张肾。

按照調(diào)用棧的過程,可以看到之后是FrameworkServletinitServletBean的調(diào)用锚扎。這回先上代碼吞瞪。

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容器,好驾孔,在進(jìn)入這個(gè)初始的代碼看看芍秆,又做了一些什么事情呢。

protected WebApplicationContext initWebApplicationContext() {
    //先嘗試從ServletContext中獲得全局的Spring容器
    //全局的Spring容器是通過監(jiān)聽器獲得的翠勉,但是我這里沒有配置
    //所以返回的是個(gè)null妖啥,rootContext=null
    WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
    WebApplicationContext wac = null;
    //分為兩種情況,一種是Bean容器已存在(什么情況下會(huì)這樣呢?)
    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);
                }
                //最后調(diào)用這個(gè)配置和刷新Bean容器
                //如果是下面一個(gè)創(chuàng)建的分支的話对碌,最后也是會(huì)執(zhí)行這個(gè)函數(shù)的
                this.configureAndRefreshWebApplicationContext(attrName);
            }
        }
    }
    //如果沒有初始化荆虱,第一次進(jìn)來的時(shí)候一定是沒有初始化的
    //找一下?怎么找?
    if(wac == null) {
        wac = this.findWebApplicationContext();
    }
    //找不到就造一個(gè),實(shí)例化一個(gè)
    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這里朽们。有個(gè)關(guān)鍵一個(gè)是把從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());
        //將從監(jiān)聽器獲得的Spring容器作為父容器
        wac.setParent(parent);
        wac.setConfigLocation(this.getContextConfigLocation());
        //調(diào)用這個(gè)配置和刷新Web應(yīng)用上下文的函數(shù)  
        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之類的設(shè)置進(jìn)入Web應(yīng)用上下菜枷,下面是refresh()
    wac.refresh();
}

再進(jìn)入到refresh()函數(shù)中,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;
        }

    }
}

中間跳過無數(shù)看不懂的東西,好像是一些事件傳遞歹袁,監(jiān)聽坷衍,委托之類的,最后終于調(diào)用了DispatherServletonRefresh函數(shù)和initStrategies函數(shù)条舔。但是其實(shí)在DispatherServletTomcat初始化的時(shí)候會(huì)先調(diào)用DiapatherServlet的靜態(tài)區(qū)塊枫耳,之后才是無參構(gòu)造函數(shù)。

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

再補(bǔ)上我這個(gè)Debug項(xiàng)目的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的環(huán)境是Tomcat8.0Spring4.0.6版本迁杨,不同的版本之間應(yīng)該會(huì)有一些出入钻心,所以紀(jì)錄一下版本,想要調(diào)試的源代碼版本是Github上面的AllDemodemo_producer612dd1316d4d762c166901698ba1818f1b18bfca版本铅协。

還得補(bǔ)一張完整堆棧圖捷沸。


Paste_Image.png

看了那么多,小結(jié)一下狐史,DispatcherServlet繼承了FrameWorkServlet痒给,這個(gè)類里面其實(shí)幫助初始化了Web上下文,最后才是核心控制器的東西骏全。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末苍柏,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子姜贡,更是在濱河造成了極大的恐慌试吁,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件楼咳,死亡現(xiàn)場離奇詭異熄捍,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)爬橡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進(jìn)店門治唤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人糙申,你說我怎么就攤上這事宾添。” “怎么了柜裸?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵缕陕,是天一觀的道長。 經(jīng)常有香客問我疙挺,道長扛邑,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任铐然,我火速辦了婚禮蔬崩,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘搀暑。我一直安慰自己沥阳,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布自点。 她就那樣靜靜地躺著桐罕,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上功炮,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天溅潜,我揣著相機(jī)與錄音,去河邊找鬼薪伏。 笑死滚澜,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的嫁怀。 我是一名探鬼主播博秫,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼眶掌!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起巴碗,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤朴爬,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后橡淆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體召噩,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年逸爵,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了具滴。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,488評論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡师倔,死狀恐怖构韵,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情趋艘,我是刑警寧澤疲恢,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站瓷胧,受9級特大地震影響显拳,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜搓萧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一杂数、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧瘸洛,春花似錦揍移、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春喧锦,著一層夾襖步出監(jiān)牢的瞬間读规,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工燃少, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留束亏,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓阵具,卻偏偏與公主長得像碍遍,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子阳液,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 從三月份找實(shí)習(xí)到現(xiàn)在怕敬,面了一些公司,掛了不少帘皿,但最終還是拿到小米东跪、百度、阿里鹰溜、京東虽填、新浪、CVTE曹动、樂視家的研發(fā)崗...
    時(shí)芥藍(lán)閱讀 42,274評論 11 349
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法斋日,類相關(guān)的語法,內(nèi)部類的語法墓陈,繼承相關(guān)的語法恶守,異常的語法,線程的語...
    子非魚_t_閱讀 31,661評論 18 399
  • 0 系列目錄# WEB請求處理 WEB請求處理一:瀏覽器請求發(fā)起處理 WEB請求處理二:Nginx請求反向代理 本...
    七寸知架構(gòu)閱讀 13,970評論 22 190
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,847評論 6 342
  • 本教程簡述如何用CSS3實(shí)現(xiàn)旋轉(zhuǎn)的球體 效果如下圖所示跛蛋,球體沿著中間的軸旋轉(zhuǎn): 要理解的知識點(diǎn) 1 三維空間的透視...
    小碼哥教育520it閱讀 7,794評論 1 4