Java swagger-ui 未找到 HTTP 请求的映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43545540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:59:43  来源:igfitidea点击:

swagger-ui No mapping found for HTTP request

javaspringspring-mvcswagger-uispringfox

提问by felipe

I'm trying to document and existing Rest API a Spring MVC project (NOT spring boot!).

我正在尝试记录和现有的 Rest API 一个 Spring MVC 项目(不是 spring boot!)。

My application is called apiso http://localhost:9090/apiwould be the root endpoint. Because I'm using spring-data-rest, on that URL I can see the json of all my exposed repositories. So far so good.

我的应用程序称为api,因此http://localhost:9090/api将是根端点。因为我使用的是 spring-data-rest,所以在该 URL 上我可以看到所有公开存储库的 json。到现在为止还挺好。

I can also access the swagger JSON http://localhost:9090/api/v2/api-docs

我还可以访问 swagger JSON http://localhost:9090/api/v2/api-docs

The problem

问题

I can't access the swagger-UI component on http://localhost:9090/api/swagger-ui.html. It gives me

我无法访问http://localhost:9090/api/swagger-ui.html上的 swagger-UI 组件。它给了我

WARN  org.springframework.web.servlet.PageNotFound- No mapping found for HTTP request with URI [/api/swagger-ui.html] in DispatcherServlet with name 'dispatcher'

Checking the spring logs when starting tomcat I can see something weird

启动tomcat时检查spring日志我可以看到一些奇怪的东西

DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory- Finished creating instance of bean 'swaggerApiListingReader'
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerConfig': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swagger2Controller': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerMediaTypeReader': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerOperationModelsProvider': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerOperationResponseClassReader': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerOperationTagsReader': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerResponseMessageReader': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerParameterDescriptionReader': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerExpandedParameterBuilder': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerApiListingReader': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swaggerProperties': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'springfox.documentation.swagger.configuration.SwaggerCommonConfiguration': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration': no URL paths identified
DEBUG org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping- Rejected bean name 'swagger2Module': no URL paths identified

That seems to indicate the for some reason swaggerController is not associated to any URL, hence the 404 error.

这似乎表明由于某种原因 swaggerController 未与任何 URL 关联,因此出现 404 错误。

These are the version I'm working with

这些是我正在使用的版本

  <spring.version>4.2.8.RELEASE</spring.version>
  <spring-data.version>Gosling-SR4</spring-data.version>
  <spring-data-rest>2.4.6.RELEASE</spring-data-rest> 
   <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-data-rest</artifactId>
        <version>2.6.1</version>
    </dependency>

This is my Java conf. Worth pointing out that the method addResourceHandlersNEVER GETS executed

这是我的 Java conf。值得指出的是addResourceHandlers方法永远不会被执行

    @Configuration
    @EnableSwagger2
    @EnableWebMvc

  @Import({springfox.documentation.spring.data.rest.configuration.SpringDataRestConfiguration.class})
public class SwaggerConfig extends WebMvcConfigurerAdapter {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        System.out.println("******************************Configuring swagger resource handler");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

Any suggestions? In short, swagger-ui does not work.

有什么建议?简而言之,swagger-ui 不起作用。

回答by Dilip Krishnan

This solution is courtesy this answerby @oksett

这个解决方案是由@oksett提供的这个答案礼貌

Create a configuration class, which extends WebMvcConfigurerAdapterand override the following methods:

创建一个配置类,它扩展WebMvcConfigurerAdapter和覆盖以下方法:

If Using Spring 5, instead of extends WebMvcConfigurerAdapterimplements WebMvcConfigurer

如果使用 Spring 5,而不是 extendsWebMvcConfigurerAdapter实现WebMvcConfigurer

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addRedirectViewController("/api/v2/api-docs", "/v2/api-docs");
    registry.addRedirectViewController("/api/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
    registry.addRedirectViewController("/api/swagger-resources/configuration/security", "/swagger-resources/configuration/security");
    registry.addRedirectViewController("/api/swagger-resources", "/swagger-resources");
}

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

In your case you need to add and implementation of addViewControllersto SwaggerConfig. Also note the changes in the addResourceHandlersmethod to prepend /apito the the rescue handler location.

在您的情况下,您需要添加和实现addViewControllersto SwaggerConfig。还要注意添加到救援处理程序位置的addResourceHandlers方法中的更改/api

You should now be able to access into my swagger-ui.html @ http://localhost:9090/api/swagger-ui.html

您现在应该可以访问我的 swagger-ui.html @ http://localhost:9090/api/swagger-ui.html

回答by felipe

We ended up deploying Swagger-UI client separately and serving it through Nginx. We could not work out what's wrong with it and based on extensive research found many others having same difficulty so we decided to stop spending time on trying the embedded approach.

我们最终单独部署了 Swagger-UI 客户端并通过 Nginx 为其提供服务。我们无法弄清楚它有什么问题,并且根据广泛的研究发现许多其他人也有同样的困难,因此我们决定停止花时间尝试嵌入式方法。

回答by Marcin

Had a similar problem and Dilips anwser worked. To be more precise:

有一个类似的问题和 Dilips anwser 工作。更准确地说:

  1. My api-docs location worked fine

  2. My swagger-ui.html was rendering but nothing viewed. In browser console i could see 404 for /configuration/ui dir.

  1. 我的 api-docs 位置工作正常

  2. 我的 swagger-ui.html 正在渲染,但没有看到任何内容。在浏览器控制台中,我可以看到 /configuration/ui 目录的 404。

the correct dir was /swagger-resources/configuration/ui so i had to do a redirection:

正确的目录是 /swagger-resources/configuration/ui 所以我不得不做一个重定向:

registry.addRedirectViewController("/configuration/ui", "/swagger-resources/configuration/ui");

回答by biniam

The following is a complete code on how to configure spring boot with swagger doc and working UI.

以下是关于如何使用 swagger doc 和工作 UI 配置 spring boot 的完整代码。

pom.xml

pom.xml

<!-- Spring boot version is 2.0.3.RELEASE-->

<dependencies>
  <!-- Swagger 2 Doc Dependency -->
  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
  </dependency>

  <!-- Swagger 2 UI -->
  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
  </dependency>
</dependencies>

SwaggerDocConfig.java

SwaggerDocConfig.java

package com.example.springbootswagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerDocConfig 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/");
    }

    @Bean
    public Docket apiDocket() {

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(getApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.springbootswagger.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo getApiInfo() {

        return new ApiInfoBuilder()
                .title("Swagger API Doc")
                .description("More description about the API")
                .version("1.0.0")
                .build();
    }
}

回答by Salah Eddine El Ouali

Had a similar problem a while ago. I found out it was caused by @EnableWebMvcannotation in my custom Exception Handler.

前一阵子遇到了类似的问题。我发现它是由@EnableWebMvc我的自定义异常处理程序中的注释引起的。

@ControllerAdvice
@RestController
@EnableWebMvc
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {}

Removing @EnableWebMvcdid the trick for me!!

删除@EnableWebMvc对我有用!!

回答by hang gao

is work for me

对我有用

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");    
   }
}

回答by vikifor

This is what works for me

这对我有用

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport{ 

@Override
public void addViewControllers(ViewControllerRegistry registry) {
  registry.addRedirectViewController("/configuration/ui", "/swagger-resources/configuration/ui");
}

@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/");
}}

Here is the pom:

这是pom:

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

回答by Tiago Medici

If you are using spring boot, that's all you need :

如果您使用的是弹簧靴,这就是您所需要的:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
    <relativePath />
</parent>



    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

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

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

the configuration 4 swagger :

配置4招摇:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();
    }
}

回答by m1sh0

I fixed the issue with this implementation:

我解决了这个实现的问题:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.annotation.AuthenticationPrincipal;

import com.google.common.base.Predicates;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebSecurityConfigurerAdapter {
    public static String[] SWAGGER_URL_PATHS = new String[] { "/swagger-ui.html**", "/swagger-resources/**",
            "/v2/api-docs**", "/webjars/**" };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.requestMatchers().antMatchers(SWAGGER_URL_PATHS).and().authorizeRequests().antMatchers(SWAGGER_URL_PATHS)
                .permitAll();
    }

    @Bean
    public Docket docket() {

        return new Docket(DocumentationType.SWAGGER_2).ignoredParameterTypes(AuthenticationPrincipal.class).select()
                .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
                .paths(PathSelectors.any()).build();
    }

}

P.S don't forget to this in your gradle file

PS不要忘记在你的gradle文件中

compile('org.springframework.boot:spring-boot-starter-security')