swagger+springboot打开swagger-ui.html出现base url错误,页面空白,404等问题

首先别忘记导入两个jar包:

        
            io.springfox
            springfox-swagger2
            2.9.2
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        

别忘了加注解:

@EnableSwagger2

 

404问题,页面空白

原因:Springboot找不到swagger-ui.html这个路径,加载不带swagger-ui的静态资源

解决方法:

看下swagger-ui jar包的resource资源,就知道应该设置springboot找到这个路径,增加一个@configuration配置类,加载资源:


@Configuration
@EnableWebMvc
@EnableSwagger2
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        WebMvcConfigurer.super.addResourceHandlers(registry);
    }



    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

}

在使用filter、spring security、shiro等可以拦截url的框架是出现base url错误,页面空白:

原因:没有权限

解决:开发有关swagger资源的访问权限,以filter为例


@Component
@Slf4j
public class JwtFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain filterChain) throws ServletException, IOException {
       
        if(httpRequest.getRequestURI().equals("/swagger-ui.html")){
                filterChain.doFilter(httpRequest,httpResponse);
        }
        if(httpRequest.getRequestURI().contains("swagger")){
            filterChain.doFilter(httpRequest,httpResponse);
        }
        if(httpRequest.getRequestURI().equals("/v2/api-docs")){
            filterChain.doFilter(httpRequest,httpResponse);
        }
        if(httpRequest.getRequestURI().startsWith("/webjars")){
            filterChain.doFilter(httpRequest,httpResponse);
        }

        ...其他逻辑...

}

 

 

 

 

你可能感兴趣的:(SpringBoot,Swagger,Java)