struts2拦截器的使用一般是用来判断权限的,如,如果用户没有登录则不允许访问,直接返回;或者如果用户没有xxx属性则不允许登录,返回
如何自定义一个拦截器?
自定义一个拦截器需要三步:
1 自定义一个实现Interceptor接口(或者继承自AbstractInterceptor)的类。
2 在strutx.xml中注册上一步中定义的拦截器。
3 在需要使用的Action中引用上述定义的拦截器,为了方便也可将拦截器定义为默认的拦截器,这样在不加特殊声明的情况下所有的Action都被这个拦截器拦截。(<default-interceptor-ref name="teamwareStack"/>)
Interceptor接口声明了三个方法:
public interface Interceptor extends Serializable {
void destroy();
void init();
String intercept(ActionInvocation invocation) throws Exception;
}
Init方法在拦截器类被创建之后,在对Action镜像拦截之前调用,相当于一个post-constructor方法,使用这个方法可以给拦截器类做必要的初始话操作。
Destroy方法在拦截器被垃圾回收之前调用,用来回收init方法初始化的资源。
Intercept是拦截器的主要拦截方法,如果需要调用后续的Action或者拦截器,只需要在该方法中调用invocation.invoke()方法即可,在该方法调用后可以插入Action调用前后拦截器需要做的方法。如果不需要调用后续的方法,则返回一个String类型的对象即可,例如Action.SUCCESS。
另外AbstractInterceptor提供了一个简单的Interceptor的实现,这个实现为:
public abstract class AbstractInterceptor implements Interceptor {
public void init() {
}
public void destroy() {
}
public abstract String intercept(ActionInvocation invocation) throws Exception;
}
在不需要编写init和destroy方法的时候,只需要从AbstractInterceptor继承而来,实现intercept方法即可。
我们尝试编写一个Session过滤用的拦截器,该拦截器查看用户Session中是否存在特定的属性(LOGIN属性)如果不存在,中止后续操作定位到LOGIN,否则执行原定操作,代码为:
public class CheckLoginInterceptor extends AbstractInterceptor {
public static final String LOGIN_KEY = "LOGIN";
public static final String LOGIN_PAGE = "global.login";
public String intercept(ActionInvocation actionInvocation) throws Exception {
System.out.println("begin check login interceptor!");
// 对LoginAction不做该项拦截
Object action = actionInvocation.getAction();
if (action instanceof LoginAction) {
System.out.println("exit check login, because this is login action.");
return actionInvocation.invoke();//执行LoginAction的方法,不拦截该action
}
// 确认Session中是否存在LOGIN
Map session = actionInvocation.getInvocationContext().getSession();
String login = (String) session.get(LOGIN_KEY);
if (login != null && login.length() > 0) {
// 存在的情况下进行后续操作。
System.out.println("already login!");
return actionInvocation.invoke();
} else {
// 否则终止后续操作,返回LOGIN
System.out.println("no login, forward login page!");
return LOGIN_PAGE;
}
}
}
注册拦截器
<interceptors>
<interceptor
name="login"
class="com.jpleasure.teamware.util.CheckLoginInterceptor"/>
<interceptor-stack name="teamwareStack">
<interceptor-ref name="login"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
如果只为某个action的引用该拦截器,则只需要在action中引入<intercept-ref ....>即可。
如果要整个包中的所以action引用拦截器,则;
<default-interceptor-ref name="teamwareStack"/>
这样在后续同一个package内部的所有Action执行之前都会被login拦截。