首先,要跟大家道個歉,前一陣子為給客戶個一個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所示。

圖1 攔截器調用序列圖
struts 2已經為您提供豐富多樣的,功能齊全的攔截器實作。大家可以到struts2-all-2.0.1.jar或struts2-core-2.0.1.jar包的struts-default.xml檢視關于預設的攔截器與攔截器鍊的配置。
在本文使用是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檔案摘取的内容:
< interceptor name ="alias" class ="com.opensymphony.xwork2.interceptor.aliasinterceptor" />
< interceptor name ="autowiring" class ="com.opensymphony.xwork2.spring.interceptor.actionautowiringinterceptor" />
< interceptor name ="chain" class ="com.opensymphony.xwork2.interceptor.chaininginterceptor" />
< interceptor name ="conversionerror" class ="org.apache.struts2.interceptor.strutsconversionerrorinterceptor" />
< interceptor name ="createsession" class ="org.apache.struts2.interceptor.createsessioninterceptor" />
< interceptor name ="debugging" class ="org.apache.struts2.interceptor.debugging.debugginginterceptor" />
< interceptor name ="external-ref" class ="com.opensymphony.xwork2.interceptor.externalreferencesinterceptor" />
< interceptor name ="execandwait" class ="org.apache.struts2.interceptor.executeandwaitinterceptor" />
< interceptor name ="exception" class ="com.opensymphony.xwork2.interceptor.exceptionmappinginterceptor" />
< interceptor name ="fileupload" class ="org.apache.struts2.interceptor.fileuploadinterceptor" />
< interceptor name ="i18n" class ="com.opensymphony.xwork2.interceptor.i18ninterceptor" />
< interceptor name ="logger" class ="com.opensymphony.xwork2.interceptor.logginginterceptor" />
< interceptor name ="model-driven" class ="com.opensymphony.xwork2.interceptor.modeldriveninterceptor" />
< interceptor name ="scoped-model-driven" class ="com.opensymphony.xwork2.interceptor.scopedmodeldriveninterceptor" />
< interceptor name ="params" class ="com.opensymphony.xwork2.interceptor.parametersinterceptor" />
< interceptor name ="prepare" class ="com.opensymphony.xwork2.interceptor.prepareinterceptor" />
< interceptor name ="static-params" class ="com.opensymphony.xwork2.interceptor.staticparametersinterceptor" />
< interceptor name ="scope" class ="org.apache.struts2.interceptor.scopeinterceptor" />
< interceptor name ="servlet-config" class ="org.apache.struts2.interceptor.servletconfiginterceptor" />
< interceptor name ="sessionautowiring" class ="org.apache.struts2.spring.interceptor.sessioncontextautowiringinterceptor" />
< interceptor name ="timer" class ="com.opensymphony.xwork2.interceptor.timerinterceptor" />
< interceptor name ="token" class ="org.apache.struts2.interceptor.tokeninterceptor" />
< interceptor name ="token-session" class ="org.apache.struts2.interceptor.tokensessionstoreinterceptor" />
< interceptor name ="validation" class ="com.opensymphony.xwork2.validator.validationinterceptor" />
< interceptor name ="workflow" class ="com.opensymphony.xwork2.interceptor.defaultworkflowinterceptor" />
< interceptor name ="store" class ="org.apache.struts2.interceptor.messagestoreinterceptor" />
< interceptor name ="checkbox" class ="org.apache.struts2.interceptor.checkboxinterceptor" />
< interceptor name ="profiling" class ="org.apache.struts2.interceptor.profilingactivationinterceptor" />
在struts-default.xml中已經配置了以上的攔截器。如果您想要使用上述攔截器,隻需要在應用程式struts.xml檔案中通過“<include file="struts-default.xml" />”将struts-default.xml檔案包含進來,并繼承其中的struts-default包(package),最後在定義action時,使用“<interceptor-ref name="xx" />”引用攔截器或攔截器棧(interceptor
stack)。一旦您繼承了struts-default包(package),所有action都會調用攔截器棧 ——defaultstack。當然,在action配置中加入“<interceptor-ref name="xx" />”可以覆寫defaultstack。
下面是關于攔截器timer使用的例子。首先,建立action類tuotrial/timerinterceptoraction.java,内容如下:
package tutorial;
import com.opensymphony.xwork2.actionsupport;
public class timerinterceptoraction extends actionsupport {
@override
public string
execute() {
try {
// 模拟耗時的操作
thread.sleep( 500 );
} catch (exception
e) {
e.printstacktrace();
}
return success;
}
}
配置action,名為timer,配置檔案如下:
<! doctype struts public
"-//apache software foundation//dtd struts configuration 2.0//en"
< struts >
< include file ="struts-default.xml" />
< package name ="interceptordemo" extends ="struts-default" >
< action name ="timer" class ="tutorial.timerinterceptoraction" >
< interceptor-ref name ="timer" />
< result > /timer.jsp </ result >
</ action >
</ package >
</ struts >
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自定義攔截器是相當容易的一件事。
大家在開始着手建立自定義攔截器前,切記以下原則:
攔截器必須是無狀态的,不要使用在api提供的actioninvocation之外的任何東西。
要求攔截器是無狀态的原因是struts 2不能保證為每一個請求或者action建立一個執行個體,是以如果攔截器帶有狀态,會引發并發問題。
所有的struts 2的攔截器都直接或間接實作接口com.opensymphony.xwork2.interceptor.interceptor。除此之外,大家可能更喜歡繼承類com.opensymphony.xwork2.interceptor.abstractinterceptor。
以下例子示範通過繼承abstractinterceptor,實作授權攔截器。
首先,建立授權攔截器類tutorial.authorizationinterceptor,代碼如下:
import java.util.map;
import com.opensymphony.xwork2.action;
import com.opensymphony.xwork2.actioninvocation;
import com.opensymphony.xwork2.interceptor.abstractinterceptor;
public class authorizationinterceptor extends abstractinterceptor {
intercept(actioninvocation ai) throws exception {
map session = ai.getinvocationcontext().getsession();
string role = (string)
session.get( " role " );
if ( null != role) {
object o = ai.getaction();
if (o instanceof roleaware) {
roleaware action = (roleaware)
o;
action.setrole(role);
}
return ai.invoke();
} else {
return action.login;
}
以上代碼相當簡單,我們通過檢查session是否存在鍵為“role”的字元串,判斷使用者是否登陸。如果使用者已經登陸,将角色放到action中,調用action;否則,攔截直接傳回action.login字段。為了友善将角色放入action,我定義了接口tutorial.roleaware,代碼如下:
public interface roleaware {
void setrole(string
role);
接着,建立action類tutorial.authorizatedaccess模拟通路受限資源,它作用就是通過實作roleaware擷取角色,并将其顯示到showuser.jsp中,代碼如下:
public class authorizatedaccess extends actionsupport implements roleaware {
private string
role;
public void setrole(string
role) {
this .role = role;
getrole() {
return role;
以下是showuser.jsp的代碼:
<% @ page contenttype = " text/html;
charset=utf-8 " %>
<% @taglib prefix = " s " uri = " /struts-tags " %>
< html >
< head >
< title > authorizated
user </ title >
</ head >
< body >
< h1 > your
role is: < s:property value ="role" /></ h1 >
</ body >
</ html >
然後,建立tutorial.roles初始化角色清單,代碼如下:
import java.util.hashtable;
public class roles {
public map < string,
string > getroles() {
map < string,
string > roles = new hashtable < string,
string > ( 2 );
roles.put( " employee " , " employee " );
roles.put( " manager " , " manager " );
return roles;
接下來,建立login.jsp執行個體化tutorial.roles,并将其roles屬性賦予<s:radio>标志,代碼如下:
< title > login </ title >
< h1 > login </ h1 >
please select a role below:
< s:bean id ="roles" name ="tutorial.roles" />
< s:form action ="login" >
< s:radio list ="#roles.roles" value ="'employee'" name ="role" label ="role" />
< s:submit />
</ s:form >
建立action類tutorial.login将role放到session中,并轉到action類tutorial.authorizatedaccess,代碼如下:
import org.apache.struts2.interceptor.sessionaware;
public class login extends actionsupport implements sessionaware {
role;
private map
session;
public void setsession(map
session) {
this .session = session;
session.put( " role " ,
}
最後,配置struts.xml檔案,内容如下:
< interceptors >
< interceptor name ="auth" class ="tutorial.authorizationinterceptor" />
</ interceptors >
< action name ="login" class ="tutorial.login" >
< result type ="chain" > authorizatedaccess </ result >
< action name ="authorizatedaccess" class ="tutorial.authorizatedaccess" >
< interceptor-ref name ="auth" />
< result name ="login" > /login.jsp </ result >
< result name ="success" > /showrole.jsp </ result >
圖2 login.jsp
選中employee,點選submit,出現圖3所示頁面:
圖3 showrole.jsp
攔截器是struts 2比較重要的一個功能。通過正确地使用攔截器,我們可以編寫高可複用的代碼。