struts2源碼的解讀

學習開源框架最好的方法,莫過於仔細閱讀源代碼,這樣既可以體會大牛們巧妙的設計,還可以看看大牛們的寫代碼的風格。對比中找缺陷,它就像一面鏡子,會讓我看到很多自己的缺點,受益頗多。

以下是自己學習的一些資料,有些事自己網上看的,有的是自己從代碼中發現的,學習,如果有不對的地方,希望高手指出,小弟在此謝過

 

1 struts2的源碼簡介

Struts2是Struts社區和WebWork社區的共同成果,我們甚至可以說,Struts2是WebWork的升級版,他採用的正是WebWork的核心,特別要指出的是構建在WebWork基礎之上的Struts2是一個運行穩定、性能優異、設計成熟的WEB框架。

    分析struts2源碼,因爲Struts2與WebWork的關係如此密不可分,所以下載並認真研究xwork的源碼是很有必要的。現在http://struts.apache.org/download.cgi#struts234

Struts2的源代碼中包含有xwrok的源碼具體包如下圖(本人儘量把最新的struts)

 

其中struts2的核心代碼的源文件如下圖所以

 

 

Struts2中主要的包和類的介紹

Struts2框架的正常運行,除了佔核心地位的xwork的支持以外,Struts2本身也提供了許多類,這些類被分門別類組織到不同的包中。從源代碼中發現,基本上每一個Struts2類都訪問了WebWork提供的功能,從而也可以看出Struts2與WebWork千絲萬縷的聯繫。但無論如何,Struts2的核心功能比如將請求委託給哪個Action處理都是由xwork完成的,Struts2只是在WebWork的基礎上做了適當的簡化、加強和封裝,並少量保留Struts1.x中的習慣。

包名

說明

org.apache.struts2. components

該包封裝視圖組件,Struts2在視圖組件上有了很大加強,不僅增加了組件的屬性個數,更新增了幾個非常有用的組件,如updownselect、doubleselect、datetimepicker、token、tree等。另外,Struts2可視化視圖組件開始支持主題(theme),缺省情況下,使用自帶的缺省主題,如果要自定義頁面效果,需要將組件的theme屬性設置爲simple。

org.apache.struts2. config

該包定義與配置相關的接口和類。實際上,工程中的xml和properties文件的讀取和解析都是由WebWork完成的,Struts只做了少量的工作。

org.apache.struts2.dispatcher

Struts2的核心包,最重要的類都放在該包中。

org.apache.struts2.impl

該包只定義了3個類,他們是StrutsActionProxy、StrutsActionProxyFactory、StrutsObjectFactory,這三個類都是對xwork的擴展。

org.apache.struts2.interceptor

定義內置的截攔器。

org.apache.struts2.util

實用包。

org.apache.struts2.validators

只定義了一個類:DWRValidator

org.apache.struts2.views

提供freemarker、jsp、velocity等不同類型的頁面呈現。

 

Struts2中一些重要的類說明

類名

說明

org.apache.struts2.dispatcher. Dispatcher

該類有兩個作用:初始化、調用指定的Action的execute()方法。

org.apache.struts2.dispatcher. FilterDispatcher

這是一個過濾器。文檔中已明確說明,如果沒有經驗,配置時請將url-pattern的值設成/*。該類有四個作用:執行Action、清理ActionContext,避免內存泄漏、處理靜態內容(Serving static content)、爲請求啓動xwork’s的截攔器鏈。

com.opensymphony.xwork2. ActionProxy

Action的代理接口。

com.opensymphony.xwork2. ctionProxyFactory

生產ActionProxy的工廠。

com.opensymphony.xwork2.ActionInvocation

負責調用Action和截攔器。

com.opensymphony.xwork2.config.providers. XmlConfigurationProvider

負責Struts2的配置文件的解析。

 

 

 

2 Struts2架構

Struts2的工作流程圖如下,此圖來自於struts2的官方文檔

         從圖中可以看出,一個請求在struts2框架中分爲以下幾個步驟:

1)  客戶端初始化一個指向servlet容器的請求;

2)  這個請求經過一系列的過濾器(Filter)這些過濾器中有一個叫做ActionContextCleanUp的可選擇過濾器,這個過濾器對於struts2和其他框架的集成很有幫助,例如SiteMEsh Plugin等;

3)  接着FilterDispatcher被調用,FilterDispatcher詢問ActionMapper來決定這個請求是否需要調用某個Action

4)  如果ActionMapper決定需要調用某個ActionFilterDispatcher把請求的處理交過ActionProxy

5)  ActionProxy通過Configuration Manager詢問框架配置文件,找到對應的Action類;

6)  ActionProxy創建一個ActionInvocation實例

7)  ActionInvocation實例使用命名模式來調用在Action過程前後,涉及到相關的攔截器(intercepter)的調用;

8)  一旦Action執行完畢,ActionInvocation負責根據struts.xml中的配置找到對應的返回結果。返回結果通常是一個需求蓓表示的jsp或者FreeMarker的模板。在表示的過程中可以使用Struts2框架中繼承標籤,這個過程中涉及到ActionMapper

 

請求首先通過Filter chain,Filter主要包括ActionContextCleanUp,它主要清理當前線程的ActionContext和Dispatcher;FilterDispatcher主要通過AcionMapper來決定需要調用哪個Action。ActionMapper取得了ActionMapping後,在Dispatcher的serviceAction方法裏創建ActionProxy,ActionProxy創建ActionInvocation,然後ActionInvocation調用Interceptors,執行Action本身,創建Result並返回,當然,如果要在返回之前做些什麼,可以實現PreResultListener。

3 Struts2源代碼解讀

         struts1.x不同,struts2的啓動是通過FilterDispatcher過濾器實現的。下面是該過濾器在web.xml中的配置

<filter>

       <filter-name>struts</filter-name>

    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>

    </filter>

    <filter-mapping>

       <filter-name>struts</filter-name>

       <url-pattern>/*</url-pattern>

    </filter-mapping>

 

建議在對struts2不熟悉的情況下,最好將url-pattern配置爲/*,這樣該過濾器將攔截所有的請求。實際FilterDispatcher類除了實現Filter接口之外,還實現了StrutsStatics接口,繼承代碼如下: publicclass FilterDispatcher implements StrutsStatics, Filter {}

StrutsStatics並沒有定義業務方法,只是定義了若干個常量。Struts2對常用的接口進行了重新封裝,比如HttpServletRequest、HttpServletResponse、HttpServletContext等。

 

    容器啓動後,FilterDispatcher被實例化,調用init(FilterConfig filterConfig)方法。該方法創建Dispatcher實例,並將FilterDispatcherde配置的初始化參數傳到對象中,並負責Action的執行。

publicvoid init(FilterConfig filterConfig) throws ServletException {

        try {

            this.filterConfig = filterConfig;

 

            initLogging();

 

            dispatcher = createDispatcher(filterConfig);

            dispatcher.init();

            dispatcher.getContainer().inject(this);

 

            staticResourceLoader.setHostConfig(new FilterHostConfig(filterConfig));

        } finally {

            ActionContext.setContext(null);

        }

}

其中dispatcher.init();方法完成了對struts2的基本配置文件的讀取,源碼如下

dispatcher.init();

    publicvoid init() {

 

    if (configurationManager == null) {

        configurationManager = createConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);

    }

 

        try {

            init_DefaultProperties(); // [1]完成讀取org/apache/struts2/default.properties的配置信息,如果項目中需要覆蓋,可以在classpath裏的struts.properties裏覆寫

            init_TraditionalXmlConfigurations(); // [2]此方法是對struts-default.xmlstruts2.xml文件的加載,介於此文件比較重要,所以在下面列舉了本函數的源代碼

            init_LegacyStrutsProperties(); // [3]

            init_CustomConfigurationProviders(); // [5]

            init_FilterInitParameters() ; // [6]

            init_AliasStandardObjects() ; // [7]

 

            Container container = init_PreloadConfiguration();

            container.inject(this);

            init_CheckConfigurationReloading(container);

            init_CheckWebLogicWorkaround(container);

 

            if (!dispatcherListeners.isEmpty()) {

                for (DispatcherListener l : dispatcherListeners) {

                    l.dispatcherInitialized(this);

                }

            }

        } catch (Exception ex) {

            if (LOG.isErrorEnabled())

                LOG.error("Dispatcher initialization failed", ex);

            thrownew StrutsException(ex);

        }

    }

//讀取Struts2的struts-default.xml和struts.xml

privatevoid init_TraditionalXmlConfigurations() {

//首先讀取web.xml中的config初始值

//如果沒有配置就使用默認”struts-default.xml,struts-plugin.xml

// struts.xml”文件,這也是爲什麼默認的配置文件必須取名爲這三個文件

//如果不想使用默認的名稱,直接在web.xml中配置config初始值即可。

        String configPaths = initParams.get("config");

        if (configPaths == null) {

            configPaths = DEFAULT_CONFIGURATION_PATHS;

        }

        String[] files = configPaths.split("\\s*[,]\\s*");

//一次解析配置文件,xwork.xml單獨解析

        for (String file : files) {

            if (file.endsWith(".xml")) {

                if ("xwork.xml".equals(file)) {

configurationManager.addConfigurationProvider(createXmlConfigurationProvider(file, false));

                } else {

                    configurationManager.addConfigurationProvider(createStrutsXmlConfigurationProvider(file, false, servletContext));

                }

            } else {

                thrownew IllegalArgumentException("Invalid configuration file name");

            }

        }

}

在上面的configurationManager.addConfigurationProvider(createStrutsXmlConfigurationProvider(file, false, servletContext));執行會創建一個下面的類對象。

publicclass StrutsXmlConfigurationProvider extends XmlConfigurationProvider {}

此類繼承XmlConfigurationProvider,而XmlConfigurationProvider又實現了接口ConfigurationProvider 接口。XmlConfigurationProvider負責配置文件的讀取和解析,addAction()負責加載Struts2配置文件中的action. addAction()方法負責讀取<action>標籤,並將數據保存在ActionConfig中;addResultTypes()方法負責將<result-type>標籤轉化爲ResultTypeConfig對象;loadInterceptors()方法負責將<interceptor>標籤轉化爲InterceptorConfi對象;loadInterceptorStack()方法負責將<interceptor-ref>標籤轉化爲InterceptorStackConfig對象;loadInterceptorStacks()方法負責將<interceptor-stack>標籤轉化成InterceptorStackConfig對象。而上面的方法最終會被addPackage()方法調用,將所讀取到的數據彙集到PackageConfig對象中

 

當用戶想struts2發送請求時,FilterDispatcher的doFilter()方法自動調用,這個方法非常關鍵。首先,struts2對請求對象進行了重新包裝,此次包裝根據請求內容的類型不容,返回不同的對象,如果爲multipart/form-data類型,則返回StrutsPartRequestWrapper類型的對象,該對象服務於文件上傳,否則返回StrutsRequestWrapper類型的對象,前者是後者的子類。代碼如下:

publicvoid doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

 

        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse response = (HttpServletResponse) res;

        ServletContext servletContext = getServletContext();

 

        String timerKey = "FilterDispatcher_doFilter: ";

        try {

 

            // FIXME: this should be refactored better to not duplicate work with the action invocation

            ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();

            ActionContext ctx = new ActionContext(stack.getContext());

            ActionContext.setContext(ctx);

 

            UtilTimerStack.push(timerKey);

            request = prepareDispatcherAndWrapRequest(request, response);//重新包裝request

            ActionMapping mapping;

            try {

                mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());//獲取Action的值,一個url對應一個action,如果此actionnull則認爲無action請求,在後面有判斷

            } catch (Exception ex) {

                log.error("error getting ActionMapping", ex);

                dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);

                return;

            }

 

            if (mapping == null) {

                // there is no action in this request, should we look for a static resource?

                String resourcePath = RequestUtils.getServletPath(request);

 

                if ("".equals(resourcePath) && null != request.getPathInfo()) {

                    resourcePath = request.getPathInfo();

                }

//如果請求資源以/struts開頭,則當做靜態資源處理

                if (staticResourceLoader.canHandle(resourcePath)) {

                    staticResourceLoader.findStaticResource(resourcePath, request, response);

                } else {

                    // this is a normal request, let it pass through

                    chain.doFilter(request, response);

                }

                // The framework did its job here

                return;

            }

//如果請求資源是action,則調用serviceAction方法

            dispatcher.serviceAction(request, response, servletContext, mapping);

 

        } finally {

            dispatcher.cleanUpRequest(request);

            try {

                ActionContextCleanUp.cleanUp(req);

            } finally {

                UtilTimerStack.pop(timerKey);

            }

            devModeOverride.remove();

        }

    }

Dispatcher類最重要的一個方法是publicvoid serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,ActionMapping mapping) throws ServletException{}此方法

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章