【问题标题】:Disable execution of an Interceptor禁用拦截器的执行
【发布时间】:2015-06-24 04:03:45
【问题描述】:

我正在研究 Struts 2。在实施 Interceptor 的过程中,我遇到了一个问题:

是否可以通过配置或任何其他方式一起停止拦截器的执行?

【问题讨论】:

  • 停止执行是什么意思?您还可以展示您尝试过的代码吗?

标签: java struts2 struts2-interceptors interceptorstack


【解决方案1】:

有很多方法可以决定 Struts2 Action 何时必须通过 Interceptor... 最简单的是最有可能的:

  1. 以编程方式 - Interceptor Configuration

    多次定义相同的动作,每一个都使用不同的拦截器堆栈运行(两者都在包级别全局定义,或者像下面的示例一样,在动作配置本身中定义),一个包含您的拦截器,另一个不包含它:

    <action name="actionWithInterceptor" class="foo.bar.actions.MyAction">
        <interceptor-ref name="myCustomInterceptor" />
        <interceptor-ref name="defaultStack" />
        <result>/view.jsp</result>
    </action>
    
    <action name="actionWithoutInterceptor" class="foo.bar.actions.MyAction">
     <!--   <interceptor-ref name="myCustomInterceptor" /> -->
        <interceptor-ref name="defaultStack" />
        <result>/view.jsp</result>
    </action>
    
  2. 以编程方式 - Method Filtering

    MethodFilterInterceptor 是一个抽象的 Interceptor,用作拦截器的基类,它将根据指定的包含/排除方法列表根据方法名称过滤执行。

    可设置的参数如下:

    • excludeMethods - 从拦截器处理中排除的方法名称
    • includeMethods - 要包含在拦截器处理中的方法名称

    在您的自定义拦截器中扩展此抽象拦截器,并在配置中定义将过滤拦截器执行的方法。在示例中,每个名为 foo()bar() 或以 withoutCustom 开头的操作方法(如 withoutCustomMethod())都会避免运行拦截器,所有其他方法都会运行它:

    <interceptor-stack name="myCustomStack">
    
        <interceptor-ref name="myCustomInterceptor">
            <param name="excludeMethods">foo,bar,withoutCustom*</param>
        </interceptor-ref>
    
        <interceptor-ref name="exception"/>
        <interceptor-ref name="alias"/>
        <interceptor-ref name="params"/>
        <interceptor-ref name="servletConfig"/>
        <interceptor-ref name="prepare"/>
        <interceptor-ref name="i18n"/>
        <interceptor-ref name="chain"/>
        <interceptor-ref name="modelDriven"/>
        <interceptor-ref name="fileUpload"/>
        <interceptor-ref name="staticParams"/>
        <interceptor-ref name="params"/>
        <interceptor-ref name="conversionError"/>
        <interceptor-ref name="validation">
            <param name="excludeMethods">myValidationExcudeMethod</param>
        </interceptor-ref>
        <interceptor-ref name="workflow">
            <param name="excludeMethods">myWorkflowExcludeMethod</param>
        </interceptor-ref>
    </interceptor-stack>
    
  3. 动态 - From within the Interceptor

    在拦截器逻辑中做,基于

    • 一个请求参数:

      if (request.get(MY_REQUEST_PARAM)!=null && 
          ((String) request.get(MY_REQUEST_PARAM)[0]).equals("myVal")) { ...
      
    • 一个会话参数:

      if (session.get(MY_SESSION_PARAM)!=null && 
          session.get(MY_SESSION_PARAM).equals("myVal")) { ...
      
    • 一个由你的 Action 扩展的接口:

      if(action instanceof MyStuffAware) { ...
      

等等……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多