首先访问swagger-ui需要放行对应的路由,比如"/swagger-ui.html/**","/swagger-resources/**","webjar/**","/v2/**","doc.html","/error"等等。如
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(getAuthInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**","doc.html","/error");
super.addInterceptors(registry);
}
还有对应的swagger需要的资源,使用addResourceHandlers(),如
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html","doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
其中遇到的问题,在webmvcConfig配置类里需要注入拦截器,不然可能会加载拦截器失败
@Bean
public MyInterceptor getMyInterceptor() {
return new MyInterceptor();
}
还有是在放行规则中加入/error的路由,防止访问到404的页面报了跳转/error也会拦截,一般报错了拦截了不能拦截的url,最好断点观察,preHandle方法中,然后查看request.requestDispatcerPath的值就知道了。