1

我正在研究 Struts 2。在实施拦截器期间,我遇到了一个问题:

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

4

1 回答 1

3

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

  1. 以编程方式 -拦截器配置

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

    <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. 以编程方式-方法过滤

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

    可设置的参数如下:

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

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

    <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. 动态 -从拦截器内部

    在拦截器逻辑中执行它,基于

    • 请求参数:

      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")) { ...
      
    • 由您的操作扩展的接口:

      if(action instanceof MyStuffAware) { ...
      

等等...

于 2015-06-25T08:42:50.060 回答