Struts 2 struts.xml詳解(二)

Action配置

        上節大致講了關於struts.xml的整體結構,下面講一下它的一些詳細的配置。先從action說起吧!


Method屬性

        在action中有一個method屬性,可以指定此action調用哪一個方法。如果沒有指定,默認調用execute()方法。

        例如:

<action name="Login"class="com.stuqbx.web.action. HelloWorld" method=”login”>
        <result name="error">/pages/error.jsp</result>
        <result name="success">/pages/HelloWorld.jsp</result>
</action>

        上面的配置指定Login.action調用HelloWorld的login方法。但是需注意調用的方法的簽名要和execute()簽名一樣,即login的簽名爲:public String login() throws Exception。


Action動態方法調用

        在Struts 2的核心jar包-struts2-core中,有一個default.properties的默認配置文件。裏面配置了一些全局的信息。這裏如果把struts.enable.DynamicMethodInvocation= true(default.properties是不能被更改的。如需要更改裏面的配置信息,可以在src根目錄下建一個 struts.properties的配置文件,然後重寫所要更改的配置信息或者可以用constant標籤在struts.xml配置),——動態方法調用,爲true時,就可以在struts.xml配置“*”的通配符,來調用action裏的方法。

        通配符有點類似於變量,但這裏的變量是用“*”表示。

        看一個例子:

<action name="HelloWorld_*" method="{1}" class="com.stuqbx.web.action.HelloWorld ">
       <result name="success">/pages/success.jsp</result>
       <result name="error">/pages/error.jsp</result>
</action>
        這裏在action的name中通配了一個HelloWorld_*",它對應映射的是method屬性。如果在客戶端發生一個這樣的請求:HelloWorld_login.action、HelloWorld_show.action等,這時服務器就會自動調用這個action中的login ()方法或show()方法。這裏的method="{1}"代表是第一個“*”,如果有多個星號,就要根據順序來通配{1},{2},{3}....

        再如下面多個星號的配置:

<action name="*/*" method="{2}" class="com.stuqbx.web.action.{1}">
        <result name="succes" >/pages/success.jsp</result>
        <result name="error" >/pages/error.jsp</result> 
</action>

        其中第一個“*”映射到具體的某個action類,第二個“*”映射到該類的方法。不過這裏要注意的name=”*/*",是相當於客戶端要發送如 “HelloWorld/login.action”,在地址欄裏就變成了/struts/HelloWorld/login.action,那服務器到底是會認/login.action還是HelloWorld/login.action呢。其實服務器默認還是/login.action,如果要使帶"/"的action生 效,需要把default.properties中的struts.enable.SlashesInActionNames= false改爲true就可以。


默認的Action

        當沒有指定Action的class屬性的時候,例如:

<action name="HelloWorld"/> 

        則默認使用com.opensymphony.xwork.ActionSupport。ActionSuppor有兩個方法input和execute,每個方法都是簡單的返回SUCCESS。

        通常情況下,請求的Action不存在的情況下,Struts2框架會返回一個Error畫面:“404 - Page not found”,有些時候或許我們不想出現一個控制之外的錯誤畫面,我們可以指定一個默認的Action,在請求的Action不存在的情況下,調用默認的Action,通過如下配置可以實現: 

<package name="com.stuqbx.web.action" extends="action-default"> 
        <default-action-ref name="DefaultAction"/> 
        <action name="DefaultAction">
                <result>/pages/default.jsp</result>
        </action> 
</package>


Action參數

        在struts2中可以爲action指定參數。大家還記着struts1是如何設置的action參數不?在struts 1中可以使用<action>標籤的parameter屬性爲其指定一個action參數,如果要指定多個,就只能通過逗號(,)或其他的分隔符將不同的參數隔開。而在struts 2中可以通過<param>標籤爲action指定任意多個參數。

        配置如下:

<action name="ParamAction" class="com.stuqbx.web.action.ParamAction">
       <param name="param1">value1</param>
       <param name="param2">value2</param>
       <result name="save">/pages/save.jsp</result>
</action>

        在action中讀參數非常簡單,只需要像獲取請求參數一樣在action類中定義相應的setter方法即可(一般不用定義getter方法),這樣就可以將參數的值注入相應的參數中。

        如下面的代碼將讀取param1和param2參數的值:

public class ParamAction extends ActionSupport
{
     private String param1;
     private String param2;

     public void setParam1(String param1)
     {
         this.param1 = param1;
     }

     public void setParam2(String param2)
     {
         this.param2 = param2;
     }

     public String execute() throws Exception
     {
            String str = param1 + param2;
            …
     }
}

        當struts 2在調用execute之前,param1和param2就已經被注入相應的值了,因此,在execute方法中可以直接使用param1和param2。


Result類型

        在action的result時,如果沒有指定type,那麼默認爲” dispatche”(實際上就是轉發,forward)。我們也可以根據需要指定它的類型。

如下面的配置指定result的類型爲redirect

<action name="HelloWorld!login" class="com.stuqbx.web.action.HelloWorld">
        <result name="error" type="redirect">/pages/error.jsp</result>
</action>

        result-type可以在struts2-core-2.*.jar包或struts 2源代碼中的struts-default.xml文件中找到,在這個文件中找到<result-types>標籤,所有的result-type都在裏面定義了。

代碼如下:

<result-types>
        <result-type name="chain"class="com.opensymphony.xwork2.ActionChainResult"/>
        <result-type name="dispatcher"class="org.apache.struts2.dispatcher.ServletDispatcherResult"default="true"/>
        <result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>
        <result-type name="httpheader"class="org.apache.struts2.dispatcher.HttpHeaderResult"/>
        <result-type name="redirect"class="org.apache.struts2.dispatcher.ServletRedirectResult"/>
        <result-type name="redirectAction"class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>
        <result-type name="stream"class="org.apache.struts2.dispatcher.StreamResult"/>
        <result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>
        <result-type name="xslt"class="org.apache.struts2.views.xslt.XSLTResult"/>
        <result-type name="plainText"class="org.apache.struts2.dispatcher.PlainTextResult" />
        <!-- Deprecated name form scheduledfor removal in Struts 2.1.0. The camelCase versions are preferred. See ww-1707-->
        <result-type name="redirect-action"class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>
        <result-type name="plaintext" class="org.apache.struts2.dispatcher.PlainTextResult"/>
</result-types>

類型

描述

chain

用來處理Action鏈

dispatcher

用來轉向頁面,通常處理JSP,這是默認的結果類型

freeMarker

處理FreeMarker模板

httpHeader

用來控制特殊的Http行爲

redirect

重定向到一個URL

redirect-action

重定向到一個Action

stream

向瀏覽器發送InputSream對象,通常用來處理文件下載

velocity

處理Velocity模板

xslt

處理XML/XLST模板

plaintext

顯示原始文件內容,例如文件源代碼

tiles

結合Tile使用

        另外第三方的Result類型還包括JasperReports Plugin,專門用來處理JasperReport類型的報表輸出;JfreechartPlugin;JSF Plugin。


全局的result

        很多時候,很多action可能有相同的result(也就是說一個result被多個action使用),可是在每個action裏都定義一個result很繁瑣,這時我們可以把這個公用的result定義成全局的,這樣就可以同時被多個action使用了。

例如:

<package name="com.stuqbx.web.action"namespace="/action" extends="struts-default">
      <global-results>
             <result name="print">/pages/global.jsp</result>
      </global-results>

      <action name="PrintHelloWorld"class=" com.stuqbx.web.action. HelloWorld"method="print">
            <result name="error">/pages/error.jsp</result>
            <result name="success">/pages/HelloWorld.jsp</result>
      </action>

      <action name="PrintTest" class="com.stuqbx.web.action.Test"method="print"/>
</packgage>

        HelloWorld和Teat裏都有一個方法print(),返回值都是”print”, PrintTest.action和PrintHelloWorld.action都調用各自的print()方法,但是他們的action裏都沒有定義name=”print”的result,此時,它們仍然可以訪問,其實它們都是用global-results裏的name爲”print”的result。

 

        以上講的都是關於action的配置,既然說到action,再補充一點不是關於配置的。

Action訪問Servlet

        Struts2中的Action並沒有和任何Servlet API耦合,這樣框架更具靈活性,更易測試。

        但是,對於web應用的控制器而言,不訪問Servlet幾乎是不可能的,例如跟蹤HTTPSession狀態等。Struts 2框架提供了一種更輕鬆的方式來訪問Servlet。Struts 2中提供了一個ActionContext類(當前Action的上下文對象),通過這個類可以訪問Servlet。

        下面是該類中提供的幾個常用方法:

                 public static ActionContext getContext() :獲得當前Action的ActionContext實例。

                 public Object get(Object key) :此方法類似於調用HttpServletRequest的getAttribute(String name)方法。

                 public void put(Object key, Object value) :此方法類似於調用HttpServletRequest的setAttribute(String name, Object o)。

                 public Map getParameters() :獲取所有的請求參數。類似於調用HttpServletRequest對象的getParameterMap() 方法。

                 public Map getSession() :返回一個Map對象,該Map對象模擬了HttpSession實例。

                 public void setSession(Map session) :直接傳入一個Map實例,將該Map實例裏的key-value對轉換成session的屬性名-屬性值對。

                 public Map getApplication() :返回一個Map對象,該對象模擬了該應用的ServletContext實例。

                 public void setApplication(Map application) :直接傳入一個Map實例,將該Map實例裏的key-value對轉換成application的屬性名-屬性值對。

        Struts2中通過ActionContext來訪問Servlet,讓Action徹底從Servlet中分離出來,最大的好處就是可以脫離Web容器測試Action。

另外,Struts2中還提供了一個ServletActionContext類,Action只要繼承自該類,就可以直接訪問Servlet。具體方法參看struts 2的API文檔。




轉載請註明出處!!!

http://blog.csdn.net/stuqbx

 

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