读书笔记:Struts2拦截器
1、拦截器相关基础类
Interceptor接口
--> AbstractInterceptor抽象类
--> MethodFilterInterceptor抽象类(支持方法过滤)
2、配置拦截器
<interceptor name="拦截器名" class="拦截器实现类">
3、使用拦截器
<interceptors>
<interceptor name="mySimple" class="com.cjm.SimpleInterceptor"/>
</interceptors>
<action name="login" class="com.cjm.LoginAction">
<result name="success">main.jsp</result>
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="mySimple"/>
</action>
注意:一旦我们为Action显式指定了某个拦截器,则默认的拦截器就不再起作用,如果该Action需要使用默认拦截器,则必须手动配置该拦截器的引用。
4、实现拦截器类
public class SimpleInterceptor extends AbstractInterceptor{
public String intercept(ActionInvocation invocation)throws Exception{
//取得被拦截的Action实例
LoginAction action = (LoginAction) invocation.getAction();
//将控制权转给下一个拦截器,或者转给Action的execute方法
String result = invocation.invoke();
//返回逻辑视图名
return result;
}
}
5、带方法过滤特性的拦截器类
public class MyFilterInterceptor extends MethodFilterInterceptor{
private String name;
public void setName(String name){
this.name = name;
}
public String doIntercept(ActionInvocation invocation)throws Exception{
LoginAction action = (LoginAction) invocation.getAction();
String result = invocation.invoke();
return result;
}
}
<interceptors> <interceptor name="myFilter" class="com.cjm.MyFilterInterceptor"/> </interceptors> <action name="login" class="com.cjm.LoginAction"> <result name="success">main.jsp</result> <interceptor-ref name="defaultStack"/> <interceptor-ref name="myFilter"> <param name="name">属性值</param> <param name="excludeMethods">execute,view,edit</param> <param name="includeMethods">add,list</param> </interceptor-ref> </action>
注意:如果excludeMethods参数和includeMethods参数同时指定了一个方法名,则拦截器会拦截该方法。
6、覆盖拦截器中特定拦截器的参数
语法: <拦截器名>.<参数名>
<interceptor-ref name="myFilter"> <param name="mySimple.name">新属性值</param> </interceptor-ref>
7、拦截器中设置的参数在Action类中读取
在拦截器类中设置参数值:
valueStack.getContext().put("httpHelper", "参数值");
在Action类中读取该参数值:
ActionContext.getContext().getValueStack().findValue("httpHelper")
8、拦截结果的监听器
实现拦截结果的监听器必须实现PreResultListener接口,该监听器是通过手动注册在拦截器内部的。
invocation.addPreResultListener(new MyPreResultListener());
不要在PreResultListener监听器的beforeResult方法中通过ActionInvocation参数调用invoke方法。