如果用户要开发自己的拦截器类,应该实现com.opensymphony.xwork2.interceptor.Interceptor接口,该接口的类定义代码如下:
public interface Interceptor extends Serializable{
//销毁拦截器前的回调方法
void destory();
//初始拦截器的回调方法
void init();
//拦截器实现拦截的逻辑方法
String intercept (ActionInvocation invocation) throws Exception;
}
Struts2还提供了一个AbstractInterceptor类(Interceptor的实现类),该类提供了一个init()和destroy()方法的空实现,如果实现的拦截器不需要打开资源,则可以无须实现这两个方法。继承此类只需重写一个方法,较方便。
@SuppressWarnings("serial")
public class SessionInterceptor extends AbstractInterceptor {
private static final Object LOGIN_KEY = "admin";
public static final String LOGIN_PAGE = "loginPage";
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
Map session = actionInvocation.getInvocationContext().getSession();
Admin admin = (Admin) session.get(LOGIN_KEY);
if (admin != null) {
//执行该拦截器的后一个拦截器
//如果该拦截器后没有其他拦截器,则执行Action的被拦截方法
return actionInvocation.invoke();
} else {
return LOGIN_PAGE;
}
}
}
使用自定义拦截器时需要在struts.xml中配置。
1.通过<interceptor.../>元素来定义拦截器。
2.通过<interceptor-ref.../>元素来使用拦截器。
<package name="default" extends="struts-default">
<interceptors>
<interceptor name="SessionInterceptor"
class="net.csdn.action.interceptors.SessionInterceptor" />
</interceptors>
<action name="myAction"
class="net.csdn.action.myAction">
<result name="input">/xx.jsp</result>
<result type="chain">xxx</result>
<interceptor-ref name="defaultStack" />
<interceptor-ref name="SessionInterceptor" />
</action>
</package>
注意:如果为Action指定了一个拦截器,则系统默认的拦截器将会失去作用。为了继续使用默认拦截器,所以上面配置文件中显示地应用了默认拦截器。
到此,简单的自定义拦截器完成了。