Struts 源碼學習之ActionServlet ( 一)

Struts 源碼最新版本爲 struts-1.3.8-src.zip  12-Mar-2007 00:06 java

學習筆記使用struts-1.3.5-src.zip 的源碼,web

下載地址:http://archive.apache.org/dist/struts/source/apache

1.  web.xml中經過下面定義把全部的*.do交給ActionServlet處理緩存

 

<!-- Standard Action Servlet Configuration (with debugging) -->tomcat

<servlet>app

    <servlet-name>action</servlet-name>學習

    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>this

    <init-param>url

      <param-name>config</param-name>spa

      <param-value>

          /WEB-INF/struts-config.xml,

          /WEB-INF/struts-config-Wildcard.xml

       </param-value>

    </init-param>

    <load-on-startup>2</load-on-startup>

  </servlet>

 

  <!-- Standard Action Servlet Mapping -->

  <servlet-mapping>

    <servlet-name>action</servlet-name>

    <url-pattern>*.do</url-pattern>

  </servlet-mapping>

 

2.  下面研究一下struts的源碼,因爲servlet設置了load-on-startup,因此tomcat啓動時會加載ActionServlet,也就是會執行ActionServlet中的init()方法,Struts 的初始化實現就是在這裏實現的

 

注: 因爲servlet的生命週期爲 web容器加載和實例化類/init()初始化/service()請求處理/destroy()四個階段,而init()方法在tomcat啓動後只執行一次,因此若是想在tomcat啓動後用debug模式查看ActionServletinit()方法的執行,能夠把上面的<load-on-startup>2</load-on-startup>註釋掉就能夠了(不過真正開發時仍是須要的)。

 

3.  ActionServlet中定義了一些常量,以下:

    // 默認的struts配置文件爲/WEB-INF/struts-config.xml

    protected String config = "/WEB-INF/struts-config.xml"; //  initOther();  initModuleConfig ();

 

    // 默認的鏈(定義了一個按順序執行的處理流程)配置文件

protected String chainConfig = "org/apache/struts/chain/chain-config.xml";

//  initChain();

 

protected Digester configDigester = null; //  initModuleConfig ();

// convertNull trueJava包裝類(如java.lang.Integer)的初始值爲null

protected boolean convertNull = false; //  initOther();

 

protected MessageResources internal = null; //  initInternal();

// 默認的 struts-core-1.3.5.jar  中資源文件爲ActionResources.properties

protected String internalName = "org.apache.struts.action.ActionResources";

//  initInternal();

 

// 一些文檔類型定義,用來驗證相應的配置文件如struts-config.xml是否正確

    protected String[] registrations =

        {

            "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN",

            "/org/apache/struts/resources/struts-config_1_0.dtd",

            "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN",

            "/org/apache/struts/resources/struts-config_1_1.dtd",

            "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN",

            "/org/apache/struts/resources/struts-config_1_2.dtd",

            "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN",

            "/org/apache/struts/resources/struts-config_1_3.dtd",

            "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN",

            "/org/apache/struts/resources/web-app_2_3.dtd"

        }; //  initServlet();

    protected String servletMapping = null; //  initServlet();

protected String servletName = null; //  initServlet();

 

4.  ActionServlet 中的init()方法執行流程以下

 

struts_src.jpg 

① 內部資源文件 ActionResources.properties 的初始化 initInternal();

protected MessageResources internal = null; //  initInternal();

protected String internalName = "org.apache.struts.action.ActionResources"; //  initInternal();

 

// initInternal 方法中經過下面獲得一個MessageResources對象

internal = MessageResources.getMessageResources(internalName);

此資源文件主要包括一些消息信息的定義,具體可參考org.apache.struts.action下的ActionResources.properties文件

 

MessageResources.java中的getMessageResources方法,

        if (defaultFactory == null) {

            defaultFactory = MessageResourcesFactory.createFactory(); // 

        }

        return defaultFactory.createResources(config); // 傳入internalName // 

 

MessageResourcesFactory.createFactory() 所作的工做:

protected static transient Class clazz = null;

protected static String factoryClass =

        "org.apache.struts.util.PropertyMessageResourcesFactory";

clazz = RequestUtils.applicationClass(factoryClass);

RequestUtils.applicationClass經過classLoader加載一個

org.apache.struts.util.PropertyMessageResourcesFactory

 

defaultFactory.createResources(config) 所作的工做:

this.factory = factory;

("org.apache.struts.util.PropertyMessageResourcesFactory")

this.config = config;("org.apache.struts.action.ActionResources")

this.returnNull = returnNull;(true)

PropertyMessageResourcesFactory extends MessageResourcesFactory

返回一個MessageResources對象

 

 

② 調用 initOther(); web.xml中加載ActionServlet的初始化參數,包括config/ convertNull

protected String config = "/WEB-INF/struts-config.xml"; //  initOther();

protected boolean convertNull = false; //  initOther();

 

// 獲得web.xml"config"參數

String value;

value = getServletConfig().getInitParameter("config");

if (value != null) {

    config = value;

}

    <servlet>

        <servlet-name>action</servlet-name>

        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

        <init-param>

            <param-name>config</param-name>   <!-- 獲得"config"參數-->

            <param-value>/WEB-INF/struts-config.xml</param-value>

        </init-param>

        <init-param>

            <param-name>convertNull</param-name>   <!-- 獲得"convertNull"參數-->

            <param-value>true</param-value>

        </init-param>

        .......

    </servlet>   

 

// 得到convertNull的值(true/yes/on/y/1

getServletConfig().getInitParameter("convertNull");

若是這個參數的值爲 true true/yes/on/y/1 數值型(BigDecimal/BigInteger/Boolean/Byte/Character/Double/Float/Integer/Long/Short)Java 包裝類(好比java.lang.Integer)的初始值爲null,而非0。缺省值[false]

 

使其初始值爲null的方法以下:

// 將全部的轉換器註銷掉

ConvertUtils.deregister();

// 爲指定類型clazz註冊轉換器converter

ConvertUtils.register(new BigDecimalConverter(null), BigDecimal.class);

ConvertUtils.register(new BigIntegerConverter(null),BigInteger.class);

.......

 

注: ConvertUtils 用法以下

deregister ()  deregister (java.lang.Class clazz)

註銷轉換器,前者將全部的轉換器註銷掉,後者只註銷對應於clazz的轉換器register( Converter  converter, java.lang.Class clazz)

爲指定類型clazz註冊轉換器converter。若是clazz已經存在一個對應的轉換器,那麼converter覆蓋原來的轉換器。

 

 

③ 調用 initServlet(); web.xml中加載ActionServlet的初始化參數如servlet-name,加載DTD文件並把其放入HashMap緩存,讀取並解析web.xml的內容

// Remember our servlet name

getServletConfig().getServletName();

<servlet>

        <servlet-name>action</servlet-name>

        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

        <init-param>

            <param-name>config</param-name>   <!-- 獲得"config"參數-->

            <param-value>/WEB-INF/struts-config.xml</param-value>

        </init-param>

        <init-param>

            <param-name>convertNull</param-name>   <!-- 獲得"convertNull"參數-->

            <param-value>true</param-value>

        </init-param>

        .......

    </servlet>

 

// Prepare a Digester to scan the web application deployment descriptor

Digester digester = new Digester();

// 把當前的 ActionServlet 對象放入到解析堆棧中

digester.push(this);

// 指明要考慮命名空間

digester.setNamespaceAware(true);

// 缺省值[false] ,解析器只是檢查XML是否格式良好(well formed)

digester.setValidating(false);

 

// Register our local copy of the DTDs that we can find

// struts 可以使用 struts-core-1.3.5.jar  中的DTD中來處理struts配置文件,這樣可適用於那些沒有鏈接到internet的應用環境

        for (int i = 0; i < registrations.length; i += 2) {

            URL url = this.getClass().getResource(registrations[i + 1]);

 

            if (url != null) {

                // 讀取DTD文件並把其放入 HashMap 緩存

                digester.register(registrations[i], url.toString());

            }

        }

 

/************************************************************

// 一些文檔類型定義,用來驗證相應的配置文件如struts-config.xml是否正確

    protected String[] registrations =

        {

            "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN",

            "/org/apache/struts/resources/struts-config_1_0.dtd",

            "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN",

            "/org/apache/struts/resources/struts-config_1_1.dtd",

            "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN",

            "/org/apache/struts/resources/struts-config_1_2.dtd",

            "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN",

            "/org/apache/struts/resources/struts-config_1_3.dtd",

            "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN",

            "/org/apache/struts/resources/web-app_2_3.dtd"

        }; //  initServlet();

************************************************************/

 

// Configure the processing rules that we need

// 運行時,digester 就會調用 ActionServlet中的 addServletMapping() 方法,並傳入兩個參數

digester.addCallMethod("web-app/servlet-mapping", "addServletMapping", 2);

digester.addCallParam("web-app/servlet-mapping/servlet-name", 0);

digester.addCallParam("web-app/servlet-mapping/url-pattern", 1);

獲得

<servlet-mapping>

    <servlet-name>action</servlet-name>

    <url-pattern>*.do</url-pattern>

</servlet-mapping>

 

/************************************************************

// 來判斷當前 servlet 名稱是否爲正在運行的 servlet 名稱,如是,就把 url-pattern 做爲 servletMapping

public void addServletMapping(String servletName, String urlPattern) {

        if (servletName == null) {

            return;

        }

        if (servletName.equals(this.servletName)) {

            if (log.isDebugEnabled()) {

                log.debug("Process servletName=" + servletName

                    + ", urlPattern=" + urlPattern);

            }

            this.servletMapping = urlPattern;

        }

}

************************************************************/

 

// 讀取配置文件web.xml的內容

InputStream input = getServletContext().getResourceAsStream("/WEB-INF/web.xml");

// 如找不到/WEB-INF/web.xml文件,則報錯

if (input == null) {

    log.error(internal.getMessage("configWebXml"));

    throw new ServletException(internal.getMessage("configWebXml"));

}

/************************************************************

// 報錯信息定義在org\apache\struts\action\ActionResources.properties

configWebXml=The /WEB-INF/web.xml was not found.

************************************************************/

 

// 解析input流文件,每讀到一個節點元素就觸發一個事件

digester.parse(input);

 

注: Digester 是一個基於 DOM  SAX 實現的類,它是事件觸發的,能夠將XML文件轉換爲任意的Java對象,支持規則的對任意XML文檔的處理。原先是struts項目的一部分,後因其通用性而劃歸Commons子項目。

 

// servletMapping存儲到servletContext中,屬性名爲Globals.SERVLET_KEY  " org.apache.struts.action.SERVLET_MAPPING " 

if (servletMapping != null) {

    getServletContext().setAttribute(Globals.SERVLET_KEY,servletMapping);

}

相關文章
相關標籤/搜索