struts2拦截器

来源:互联网 发布:java生成嵌套json数据 编辑:程序博客网 时间:2024/05/30 07:12

拦截器定义

<interceptors>

< interceptor name="拦截器名" class ="拦截器实现类"/>

<params name="参数名" >参数值</params>

</interceptor>

。。。。

</interceptors>

拦截器栈和拦截器功能是完全统一的。


使用拦截器指定参数有两个时机:1.定义拦截器时 ,通过<inerceptor.../> 

 2.使用拦截器时  ,通过<interceptor-ref.../>  

配置默认拦截器使用<default-interceptor-ref name="拦截器名或拦截器栈名">(也可指定参数),该元素作为<package .../>子元素使用。每个包只能指定一个默认的拦截器。

  一旦为某个包指定了默认的拦截器,如果该包中的Action没有显示的指定拦截器,则默认的拦截器将会起作用。但值得注意的是,如果我们一旦为该包中的action显示的应用了某个拦截器,则默认的拦截器将不再起作用;若果需要使用该默认 的拦截器,则必须手动配置该拦截器 的引用。


    实现拦截器类:

如果用户要开发自己的拦截器类,应该实现com.opensymphony.xwork.interceptor.Interceptor接口。有以下三个方法。

   init();

  destroy();

    intercept(ActionInvocation invocation):----用户需要实现的拦截动作,就像Action的execute一样,该方法会返回一个字符串作为逻辑视图。如果该方法直接返回了一个字符串,系统将会跳转到该逻辑视图对应的实际视图资源 ,不会调用被拦截 的Action。该方法的invocation参数包含了被拦截的Action 的引用,可以调用该参数的invoke()方法,将控制权交给下一个,若该拦截之后没有其他拦截器,则直接执行Action的execute方法。


  使用拦截器:

1.通过<interceptor.../>元素定义拦截器。

2.通过<interceptor-ref.../>元素来使用拦截器

  上面讲的拦截器都是拦截Action中的所有方法,又是我们只想拦截指定的方法,为了实现方法的过滤性,struts2提供了MethodFilterInterceptor类。该类重写了intercet方法,提供了一个doIntercept(ActionInvocation invocation)抽象方法。在MethodFilterInterceptor中额外增加了如下两个方法:

           1.public void setExcludeMethods(String excludeMethods):排除需要过滤的方法,所有在excludeMethods字符串中列出的方法都不会被拦截。

   2.public void setIncludeMethods(String includeMethods):设置要过滤的方法。

可以再配置文件中指定要被拦截,或者不拦截的方法。

//定义省去了,下面是使用

    <interceptor-ref name="mysimple">

           <param name="name">重新指定name属性的值</param>

    <param name="excludeMethods">execute,haha</param> //指定execute方法与haha方法不需被拦截。

  </interceptor-ref>

                    如果一个方法既在黑名单又在白名单,则该方法会被拦截。


拦截器执行顺序:

      在Action的控制方法执行前,位于拦截器链前面的拦截器将先发生作用;在Action的控制方法执行之后,位于拦截器链后面的先发生作用。


拦截结果监听器PreResultListener

public class MyPreResultListener implements PreResultListener{//定义在处理Result之前的行为public void beforeResult(ActionInvocation invocation,String resultCode){//打印出执行结果System.out.println("返回的逻辑视图为:" + resultCode);}}

public class BeforeResultInterceptorextends AbstractInterceptor{public String intercept(ActionInvocation invocation)throws Exception{//将一个拦截结果的监听器注册给该拦截器invocation.addPreResultListener(new MyPreResultListener()); System.out.println("execute方法执行之前的拦截...");//调用下一个拦截器,或者Action的执行方法String result = invocation.invoke();System.out.println("execute方法执行之后的拦截...");return result;}}


beforeResult 在Action的execute()方法之后执行,但在进入视图资源之前执行。注意,不要在PreResultListener监听器的beforeResult方法中通过ActionInvocation参数调用invoke()方法,因为在beforeResult方法之前,Action 的execute方法已经执行结束了。如果再次调用invoke()方法将会再次执行Action处理,处理后紧跟着的是beforeResult方法。。。。这会陷入一个死循环。


 execute方法执行之前的拦截 --》进入execute方法执行体   ---》返回逻辑视图为 success--->execute方法执行之后的拦截



    




2 0
原创粉丝点击