天天看點

Struts 2的基石——攔截器(Interceptor)

首先,要跟大家道個歉,前一陣子為給客戶個一個demo,忙得不可開交,是以很久沒有更新blog。提到這個demo我想順便跟大家分享一下心得——如果大家希望快速開發,一個類似struts 2這樣的簡單友善的web架構必不可少。我們在開發demo使用的還是struts

1.2.8,而且沒有不使用任何el(表達式語言),導緻頁面出現無數類似“<%= ((integer) request.getattribute("xx")).intvalue()%6 %>”的代碼。struts 1.x的form bean的麻煩使得有部分同僚直接使用request.getparameter(string arg),繼而引入另一種麻煩。諸如此類的問題,在demo這樣時間緊迫的項目凸顯了struts 1.x對快速開發的無能為力。不過沒辦法,由于我們項目中的幾個資深員工除了struts 1.x外,對其它的web架構似乎不大感興趣。

攔截器,在aop(aspect-oriented programming)中用于在某個方法或字段被通路之前,進行攔截然後在之前或之後加入某些操作。攔截是aop的一種實作政策。

在webwork的中文文檔的解釋為——攔截器是動态攔截action調用的對象。它提供了一種機制可以使開發者可以定義在一個action執行的前後執行的代碼,也可以在一個action執行前阻止其執行。同時也是提供了一種可以提取action中可重用的部分的方式。

談到攔截器,還有一個詞大家應該知道——攔截器鍊(interceptor chain,在struts 2中稱為攔截器棧interceptor stack)。攔截器鍊就是将攔截器按一定的順序聯結成一條鍊。在通路被攔截的方法或字段時,攔截器鍊中的攔截器就會按其之前定義的順序被調用。

struts 2的攔截器實作相對簡單。當請求到達struts 2的servletdispatcher時,struts 2會查找配置檔案,并根據其配置執行個體化相對的攔截器對象,然後串成一個清單(list),最後一個一個地調用清單中的攔截器,如圖1所示。

Struts 2的基石——攔截器(Interceptor)

圖1 攔截器調用序列圖

struts 2已經為您提供豐富多樣的,功能齊全的攔截器實作。大家可以到struts2-all-2.0.1.jar或struts2-core-2.0.1.jar包的struts-default.xml檢視關于預設的攔截器與攔截器鍊的配置。

Struts 2的基石——攔截器(Interceptor)

在本文使用是struts 2的最新釋出版本2.0.1。需要下載下傳的朋友請點選以下連結:

<a target="_blank" href="http://apache.justdn.org/struts/binaries/struts-2.0.1-all.zip">http://apache.justdn.org/struts/binaries/struts-2.0.1-all.zip</a>

以下部分就是從struts-default.xml檔案摘取的内容:

&lt; interceptor name ="alias" class ="com.opensymphony.xwork2.interceptor.aliasinterceptor" /&gt; 

&lt; interceptor name ="autowiring" class ="com.opensymphony.xwork2.spring.interceptor.actionautowiringinterceptor" /&gt; 

&lt; interceptor name ="chain" class ="com.opensymphony.xwork2.interceptor.chaininginterceptor" /&gt; 

&lt; interceptor name ="conversionerror" class ="org.apache.struts2.interceptor.strutsconversionerrorinterceptor" /&gt; 

&lt; interceptor name ="createsession" class ="org.apache.struts2.interceptor.createsessioninterceptor" /&gt; 

&lt; interceptor name ="debugging" class ="org.apache.struts2.interceptor.debugging.debugginginterceptor" /&gt; 

&lt; interceptor name ="external-ref" class ="com.opensymphony.xwork2.interceptor.externalreferencesinterceptor" /&gt; 

&lt; interceptor name ="execandwait" class ="org.apache.struts2.interceptor.executeandwaitinterceptor" /&gt; 

&lt; interceptor name ="exception" class ="com.opensymphony.xwork2.interceptor.exceptionmappinginterceptor" /&gt; 

&lt; interceptor name ="fileupload" class ="org.apache.struts2.interceptor.fileuploadinterceptor" /&gt; 

&lt; interceptor name ="i18n" class ="com.opensymphony.xwork2.interceptor.i18ninterceptor" /&gt; 

&lt; interceptor name ="logger" class ="com.opensymphony.xwork2.interceptor.logginginterceptor" /&gt; 

&lt; interceptor name ="model-driven" class ="com.opensymphony.xwork2.interceptor.modeldriveninterceptor" /&gt; 

&lt; interceptor name ="scoped-model-driven" class ="com.opensymphony.xwork2.interceptor.scopedmodeldriveninterceptor" /&gt; 

&lt; interceptor name ="params" class ="com.opensymphony.xwork2.interceptor.parametersinterceptor" /&gt; 

&lt; interceptor name ="prepare" class ="com.opensymphony.xwork2.interceptor.prepareinterceptor" /&gt; 

&lt; interceptor name ="static-params" class ="com.opensymphony.xwork2.interceptor.staticparametersinterceptor" /&gt; 

&lt; interceptor name ="scope" class ="org.apache.struts2.interceptor.scopeinterceptor" /&gt; 

&lt; interceptor name ="servlet-config" class ="org.apache.struts2.interceptor.servletconfiginterceptor" /&gt; 

&lt; interceptor name ="sessionautowiring" class ="org.apache.struts2.spring.interceptor.sessioncontextautowiringinterceptor" /&gt; 

&lt; interceptor name ="timer" class ="com.opensymphony.xwork2.interceptor.timerinterceptor" /&gt; 

&lt; interceptor name ="token" class ="org.apache.struts2.interceptor.tokeninterceptor" /&gt; 

&lt; interceptor name ="token-session" class ="org.apache.struts2.interceptor.tokensessionstoreinterceptor" /&gt; 

&lt; interceptor name ="validation" class ="com.opensymphony.xwork2.validator.validationinterceptor" /&gt; 

&lt; interceptor name ="workflow" class ="com.opensymphony.xwork2.interceptor.defaultworkflowinterceptor" /&gt; 

&lt; interceptor name ="store" class ="org.apache.struts2.interceptor.messagestoreinterceptor" /&gt; 

&lt; interceptor name ="checkbox" class ="org.apache.struts2.interceptor.checkboxinterceptor" /&gt; 

&lt; interceptor name ="profiling" class ="org.apache.struts2.interceptor.profilingactivationinterceptor" /&gt;

在struts-default.xml中已經配置了以上的攔截器。如果您想要使用上述攔截器,隻需要在應用程式struts.xml檔案中通過“&lt;include file="struts-default.xml" /&gt;”将struts-default.xml檔案包含進來,并繼承其中的struts-default包(package),最後在定義action時,使用“&lt;interceptor-ref name="xx" /&gt;”引用攔截器或攔截器棧(interceptor

stack)。一旦您繼承了struts-default包(package),所有action都會調用攔截器棧 ——defaultstack。當然,在action配置中加入“&lt;interceptor-ref name="xx" /&gt;”可以覆寫defaultstack。

下面是關于攔截器timer使用的例子。首先,建立action類tuotrial/timerinterceptoraction.java,内容如下:

Struts 2的基石——攔截器(Interceptor)

 package tutorial;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 import com.opensymphony.xwork2.actionsupport;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 public class timerinterceptoraction extends actionsupport {

Struts 2的基石——攔截器(Interceptor)

    @override

Struts 2的基石——攔截器(Interceptor)

     public string

execute() {

Struts 2的基石——攔截器(Interceptor)

         try {

Struts 2的基石——攔截器(Interceptor)

             // 模拟耗時的操作 

Struts 2的基石——攔截器(Interceptor)

       thread.sleep( 500 );

Struts 2的基石——攔截器(Interceptor)

        } catch (exception

e) {

Struts 2的基石——攔截器(Interceptor)

            e.printstacktrace();

Struts 2的基石——攔截器(Interceptor)

        } 

Struts 2的基石——攔截器(Interceptor)

         return success;

Struts 2的基石——攔截器(Interceptor)

    } 

Struts 2的基石——攔截器(Interceptor)

}

配置action,名為timer,配置檔案如下:

&lt;! doctype struts public

        "-//apache software foundation//dtd struts configuration 2.0//en"

&lt; struts &gt; 

    &lt; include file ="struts-default.xml" /&gt;  

    &lt; package name ="interceptordemo" extends ="struts-default" &gt; 

        &lt; action name ="timer" class ="tutorial.timerinterceptoraction" &gt; 

            &lt; interceptor-ref name ="timer" /&gt; 

            &lt; result &gt; /timer.jsp &lt;/ result &gt; 

        &lt;/ action &gt; 

    &lt;/ package &gt; 

&lt;/ struts &gt;

2006 - 12 - 6 14 : 27 : 32 com.opensymphony.xwork2.interceptor.timerinterceptor

dolog

資訊: executed action [ //timer!execute ] took 2859 ms.

在您的環境中執行timer!execute的耗時,可能上述的時間有些不同,這取決于您pc的性能。但是無論如何,2859 ms與500 ms還是相差太遠了。這是什麼原因呢?其實原因是第一次加載timer時,需要進行一定的初始工作。當你重新請求timer.action時,以上輸出會變為:

2006 - 12 - 6 14 : 29 : 18 com.opensymphony.xwork2.interceptor.timerinterceptor

資訊: executed action [ //timer!execute ] took 500 ms.

ok,這正是我們期待的結果。上述例子示範了攔截器timer的用途——用于顯示執行某個action方法的耗時,在我們做一個粗略的性能調試時,這相當有用。

作為“架構(framework)”,可擴充性是不可或缺的,因為世上沒有放之四海而皆準的東西。雖然,struts 2為我們提供如此豐富的攔截器實作,但是這并不意味我們失去建立自定義攔截器的能力,恰恰相反,在struts 2自定義攔截器是相當容易的一件事。

Struts 2的基石——攔截器(Interceptor)

大家在開始着手建立自定義攔截器前,切記以下原則:

攔截器必須是無狀态的,不要使用在api提供的actioninvocation之外的任何東西。

要求攔截器是無狀态的原因是struts 2不能保證為每一個請求或者action建立一個執行個體,是以如果攔截器帶有狀态,會引發并發問題。

所有的struts 2的攔截器都直接或間接實作接口com.opensymphony.xwork2.interceptor.interceptor。除此之外,大家可能更喜歡繼承類com.opensymphony.xwork2.interceptor.abstractinterceptor。

以下例子示範通過繼承abstractinterceptor,實作授權攔截器。

首先,建立授權攔截器類tutorial.authorizationinterceptor,代碼如下:

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 import java.util.map;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 import com.opensymphony.xwork2.action;

Struts 2的基石——攔截器(Interceptor)

 import com.opensymphony.xwork2.actioninvocation;

Struts 2的基石——攔截器(Interceptor)

 import com.opensymphony.xwork2.interceptor.abstractinterceptor;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 public class authorizationinterceptor extends abstractinterceptor {

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

intercept(actioninvocation ai) throws exception {

Struts 2的基石——攔截器(Interceptor)

        map session = ai.getinvocationcontext().getsession();

Struts 2的基石——攔截器(Interceptor)

        string role = (string)

session.get( " role " );

Struts 2的基石——攔截器(Interceptor)

         if ( null != role) {

Struts 2的基石——攔截器(Interceptor)

            object o = ai.getaction();

Struts 2的基石——攔截器(Interceptor)

             if (o instanceof roleaware) {

Struts 2的基石——攔截器(Interceptor)

                roleaware action = (roleaware)

o;

Struts 2的基石——攔截器(Interceptor)

                action.setrole(role);

Struts 2的基石——攔截器(Interceptor)

            } 

Struts 2的基石——攔截器(Interceptor)

             return ai.invoke();

Struts 2的基石——攔截器(Interceptor)

        } else {

Struts 2的基石——攔截器(Interceptor)

             return action.login;

Struts 2的基石——攔截器(Interceptor)

        }  

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

以上代碼相當簡單,我們通過檢查session是否存在鍵為“role”的字元串,判斷使用者是否登陸。如果使用者已經登陸,将角色放到action中,調用action;否則,攔截直接傳回action.login字段。為了友善将角色放入action,我定義了接口tutorial.roleaware,代碼如下:

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 public interface roleaware {

Struts 2的基石——攔截器(Interceptor)

     void setrole(string

role);

Struts 2的基石——攔截器(Interceptor)

接着,建立action類tutorial.authorizatedaccess模拟通路受限資源,它作用就是通過實作roleaware擷取角色,并将其顯示到showuser.jsp中,代碼如下:

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 public class authorizatedaccess extends actionsupport implements roleaware {

Struts 2的基石——攔截器(Interceptor)

     private string

role;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

     public void setrole(string

role) {

Struts 2的基石——攔截器(Interceptor)

         this .role = role;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

getrole() {

Struts 2的基石——攔截器(Interceptor)

         return role;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

以下是showuser.jsp的代碼:

&lt;% @ page  contenttype = " text/html;

charset=utf-8 " %&gt; 

&lt;% @taglib prefix = " s " uri = " /struts-tags " %&gt; 

&lt; html &gt; 

&lt; head &gt; 

    &lt; title &gt; authorizated

user &lt;/ title &gt; 

&lt;/ head &gt; 

&lt; body &gt; 

    &lt; h1 &gt; your

role is: &lt; s:property value ="role" /&gt;&lt;/ h1 &gt; 

&lt;/ body &gt; 

&lt;/ html &gt;

然後,建立tutorial.roles初始化角色清單,代碼如下:

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 import java.util.hashtable;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 public class roles {

Struts 2的基石——攔截器(Interceptor)

     public map &lt; string,

string &gt; getroles() {

Struts 2的基石——攔截器(Interceptor)

        map &lt; string,

string &gt; roles = new hashtable &lt; string,

string &gt; ( 2 );

Struts 2的基石——攔截器(Interceptor)

        roles.put( " employee " , " employee " );

Struts 2的基石——攔截器(Interceptor)

        roles.put( " manager " , " manager " );

Struts 2的基石——攔截器(Interceptor)

         return roles;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

接下來,建立login.jsp執行個體化tutorial.roles,并将其roles屬性賦予&lt;s:radio&gt;标志,代碼如下:

    &lt; title &gt; login &lt;/ title &gt; 

    &lt; h1 &gt; login &lt;/ h1 &gt; 

    please select a role below:

    &lt; s:bean id ="roles" name ="tutorial.roles" /&gt; 

    &lt; s:form action ="login" &gt; 

        &lt; s:radio list ="#roles.roles" value ="'employee'" name ="role" label ="role" /&gt; 

        &lt; s:submit /&gt; 

    &lt;/ s:form &gt; 

建立action類tutorial.login将role放到session中,并轉到action類tutorial.authorizatedaccess,代碼如下:

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 import org.apache.struts2.interceptor.sessionaware;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

 public class login extends actionsupport implements sessionaware {

Struts 2的基石——攔截器(Interceptor)

role;    

Struts 2的基石——攔截器(Interceptor)

     private map

session;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

     public void setsession(map

session) {

Struts 2的基石——攔截器(Interceptor)

         this .session = session;

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

        session.put( " role " ,

Struts 2的基石——攔截器(Interceptor)
Struts 2的基石——攔截器(Interceptor)

    }  

Struts 2的基石——攔截器(Interceptor)

最後,配置struts.xml檔案,内容如下:

        &lt; interceptors &gt; 

            &lt; interceptor name ="auth" class ="tutorial.authorizationinterceptor" /&gt; 

        &lt;/ interceptors &gt; 

        &lt; action name ="login" class ="tutorial.login" &gt; 

            &lt; result type ="chain" &gt; authorizatedaccess &lt;/ result &gt; 

        &lt; action name ="authorizatedaccess" class ="tutorial.authorizatedaccess" &gt; 

            &lt; interceptor-ref name ="auth" /&gt; 

            &lt; result name ="login" &gt; /login.jsp &lt;/ result &gt; 

            &lt; result name ="success" &gt; /showrole.jsp &lt;/ result &gt; 

Struts 2的基石——攔截器(Interceptor)

圖2 login.jsp

選中employee,點選submit,出現圖3所示頁面:

Struts 2的基石——攔截器(Interceptor)

圖3 showrole.jsp

攔截器是struts 2比較重要的一個功能。通過正确地使用攔截器,我們可以編寫高可複用的代碼。