首页 > 代码库 > Struts(二十八):自定义拦截器

Struts(二十八):自定义拦截器

  • Struts2拦截器
  1. 拦截器(Interceptor)是Struts2的核心部分。
  2. Struts2很多功能都是构建在拦截器基础之上,比如:文件上传、国际化、数据类型转化、数据校验等。
  3. Struts2拦截器是在访问某个Action方法之前和之后实施拦截的。
  4. Struts2拦截器是可插拔的,拦截器是AOP(面向切面编程)的一种实现。
  5. 拦截器栈(Interceptor Stack):将拦截器按一定的顺序联合在一条链,在访问被拦截的方法时,Struts2拦截器栈中的拦截器就会按照之前定义的顺序被调用。
  • Interceptor接口

每个拦截器都必须实现com.opensymphony.xwork2.interceptor.Interceptor接口

package com.opensymphony.xwork2.interceptor;import com.opensymphony.xwork2.ActionInvocation;import java.io.Serializable;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;}
  1. Struts2会依次调用为某个Action而注册的每个拦截器的intercept方法
  2. 每次调用intercept方法时,Struts2会传递一个ActionInvocation接口的实例。
  3. ActionInvocation:代表一个给定Action的执行状态,拦截器可以从该类的对象里获的与该Action相关的Action对象和Result对象。在完成拦截器自己的任务之后,拦截器调用ActionInvocation对象的invoke方法前进到Action处理流程的下一个环节。
  4. AbstractInterceptor类实现了Interceptor接口,并为init,destory提供了空白的实现。

 

  • 用法示例:

 

Struts(二十八):自定义拦截器