【问题标题】:How to avoid having static resource request get's routed to interceptors?如何避免将静态资源请求路由到拦截器?
【发布时间】:2015-07-02 04:07:42
【问题描述】:

我正在使用最新的 Spring (4.1.1) 和 tomcat 7.0.52 。我已启用注释驱动的 mvc。

在我的应用程序中,我定义了一个拦截器:

<mvc:interceptors>
    <bean class="com.abc.UserAgentChangeInterceptor"/>
</mvc:interceptors>

此外,我还定义了资源:

<mvc:resources mapping="/static/**/*" location="/desktop"/>
<mvc:resources mapping="/**/*.css" location="/"/>
<mvc:resources mapping="/**/*.js" location="/"/>
<mvc:resources mapping="/**/*.gif" location="/"/>
<mvc:resources mapping="/**/*.htm" location="/"/>
<mvc:resources mapping="/**/*.svg" location="/"/>
<mvc:resources mapping="/**/*.png" location="/"/>

但是,当请求进来时,即使是静态资源/资产,它们仍然会首先被路由到拦截器。

我知道以下可以解决问题的做法:

  1. mvc:interceptor里面使用mvc:exclude-mapping来排除上述url上的请求被路由到我的拦截器,但这似乎违反了DRY原则,我真的不喜欢这种外观和感觉。

  2. 在拦截器上使用mvc:mapping。但是,我在这么多处理程序上使用注释驱动 @RequestMapping,并且有这么多不同的路径。该解决方案对我也不起作用。

我也遇到了一些意见,说使用 @ControllerAdvice 而不是拦截器可以帮助缓解这个问题,但根据我通过阅读 Spring 文档了解到的情况,@ControllerAdvice 没有任何类似于 preHandle() 的方法在@Controllers 之前执行

我仍然更喜欢使用 Spring XML 配置方法来解决这个问题,而不是在我的应用程序中定义 @Configuration 类。只是一个约定俗成的事情。

非常感谢任何意见!

【问题讨论】:

    标签: java spring spring-mvc model-view-controller


    【解决方案1】:

    方法一:在拦截器配置中使用映射路径

    <mvc:interceptors>
        <mvc:interceptor>
          <mvc:mapping path="/path" />
              <bean
                 class="bean" />
         </mvc:interceptor>
    </mvc:interceptors>
    

    方法 2:与 mvc:resources 一起指定

    <mvc:annotation-driven/>
    

    【讨论】:

    • 我在处理程序上使用注释驱动的@RequestMapping 并且有很多路径。因此,我没有在拦截器中使用路径映射。感谢您的帮助。
    【解决方案2】:

    我发现的当前“解决方案”是使用方面。例如,如果我只想拦截对@Controller 中的@RequestMapping 方法的请求。我会做的

    @Aspect
    @Order(1)
    @Component
    public class UserAgentChangeAspect {
    
        @Pointcut("execution(public * *(..)) && @within(org.springframework.stereotype.Controller) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
        private void pointcut() {
        }
    
        @Before("pointcut()")
        public void preHandle()
                throws Exception {
            // logic
            }
        }
    
        @After("pointcut()")
        public void postHandle()
                throws Exception {
            // logic
        }
    }
    

    我会将此标记为已接受。如果有人有更好的想法,请发布,如果我认为合适,我会接受。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 2011-06-17
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多