【问题标题】:Spring interceptor works with xml but not with config classSpring拦截器适用于xml但不适用于配置类
【发布时间】:2013-04-18 11:35:42
【问题描述】:

我目前正在使用这样的 xml 配置拦截器:

<mvc:interceptors>
    <bean class="org.resthub.dashboard.BasicInterceptor" />
</mvc:interceptors>

但我想把它放在我的配置类中:

    @Configuration
    @ComponentScan("org.resthub.dashboard")
    @EnableWebMvc
    @EnableAspectJAutoProxy(proxyTargetClass=true)
    public class WebAppConfig extends WebMvcConfigurerAdapter{

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new BasicInterceptor());
        }

        @Bean
        public InternalResourceViewResolver setupViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/views/");
            resolver.setSuffix(".jsp");
            return resolver;
        }
    }

但它不起作用,我不知道为什么。拦截器永远不会被调用。

有什么想法吗?

谢谢

edit : 这里是 BasicInterceptor

    package org.resthub.dashboard;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

    public class BasicInterceptor extends HandlerInterceptorAdapter {

        @Override
        public void postHandle(HttpServletRequest request,
                HttpServletResponse response, Object handler,
                ModelAndView modelAndView) throws Exception {
            // TODO Auto-generated method stub
            super.postHandle(request, response, handler, modelAndView);

            System.out.println("INTERCEPTORORRR§§§§§§");
            if (modelAndView != null && modelAndView.getModelMap() != null) {
    ...
            }
        }

    }

【问题讨论】:

  • 你验证过你的配置类真的被使用了吗?
  • 是的,函数 addInterceptors 调用得很好。
  • BasicInterceptor 类中是否使用了@Intercept?
  • 你的BasicInterceptor是什么样的?
  • 不,我没有这个注释。我需要什么版本的 Spring MVC?我找不到它。

标签: java xml spring annotations interceptor


【解决方案1】:

您的配置似乎是正确的,至少如果您已验证它实际上已被拾取。但是,问题可能是在请求期间发生了一些事情,导致postHandle 不被执行。确保在请求执行期间没有抛出任何异常。为了验证拦截器是否真的被使用,你可以实现preHandleafterCompletion,看看这些方法是否被执行。

【讨论】:

  • 没有执行这些功能。很奇怪。
  • 在这种情况下,你确定你的控制器被调用了吗?您没有尝试访问 Spring MVC 未处理的资源?
  • 是的,我确定,因为它适用于拦截器的 xml 配置。
  • 好吧,我要回到xml配置
  • 您是否同时运行任何 xml-config 和 annotation 配置?
猜你喜欢
  • 2018-02-03
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 2013-11-07
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
相关资源
最近更新 更多