Spring Inteceptor配置无法正常工作

时间:2018-10-05 04:45:41

标签: spring spring-mvc spring-boot

我有用于Spring Boot应用程序的写拦截器。

配置类

@SpringBootApplication(scanBasePackages={"com.epic"})
public class ApiConfig extends SpringBootServletInitializer{

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ApiConfig.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(ApiConfig.class, args);
    }

    @Bean
    public WebMvcConfigurerAdapter adapter() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(getIbRestInterceptor()).addPathPatterns("/**");
            }
        };
    }

    @Bean
    public IbRestInterceptor getIbRestInterceptor() {
        return new IbRestInterceptor();
    }
}

拦截器类

public class IbRestInterceptor implements HandlerInterceptor {
    final static Logger logger = Logger.getLogger(IbRestInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        try{
            System.out.println("----pre handle----");
        }catch(Exception e){
            logger.error("Interceptor perHandle Exception : " , e);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        try{
            System.out.println("----post handle----");
        }catch(Exception e){
            logger.error("Interceptor postHandle Exception : " , e);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}
}

以上类的工作文件。

当我如下更改配置类addPathPatterns时,请求不会通过拦截器类。

示例-http://localhost:8080/IB_REST/test/

@Bean
    public WebMvcConfigurerAdapter adapter() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(getIbRestInterceptor()).addPathPatterns("/IB_REST/**");
            }
        };
    }

任何人都可以描述它发生的原因以及如何解决此问题,这将对您大有帮助。预先感谢。

0 个答案:

没有答案