Struts2 拦截器
拦截器(Interceptor)是 Struts 2 的核心组成部分。
Struts2 很多功能都是构建在拦截器基础之上的,例如文件的上传和下载、国际化、数据类型转换和数据校验等等。
Struts2 拦截器在访问某个 Action 方法之前或之后实施拦截
Struts2 拦截器是可插拔的, 拦截器是 AOP(面向切面编程) 的一种实现.
拦截器栈(Interceptor Stack): 将拦截器按一定的顺序联结成一条链. 在访问被拦截的方法时, Struts2 拦截器链中的拦截器就会按其之前定义的顺序被依次调用
Struts2 自带的拦截器
Interceptor 接口
每个拦截器都是实现了接口com.opensymphony.xwork2.interceptor.Interceptor的 Java 类:
public interface Interceptor extends Serializable { /** * Called to let an interceptor clean up any resources it has allocated. */ void destroy(); /** * Called after an interceptor is created, but before any requests are processed using * {@link #intercept(com.opensymphony.xwork2.ActionInvocation) intercept} , giving * the Interceptor a chance to initialize any needed resources. */ void init(); /** * Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the * request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code. * * @param invocation the action invocation * @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself. * @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}. */ String intercept(ActionInvocation invocation) throws Exception; }
init: 该方法将在拦截器被创建后立即被调用, 它在拦截器的生命周期内只被调用一次. 可以在该方法中对相关资源进行必要的初始化
interecept: 每拦截一个请求, 该方法就会被调用一次.
destroy: 该方法将在拦截器被销毁之前被调用, 它在拦截器的生命周期内也只被调用一次.
Struts 会依次调用为某个 Action 而注册的每一个拦截器的 interecept 方法.
每次调用 interecept 方法时, Struts 会传递一个 ActionInvocation 接口的实例.
ActionInvocation: 代表一个给定 Action 的执行状态, 拦截器可以从该类的对象里获得与该 Action 相关联的 Action 对象和 Result 对象. 在完成拦截器自己的任务之后, 拦截器将调用 ActionInvocation 对象的 invoke 方法前进到 Action 处理流程的下一个环节.
AbstractInterceptor 类实现了 Interceptor 接口. 并为 init, destroy 提供了一个空白的实现
自定义拦截器
定义自定义拦截器的步骤
自定义拦截器
在 struts.xml 文件中配置自定义的拦截器
小结
4. 自定义拦截器
1). 具体步骤
I. 定义一个拦截器的类
> 可以实现 Interceptor 接口
> 继承 AbstractInterceptor 抽象类
II. 在 struts.xml 文件配置.
<interceptors>
<interceptor name="hello" class="com.atguigu.struts2.interceptors.MyInterceptor"></interceptor>
</interceptors>
<action name="testToken" class="com.atguigu.struts2.token.app.TokenAction">
<interceptor-ref name="hello"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>/success.jsp</result>
<result name="invalid.token">/token-error.jsp</result>
</action>
III. 注意: 在自定义的拦截器中可以选择不调用 ActionInvocation 的 invoke() 方法. 那么后续的拦截器和 Action 方法将不会被调用.
Struts 会渲染自定义拦截器 intercept 方法返回值对应的 result