Struts2开发自定义拦截器

jopen 9年前

Interceptor接口

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;  }

可以看出接口中只有三个方法需要实现。

实现Interceptor接口

public class MyInterceptor implements Interceptor {      public void destroy() {          System.out.println("destroy()----");      }      public void init() {          System.out.println("init()----");      }      public String intercept(ActionInvocation invocation) throws Exception {          System.out.println("在Action执行之前");          String result = invocation.invoke();          System.out.println("在Result执行之后");          return result;      }  }

我们需要在struts.xml文件中进行配置:

<package name="helloworld" extends="struts-default">          <interceptors>              <interceptor name="MyInterceptor" class="com.lc.action.MyInterceptor" />          </interceptors>          <action name="loginAction" class="com.lc.action.LoginAction">              <param name="account">test</param>              <result>/welcome.jsp</result>              <interceptor-ref name="MyInterceptor" />              <interceptor-ref name="defaultStack" />          </action>      </package>

首先声明一个自定义的拦截器:

<interceptors>              <interceptor name="MyInterceptor" class="com.lc.action.MyInterceptor" />          </interceptors>

然后在action中引用:

<interceptor-ref name="MyInterceptor" />

执行的结果可想而知:

在Action执行之前  account=test,password=test,submitFlag=login  在Result执行之后