一、什么是拦截器
拦截器是AOP的一种实现策略,在Webwork的中文文档的解释为——拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。 而拦截器链就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。在struts2中,当请求到达ServletDispatcher时,Struts 2会查找配置文件,并根据其配置实例化相应的拦截器对象,然后串成一个列表(list),最后一个一个地调用列表中的拦截器。
二、使用struts2.0自带的拦截器
struts2.0自身包含了丰富的的拦截器,在struts2-core-2.0.1.jar包的struts-default.xml可以查看关于默认的拦截器与拦截器链的配置。当我们要使用struts2.0自带的拦截器时,action所在的包名需要继承struts-default包,然后在action配置中定义使用的拦截器或拦截器链的名字。如:
<! DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd" >
< struts >
< include file ="struts-default.xml" />
< package name ="test" extends ="struts-default" >
< action name ="Timer" class ="test.Test" >
< interceptor-ref name ="timer" />
< result name="test"> /test.jsp </ result >
</ action >
</ package >
</ struts >
三、自定义拦截器
自定义的拦截器必须是无状态的,以免引起并发问题。所有的Struts 2的拦截器都直接或间接实现接口com.opensymphony.xwork2.interceptor.Interceptor。抽像类com.opensymphony.xwork2.interceptor.AbstractInterceptor实现了该接口,我们自定义拦截器时一般只要继承这个抽像类就可以了。
public String intercept(ActionInvocation ia) throws Exception {
ActionContext ac = ia.getInvocationContext();
ServletContext servletContext = (ServletContext) ac
.get(ServletActionContext.SERVLET_CONTEXT);
WebApplicationContext wc = WebApplicationContextUtils
.getWebApplicationContext(servletContext);
if (wc == null) {
logger.error("ApplicationContext could not be found.");
} else {
Object action = ia.getAction();
if (action instanceof LoginAction) {
ia.invoke();
}
Map session = ia.getInvocationContext().getSession();
String login = (String) session.get("username");
if (login != null && login.length() > 0) {
// 登录的情况下进行后续操作。
return ia.invoke();
} else {
// 否则终止后续操作,返回LOGIN
return loginpage;
}
}
return ia.invoke();
}
配置拦截器:
< package name ="test" extends ="struts-default" >
< interceptors >
< interceptor name ="auth" class ="testInterceptor" />
</ interceptors > </page>