在我的博客struts2拦截器篇(一),我们已经充分了解了拦截器及其使用,那么拦截器究竟是怎么实现的呢,让我们一起来编写一个拦截器类吧。
一个拦截器类必须实现Interceptor接口,这个接口的实现在struts提供的包中可以找到,路径为:e:\struts-2.3.24\src\xwork-core\src\main\java\com\opensymphony\xwork2\interceptor\Interceptor.java
public interface Interceptor extends Serializable {
// 销毁前调用的方法
void destroy();
// 初始化时调用的方法
void init();
// 实现拦截器逻辑的方法
String intercept(ActionInvocation invocation) throws Exception;
}
通常情况下init和destroy方法并不常用到,所以struts2中还提供了一个抽象类AbstractInterceptor,该类继承了Interceptor接口,该抽象类中提供了init和destroy方法的空实现,需要时可以覆盖它们
public abstract class AbstractInterceptor implements Interceptor {
/**
* Does nothing
*/
public void init() {
}
/**
* Does nothing
*/
public void destroy() {
}
/**
* Override to handle interception
*/
public abstract String intercept(ActionInvocation invocation) throws Exception;
}
下面让我们来实现一个简单的自定义拦截器吧,其功能是进行权限验证,
public class AuthorizationInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
//获得ActionContext对象
ActionContext ctx = invocation.getInvocationContext();
Map session = ctx.getSession();
String user = (String)session.get("username");
if(user!=null&&"bill".equals(user)){
return invocation.invoke();//如果已经登录则执行下一个拦截器或execute方法
}else{
return Action.LOGIN;//否则 返回登录结果
}
}
}
在struts.xml中的配置,
……
<interceptors>
<interceptor name="authorization" class="interceptor.AuthorizationInterceptor"/>
</interceptors>
<action name="login" class="action.LoginAction" method="process">
<result name="success">
/success.jsp
</result>
<interceptor-ref name="defaultStack" />
<interceptor-ref name="authorization"/>
</action>
……
到此,权限验证的拦截器就实现了,是不是很简单。权限验证基本上在所有的Action中都需要用到,所有可以设置为默认拦截器,也可以和其他常用的拦截器封装到拦截器栈中,设置成默认拦截器栈,简化配置