1. 程式人生 > >Struts2學習筆記2---配置檔案

Struts2學習筆記2---配置檔案

      在Struts2中主要有兩個配置檔案:web.xml和struts.xml,當新建一個web專案時,可以從Struts2的示例程式中複製一份,然後做相應的修改即可。web.xml的基本形式如下:

<web-app id="WebApp_9" 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">

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        <init-param>
        	<param-name>actionPackages</param-name>
        	<param-value>com.mycompany.myapp.actions</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- ... -->

</web-app>

     其實在這裡面,就定義了一個過濾器,用來過濾客戶端的請求,把攔截到得請求交給Struts2的StrutsPrepareAndExecuteFilter進行相應的處理,這個以後再說。對於<filter-mapping>這個標籤,定義了要攔截的請求型別,這裡寫為/*是指過濾所有的url請求。

       Struts2中還有一個比較重要的配置檔案struts.xml,它的基本內容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />

    <include file="example.xml"/>

    <package name="default" namespace="/" extends="struts-default">
        <default-action-ref name="index" />
        <action name="index">
            <result type="redirectAction">
                <param name="actionName">HelloWorld</param>
                <param name="namespace">/example</param>
            </result>
        </action>
    </package>

    <!-- Add packages here -->

</struts>

      上面這個示例檔案包含了一些最基本的配置,一般我們在開發時會把struts.devMode屬性改為true,即開啟開發模式,這樣我們對檔案的修改即可隨時體現在伺服器上。<include>標籤可以用來引入另外的配置檔案,比如說一個系統有多人開發,每個人都會有自己的配置檔案,專案完成之後再用這個標籤把所有的配置集中起來。

       接下來是Package標籤,實際上就是定義了一個包,一般可用來劃分相應的模組。在每個包中會定義若干個Action,可以用來進行相應的業務處理。每個Action都會有一個name屬性,指定這個action的名字,class屬性對應了這個action對應的具體action的實現,如果不指定class屬性,預設就為ActionSupport這個類,它的method方法用來指定這個action要執行的方法,如果不指定,預設為execute()方法。每一個action執行完之後都會返回一個字串型別的值,這就對應了每個result的name,這時就會去找相應的result,然後把結果返回回客戶端。

       總的來說,web.xml用來實現對客戶端請求的攔截,而struts.xml實現了請求處理轉發的流程。