Tomcat和Servlet和Spring

無聊在家看源碼,雖然沒看懂多少,但是還是想紀錄一下,埋下一顆種子。

有時候,一些問題,我總是想要追根尋底,一直搞的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的那條堆棧的函數??吹胶芏?code>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上下文,最后才是核心控制器的東西。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,967評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,273評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事?!?“怎么了?”我有些...
    開封第一講書人閱讀 175,870評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,742評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,527評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,010評論 1 322
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,108評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,250評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,769評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,656評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,853評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,371評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,103評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,472評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,717評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,487評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,815評論 2 372

推薦閱讀更多精彩內容

  • 從三月份找實習到現在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發崗...
    時芥藍閱讀 42,314評論 11 349
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,710評論 18 399
  • 0 系列目錄# WEB請求處理 WEB請求處理一:瀏覽器請求發起處理 WEB請求處理二:Nginx請求反向代理 本...
    七寸知架構閱讀 14,006評論 22 190
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,889評論 6 342
  • 本教程簡述如何用CSS3實現旋轉的球體 效果如下圖所示,球體沿著中間的軸旋轉: 要理解的知識點 1 三維空間的透視...
    小碼哥教育520it閱讀 7,821評論 1 4