springboot注册拦截器后swagger冲突无法访问

springboot注册拦截器后swagger冲突无法访问:

由于拦截器会把所有请求都拦截下来,而swagger文档的页面资源和接口也会被拦截,因此再注册拦截器时需要将其排除.


springboot版本和swagger依赖:

            <!--swagger-->
            <dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>knife4j-spring-boot-starter</artifactId>
                <version>2.0.9</version>
            </dependency>
            
           <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>2.2.4.RELEASE</version>
              <relativePath/> 
           </parent>

自定义拦截器

@Configuration
public class LoginHandler implements HandlerInterceptor {

    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws AuthException { 
    // 省略了用户识别过程  可以是token或者密码校验   
            if (user != null) {
                UserThreadLocal.setUser(user);
                return true;
            }
        throw new AuthException("用户身份信息异常");
    }
}

拦截器注册

@Configuration
public class HandlerConfig extends WebMvcConfigurationSupport {
    @Autowired // 自定义的拦截器
    private LoginHandler loginHandler;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //拦截路径可自行配置多个 可用 ,分隔开
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(loginHandler);
        interceptorRegistration.addPathPatterns("/**"); // 需要拦截的路径
        interceptorRegistration.excludePathPatterns(    // 不拦截的路径
                // 放行swagger相关的路径
                "/swagger-ui/**",
                "/swagger-resources/**",
                "/v3/api-docs"
        );
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置拦截器访问静态资源
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

启动后swagger和拦截器冲突问题即可解决,自测成功,欢迎讨论

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值