1、添加了拦截器后,访问swagger页面http://localhost:8088/swagger-ui.html变成空白:
2、因为拦截器是拦截所有的请求
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册RateLimitInterceptor拦截器
// 要注意这里使用this.rateLimitInterceptor()
InterceptorRegistration registration = registry.addInterceptor(this.rateLimitInterceptor());
// 所有路径都被拦截
registration.addPathPatterns("/**");
WebMvcConfigurer.super.addInterceptors(registry);
}
3、修改WebMvcConfig.java添加排除swagger路径和资源
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 拦截器配置类
* @author User
*
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
//在此处,将拦截器注册为一个Bean,才能使用@Autowired注解注入对象
@Bean
public RateLimitInterceptor rateLimitInterceptor() {
return new RateLimitInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册RateLimitInterceptor拦截器
// 要注意这里使用this.rateLimitInterceptor()
InterceptorRegistration registration = registry.addInterceptor(this.rateLimitInterceptor());
// 所有路径都被拦截
registration.addPathPatterns("/**")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**","doc.html","/error");
WebMvcConfigurer.super.addInterceptors(registry);
}
@Override
public 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/");
}
}
参考资料:
https://blog.csdn.net/InSunshine_/article/details/108725474
https://blog.csdn.net/lsqingfeng/article/details/110480709
注:最新代码上传至https://github.com/csj50/myboot