Springboot结合springdoc生成API文档还有/swagger-ui/index.html遇到的404问题

Springboot常用的Restful API文档是Swagger,Swagger提供了优秀的swagger-ui给了OpenApi组织,而最新的Springboot3新项目中可以使用Springdoc作为API生成文档,这样可以解决掉Swagger2版本、Springfox不再更新之后出现的一些问题。

Springdoc实际上页面也是使用了Swagger-ui,但是在Springboot中引入时,并不需要专门引入swagger组件。

以Springboot3.2.4为例,使用Swagger只需要引入下面的内容在pom包中

        <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
            <version>2.5.0</version>
        </dependency>

可以通过配置编写Config文件或者是编写application.yml进行初始化的配置,如下代码所示。

package com.xxxxxxxxx.config;

import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author stiller
 * @ClassName
 * @Date: 2024/4/2 14:21
 * @Description: Swagger 配置
 */

@Configuration
public class SwaggerConfig {
    @Bean
    public OpenAPI springShopOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("Doc for RESTful API")
                        .contact(new Contact())
                        .description("RESTful API")
                        .version("v0.0.8")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))
                .externalDocs(new ExternalDocumentation()
                        .description("外部文档")
                        .url("https://springshop.wiki.github.org/docs"));
    }
}

或者是yml文件(也可以配置Config中的内容)注意,在这里大多数能找到的配置都会配置path是 /swagger-ui/index.html,这样配置在当前版本中是不对的,会导致访问路径是/swagger-ui/swagger-ui/index.html ,还有就是老版本的Swagger并不是这个地址。

springdoc:
  api-docs:
    enabled: true # 开启OpenApi接口
    path: /v3/api-docs  # 自定义路径,默认为 "/v3/api-docs"
  swagger-ui:
    enabled: true # 开启swagger界面,依赖OpenApi,需要OpenApi同时开启
    # path: /swagger-ui/index.html # 自定义路径,默认为"/swagger-ui/index.html"

然后可以在

/swagger-ui/index.html 
/v3/api-docs

此时此刻所有的教程都会告诉你可以进行直接访问,但是我遇到了404的问题。api-docs可以正常访问JSON,但是/swagger-ui/index.html并不可以,显示404。

在多次查阅资料后,发现并不能直接解决掉这个问题,直到我继续写代码后,编写了一个拦截器Interceptor用来实现用户的登录检查,然后它就正常可以访问了。

什么时候仔细研究下这是为什么,在这里更新一下。

放上我写的一个简单的拦截器。

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserEntity userEntity = userService.getUserByToken(request.getHeader("token"));
        if (userEntity == null) {
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(RTDataFormat.format(401)));
            return false;
        }
        request.setAttribute("user", userEntity);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 在请求处理完毕之后调用
    }
}

实现的Configuration,这里还遇到了一个问题,我配置excludePathPatterns无效,然后我发现了是因为配置了yaml中的# path: /swagger-ui/index.html(上面红字的情况)

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;
    static final String[] EXCLUDE_PATHS = {};

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns(EXCLUDE_PATHS);
    }

}

添加了 `springdoc-openapi-starter-webflux-ui` 依赖后,我们可以通过访问 `/swagger-ui.html` 或者 `/swagger-ui/index.html` 的方式来查看 API 文档。这里的 `/swagger-ui.html` 或者 `/swagger-ui/index.html` 是 WebFlux 对应的 API 文档页面,如果是使用 Spring Boot 的 Servlet 版本,应该是访问 `/swagger-ui.html`。 此外,我们还需要在 Spring Boot 应用程序启动类上添加 `@EnableSwagger2WebFlux` 注解,启用 Swagger2WebFlux 的自动配置。 下面是一个示例: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.reactive.config.EnableWebFlux; import springfox.documentation.swagger2.annotations.EnableSwagger2WebFlux; @SpringBootApplication @EnableWebFlux @EnableSwagger2WebFlux public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example")) .paths(PathSelectors.any()) .build(); } } ``` 在上面的示例中,我们使用 `@EnableSwagger2WebFlux` 注解启用了 Swagger2WebFlux 的自动配置,并且定义了一个 `Docket` Bean,用于配置 Swagger2WebFlux 的行为。在 `Docket` 中,我们使用 `basePackage` 和 `any` 方法来指定扫描的 API 包和路径。 最后,我们可以使用浏览器访问 `http://localhost:8080/swagger-ui.html` 来查看生成API 文档
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值