Struts2拦截器
拦截器是动态拦截Action调用的对象,类似于Servlet的过滤器
在Action执行execute()方法之前,struts2会首先执行struts.xml中引用的拦截器,对action执行前后处理一些相应的操作
自定义拦截器
继承
AbstractInterceptor
api方法
void init();初始化操作,创建一些对象
String intercept(..)throws exceotion;主要操作,请求处理,
void destroy();生命周期结束,可以释放一些资源
只有调用intercept()方法中invoke()方法,才可以执行Action对象中的请求处理方法
配置拦截器
在struts.xml中struts--》package下编写
<interceptors>
<interceptor name="拦截器名称" class="拦截器类">
<param name="参数名">参数值</param>
</interceptor>
</interceptors>
拦截器栈,多个拦截器栈放在一起
<interceptors>
<interceptor name="拦截器名称1" class="拦截器类">
<param name="参数名">参数值</param>
</interceptor>
<interceptor name="拦截器名称2" class="拦截器类">
<param name="参数名">参数值</param>
</interceptor>
<interceptor-stack name="拦截器栈1">
<interceptor-ref name="拦截器名称1"></interceptor-ref>
<interceptor-ref name="拦截器名称2"></interceptor-ref>
</interceptor-stack>
<interceptor-stack name="拦截器栈2">
<interceptor-ref name="拦截器名称"></interceptor-ref>
<interceptor-ref name="拦截器栈1"></interceptor-ref>
</interceptor-stack>
</interceptors>
栗子:
<interceptors>
<interceptor name="hexie" class="com.kj.filter.MyInterceptor"></interceptor>
<interceptor-stack name="my_Stack">
<!-- struts2 提供的拦截器栈,包含了struts2的很多核心拦截器,必须添加,不然获取不到参数 -->
<interceptor-ref name="defaultStack" />
<!-- 定义文字过滤-->
<interceptor-ref name="hexie"></interceptor-ref>
</interceptor-stack>
</interceptors>
注意自定义拦截器必须要配置一个系统拦截器
<!-- struts2 提供的拦截器栈,包含了struts2的很多核心拦截器,必须添加,不然获取不到参数 -->
<interceptor-ref name="defaultStack" />
案例:https://blog.youkuaiyun.com/qq_37143903/article/details/106871617