struts.xml
<struts>
<package name="default" namespace="/" extends="struts-default">
<!-- 自定义拦截器组合 -->
<interceptors>
<!-- 自定义拦截器 -->
<interceptor name="my" class="com.tc.MyInterceptor"/>
<!-- 自定义拦截器栈 -->
<interceptor-stack name="myStack">
<interceptor-ref name="my"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 以下两种为默认情况下所依赖的拦截器,根据不同情况酌情选择 -->
<!-- 整个struts.xml都依赖于myStack拦截器栈 -->
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<!-- 整个struts.xml都依赖于my拦截器 -->
<!-- <default-interceptor-ref name="my"></default-interceptor-ref> -->
<action name="add" class="com.tc.HelloWorld" method="add">
<!-- 可添加action的自定义拦截器 -->
<interceptor-ref name="my"></interceptor-ref>
<!-- 亦可添加action的自定义拦截器栈 -->
<interceptor-ref name="myStack"></interceptor-ref>
<result>/HelloWorld.jsp</result>
</action>
</package>
</struts>
拦截器类
/**
* 自定义拦截器:
* 实现implements Interceptor
* 或者
* 继承extends AbstractInterceptor
* @author TC
*
*/
public class MyInterceptor extends AbstractInterceptor{
/**
* 拦截器销毁之前调用的方法
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("destroy");
}
/**
* 拦截器处理之前,调用init方法初始化
*/
@Override
public void init() {
// TODO Auto-generated method stub
System.out.println("init");
}
/**
* 拦截器处理方法
*/
@Override
public String intercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub
System.out.println("执行之前");
String result = invocation.invoke();
System.out.println("执行之后");
return result;
}
}