首先,要跟大家道个歉,前一阵子为给客户个一个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比较重要的一个功能。通过正确地使用拦截器,我们可以编写高可复用的代码。