Swagger配置了拦截器被拦截

拦截器把swagger拦截了无法访问,

package com.qhzx.td.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @author locken
 * @date 2022-08-23 20:51
 * @Description: -TOOD
 */
@Component
public class WebConfig extends WebMvcConfigurationSupport {

    @Autowired
    private MyInterceptorConfig myInterceptorConfig;

    /**
     * 添加接口请求拦截器  排除用户接口不用验证
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptorConfig)
                .addPathPatterns("/**")
//                .excludePathPatterns("/user/login");
                .excludePathPatterns("/user/bindUser","/user/queryUserByAddr")
                .excludePathPatterns("/doc.html") //不需要拦截的地
                .excludePathPatterns("/swagger-resources/**")
                .excludePathPatterns("/webjars/**")
                .excludePathPatterns("/v2/**")
                .excludePathPatterns("/favicon.ico")
                .excludePathPatterns("/swagger-ui.html/**");
    }

    /*
     * @param registry
     * @return void
     * @introduction: 跨域支持
     * @date 2021/5/19 21:44
     */

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD")
                .maxAge(3600 * 24);
    }
    /**
     * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");

        registry.addResourceHandler("doc.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        super.addResourceHandlers(registry);
    }
}

Swagger2Config

package com.qhzx.td.config;

import io.swagger.annotations.Api;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
//                .enable(swaggerEnable)
                .apiInfo(apiInfo())
                .select()
//                .apis(RequestHandlerSelectors.basePackage(" com.qhzx.td.controller")) //指定扫描包
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
//                .paths(PathSelectors.any())
                //只显示api路径下的页面
                //.paths(Predicates.and(PathSelectors.regex("/api/.*")))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("客户记录API文档")
                .description("客户记录API文档")
                .version("1.0.0")
                .build();
    }
}

MyInterceptorConfig 拦截器

package com.qhzx.td.config;

import io.swagger.models.HttpMethod;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

/**
 * @author locken
 * @date 2022-08-23 20:38
 * @Description: -TOOD
 */
@Configuration
@Component
@Slf4j
public class MyInterceptorConfig implements HandlerInterceptor {
    /**
     * 添加接口请求拦截器
     * @param request
     * @param resp
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse resp, Object handler) throws Exception {
        //打印请求内容
        log.info("==============preHandle======start====================");
        log.info("IP   :" + request.getRemoteAddr());
        log.info("URL  :" + request.getRequestURL().toString());
        log.info("HTTP Method   :" + request.getMethod());
        log.info("===============preHandle======End=====================");

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            log.info("OPTIONS请求,放行");
            return true;
        }
        log.info("------------ MyInterceptorConfig...................");
        String token = request.getHeader("token");
        log.info("=============== MyInterceptorConfig token : {}", token);
        if (StringUtils.isBlank(token) ) {
            log.info("=============== 请求拦截 : {}", token);
            return false;
        }
        return true;
    }
}

ApiApplication 加入@MapperScan("com.qhzx.td.mapper")

package com.qhzx.td;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableScheduling
@EnableSwagger2
@Slf4j
@MapperScan("com.qhzx.td.mapper")
public class ApiApplication {
    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        SpringApplication.run(ApiApplication.class, args);
        log.info("启动成功,耗时: " + (System.currentTimeMillis() - time) / 1000 + "s");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值