springboot项目创建笔记24 之《添加拦截器后影响swagger访问》

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
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值