簡體   English   中英

Springboot swagger url 顯示 WhiteLabel 錯誤頁面

[英]Springboot swagger url shows WhiteLabel Error page

這是我的代碼:我從 application.properties 文件 SwaggerConfig.java 中獲取所有值

@Configuration
@EnableSwagger2
@Profile("!prod")
@PropertySource(value = { "classpath:application.properties" })
public class SwaggerConfig {

    @Value("${swagger.api.title}")
    private String title;

    @Value("${swagger.api.description}")
    private String description;

    @Value("${swagger.api.termsOfServiceUrl}")
    private String termsOfServiceUrl;

    @Value("${swagger.api.version}")
    private String version;

    @Value("${swagger.api.controller.basepackage}")
    private String basePackage;


    @Bean
    public Docket postMatchApi() {
        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.ant("/**")).build().apiInfo(metaData());
    }

    private ApiInfo metaData() {
        return new ApiInfoBuilder().title(title).description(description).termsOfServiceUrl(termsOfServiceUrl)
                .version(version).build();
    }

這是我的springboot初始化程序:

@SpringBootApplication
@ComponentScan(basePackages = { "com.example.demo" })
@ComponentScan(basePackageClasses = {AppInitializer.class, SwaggerConfig.class})
@EnableAsync
@EnableRetry
public class AppInitializer{

    public static void main(String[] args) {
        SpringApplication.run(AppInitializer.class, args);
    }
}

ServletInitializer.java

public class ServletInitializer extends SpringBootServletInitializer implements WebApplicationInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(PostMatchAppInitializer.class);
    }
}

日志說它已映射:

[INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[],methods=[POST],consumes=[application/json],produces=[application/json]}" onto public <T> org.springframework.http.ResponseEntity<?> com.,org.springframework.validation.BindingResult) throws java.lang.Exception
    [INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/v2/api-docs],methods=[GET],produces=[application/json || application/hal+json]}" onto public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)
    [INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/swagger-resources/configuration/ui]}" onto org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.UiConfiguration> springfox.documentation.swagger.web.ApiResourceController.uiConfiguration()
    [INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/swagger-resources]}" onto org.springframework.http.ResponseEntity<java.util.List<springfox.documentation.swagger.web.SwaggerResource>> springfox.documentation.swagger.web.ApiResourceController.swaggerResources()
    [INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/swagger-resources/configuration/security]}" onto org.springframework.http.ResponseEntity<springfox.documentation.swagger.web.SecurityConfiguration> springfox.documentation.swagger.web.ApiResourceController.securityConfiguration()
    [INFO ] 2018-01-17 16:46:37.055 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
    [INFO ] 2018-01-17 16:46:37.071 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
    [INFO ] 2018-01-17 16:46:37.227 [restartedMain] o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5e89f6: startup date [Wed Jan 17 16:46:34 CST 2018]; root of context hierarchy

這是我得到的錯誤:

    [WARN ] 2018-01-17 16:46:42.217 [http-nio-8082-exec-1] o.s.w.s.PageNotFound - No mapping found for HTTP request with URI [/example/swagger-ui.html] in DispatcherServlet with name 'dispatcherServlet'

對於新的 Springfox 版本(3.0.0),您需要做一些不同的事情

在 pom.xml 添加以下依賴

*

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

而不是<artifactId>springfox-swagger2</artifactId><artifactId>springfox-swagger-ui</artifactId>的兩個

並訪問 ../swagger-ui/ 而不是 ../swagger-ui.html

我發現問題出在哪里,在其中一個配置文件中我不知何故有 @EnableMvc 注釋,因此 dispatcherservlet 正在尋找映射 /example/swagger-ui.html 並且由於它找不到一個它抱怨“沒有映射成立”。

刪除 @EnableMvc 后,它工作得很好。

對於像我這樣仍然收到“Whitelabel”頁面錯誤的其他人,請檢查您是否有:

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.8.0</version>
</dependency>

在您的pom.xml文件中,不僅需要官方文檔頁面顯示的“springfox-swagger2”依賴項,還需要“springfox-swagger-ui”。

我遇到了同樣的問題。 所以基本上如果你使用 spring 3 或更多然后打開 swagger 頁面,你只需要做 3 件事。

  1. 在 pom.xml 中添加 3 個依賴項

    <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2 </artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>3.0.0</version> </dependency>
  2. 創建一個配置文件。

     import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2); }

    }

  3. 打開此鏈接以訪問 API。

http://localhost:8080/swagger-ui/

現在只需匹配您錯過的步驟。 一定要問你是否卡在某個地方。

我英語不好,這就是谷歌翻譯的原因。

那個版本和做的方式已經有點過時了,如果你想自動生成文檔,SpringDoc 簡化了 API 文檔的生成和維護,基於 OpenAPI 3 規范,適用於 Spring Boot 1.x 和 2.x . 應用程序。

為了讓魔術發生,我們只需將依賴項添加到我們的 pom 中:



    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.2.32</version>
    </dependency>

然后訪問已經有它的描述http://localhost:8080/v3/api-docs/

對於招搖: http://localhost:8080/swagger-ui.html

這里的所有都是它的。

了解更多詳情

如果要自定義 api 信息,可以包含 java 樣式注釋:



    @OpenAPIDefinition(
        info = @Info(
                 title = "API personas", 
                 description = "Este es un ejemplo de servidor Personas-Server."
            + "Usted puyede encontrar mas acerca de Swagger " ++"[http://swagger.io](http://swagger.io) o en "
            + "[irc.freenode.net, #swagger](http://swagger.io/irc/).",
            termsOfService = "http://swagger.io/terms/", 
              license = @License(
                          name = "Apache 2.0", 
                          url = "http://springdoc.org"), 
       version = "otra"
    ))
    @Tag(name = "persona", description = "API para personas")
    @RestController
    @RequestMapping("persona")
    public class PersonaRest extends GeneralRest {}

也可以為特殊方法生成:



     @Operation(
         summary = "traer todas las personas", 
         description = "api para traer todas las personas, aqui no se tienen en cuenta paginaciones, ni filtros, trae todos los registros", 
         tags = { "persona" }
         )
     @ApiResponses(
         value = {
         @ApiResponse(
             responseCode = "200", 
             description = "Operación exitosa", 
             content = @Content(
                 mediaType = "application/json", 
                 array = @ArraySchema(
                     schema = @Schema(
                         implementation = PersonaTO.class
                         )))),
         @ApiResponse(
             responseCode = "401", 
             description = "Sin autorización", 
             content = @Content(
                 mediaType = "application/json", 
                 schema = @Schema(
                     implementation = Object.class
                     ))),
     })
     @GetMapping
     public List personas() {
            return personaServicio.obtenerTodo();
        }

使用最新的庫和包含始終是一種好習慣。

對我來說,它是大搖大擺的依賴版本。

問題

spring boot - 2.3.4
java - 8
swagger - 3.0.0 

沒有問題

spring boot - 2.3.4    
java - 8    
swagger - 2.9.2 

將 swagger 配置移動到您的SpringBootApplication類。 這將解決可白頁錯誤。

如果您在添加適當的依賴項后仍面臨問題,請按照以下步驟操作

1.轉到 C:\Users\User.m2
2.刪除存儲庫文件夾(完成文件夾刪除即Shift+Delete按鈕窗口)

這個文件夾基本上包含你的項目需要的所有 jars 所以當你再次打開你的項目時,它會自動下載依賴項

首先,在spring boot pom文件中添加以下依賴項,然后在應用程序類上添加@EnableSwagger注解,然后添加webappconfig類

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.1</version>
    </dependency>


    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.1</version>
    </dependency>

@Configuration
@EnableWebMvc
public class ApplicationWebMvcConfig implements WebMvcConfigurer {.   
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

}。

對於 SpringBoot Ver:2.4.0-M4,我推薦以下設置。 確保您使用 SpringFox 版本:3.0.0

//build.gradle file

def springFoxVer = '3.0.0'
def log4jVer = '2.13.3'

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-data-rest'
    implementation 'org.springframework.boot:spring-boot-starter-hateoas'
    implementation 'org.springframework.boot:spring-boot-starter-validation'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.data:spring-data-rest-hal-explorer'
    implementation "io.springfox:springfox-swagger2:$springFoxVer"
    implementation "io.springfox:springfox-boot-starter:$springFoxVer"
    implementation "io.springfox:springfox-swagger-ui:$springFoxVer"
    implementation "io.springfox:springfox-data-rest:$springFoxVer"
    implementation "org.apache.logging.log4j:log4j-core:$log4jVer"
    implementation "org.apache.logging.log4j:log4j-api:$log4jVer"
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'com.h2database:h2'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

在配置類中:

@Configuration
public class SwaggerDocumentationConfig {

    ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Sample Indentity in Project")
                .description("The identity API provides standardized mechanism for identity management such as creation, update, retrieval, deletion. Party can be an individual or an organization that has any kind of relation with the enterprise.   ### Resources - Individual  Party API performs the following operations : - Retrieve an individual - Retrieve a collection of individuals according to given criteria - Create a new individual - Update an existing individual - Delete an existing individual")
                .license("")
                .licenseUrl("http://unlicense.org")
                .termsOfServiceUrl("")
                .version("1.0.0")
                .contact(new Contact("Sean Huni", "https://sean-huni.xyz", "sean2kay@gmail.com"))
                .build();
    }

    @Bean
    public Docket customImplementation() {
        return new Docket(DocumentationType.SWAGGER_2)
                .tags(new Tag("Person Entity", "Repository for People's entities"))
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

}

在 application-runner/executor 類中:

@SpringBootApplication
@EnableSwagger2
@EnableJpaRepositories
@Import(SpringDataRestConfiguration.class)
public class SpringSwaggerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSwaggerApplication.class, args);
    }

}

按照這里的指示 大多數情況下,只需花時間閱讀要求和設置過程就意味着可以為自己節省一天的時間。

就我而言,我從 swagger 2.7.0 升級到 3.0.0,這些是到達蜜罐的步驟:

  • 添加一個依賴
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>${swagger.version}</version>
    </dependency>
  • 刪除兩個依賴項(但它們不會有害,如果您忘記了這一步)
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${swagger.version}</version>
    </dependency>
    <dependency>  
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${swagger.version}</version>
    </dependency>
  • Server-Class 現在看起來像這樣(與 swagger v2.7.0 相比沒有變化)
@SpringBootApplication(scanBasePackages = {"com.acme.product.server"})
@RestController
@EnableScheduling
@EnableSwagger2
public class AcmeProductServer {
    // [...]

    // --- swagger integration
    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.acme.product.server"))
            .build();
    }
}

  • 然后我真的不得不在'C:\ Users \ Zaphod.m2 \ repository'刪除並刷新我的本地maven存儲庫

  • 最后一個問題是使用不同的 URL:http://localhost:8080/iam/swagger-ui/(最后沒有斜杠或“/index.html”,它不起作用)

確保以下內容與版本一起:

  1. 添加了依賴項

     <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
  2. @Bean Dokcet 在 @SpringBootApplication 類中定義

  3. swagger ui 端點http://localhost:<port-number>/swagger-ui

PS:在spring boot(v2.5.0)中測試

為了在我們的項目中包含 Swagger,讓我們將以下注釋添加到我們的應用程序 void 方法中。

@SpringBootApplication
@EnableSwagger2
public class PostApplication {

   public static void main(String[] args) {
      SpringApplication.run(PostApplication.class, args);
   }

}

簡單地安裝 Spring Fox 啟動啟動器並從您的項目中刪除 springfox-swagger-ui 和 springfox-swagger2

Gradle:- 
implementation group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0'

Maven:- 
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

此外,使用以下配置創建一個名為 SwaggerCondig.java 的文件

@Configuration
@EnableSwagger2
public class SwaggerConfig {
  @Bean
  public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).select()
        .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.controller"))
        .paths(PathSelectors.any()).build();
  }
}

在 http://localhost:9005/service-name/swagger-ui/ 訪問 swagger

就我而言,我使用了 mvn 依賴項

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>3.0.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>

調用 http://localhost:8088/swagger-ui/ 而不是 http://localhost:8088/swagger-ui.html 對我有用。 如果您有 swagger 配置文件,還要檢查 basePackage 是否正確。

如果有人想使用 Swagger UI,請執行以下 3 個簡單步驟

第 1 步 -> 添加依賴項

   <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
   <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>3.0.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>

第 2 步 -> 轉到主類並給出注釋 @EnableSwagger2

@SpringBootApplication
@EnableSwagger2
class PracticeApplication {

第 3 步 -> 重啟服務器 & 只需點擊 http://localhost:8080/swagger-ui/

注意 - 這樣做后,如果有人得到 - "Failed to start bean 'documentationPluginsBootstrapper"

然后將以下行添加到 application.properties -

spring.mvc.pathmatch.matching-strategy = ANT_PATH_MATCHER

對於 Swagger 3.0,URL 已更改

http://localhost:8080/swagger-ui/index.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM