java 如何为swagger 2.8.0做友好的基本网址

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49924266/
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-11-03 10:29:24  来源:igfitidea点击:

how to do friendly base url for swagger 2.8.0

javaspring-bootrestswaggerspringfox

提问by Julia Tyrer

I'm trying to change base access url for API documentation. The url is "http://localhost:8080/swagger-ui.html". I want to get something like "http://localhost:8080/myapi/swagger-ui.html".

我正在尝试更改 API 文档的基本访问 url。网址是“ http://localhost:8080/swagger-ui.html”。我想得到类似“ http://localhost:8080/myapi/swagger-ui.html”的东西。

I use Springfox 2.8.0 Swagger, Java 8, Spring Boot 2.0 The swagger configuration is:

我使用的是 Springfox 2.8.0 Swagger、Java 8、Spring Boot 2.0 的 swagger 配置是:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket api(ServletContext servletContext) {
        return new Docket(DocumentationType.SWAGGER_2)
                .pathProvider(new RelativePathProvider(servletContext) {
                    @Override
                    public String getApplicationBasePath() {
                        return "/myapi";
                    }
                })
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/error")))
                .build()
                .useDefaultResponseMessages(false);
    }
}

Custom path provider had to help, but I still get access to api documentation by using url "http://localhost:8080/swagger-ui.html". If I use url "http://localhost:8080/myapi/swagger-ui.html", I get 404 error. Look at the screenshot below.

自定义路径提供程序必须提供帮助,但我仍然可以通过使用 url“ http://localhost:8080/swagger-ui.html”访问 api 文档。如果我使用 url " http://localhost:8080/myapi/swagger-ui.html",我会收到404 错误。看看下面的截图。

enter image description here

在此处输入图片说明

回答by Donz

https://github.com/springfox/springfox/issues/2250- as they said you can configure redirect to your own path

https://github.com/springfox/springfox/issues/2250- 正如他们所说,您可以配置重定向到您自己的路径

回答by serhii

I also have faced this problem and tried many possible resolutions, and nothings didn't help really. In my case, I can't use any resource redirect as swagger must be accessible as locally as on google cloud by match path /api-docs/**. and on google cloud any resource redirection will be denied in my case. All resources must be loading also from this path

here is my solution:
springfox-swagger2 and springfox-swagger-ui of version 2.9.2

我也遇到过这个问题并尝试了许多可能的解决方案,但没有任何帮助。就我而言,我不能使用任何资源重定向,因为 swagger 必须可以像在谷歌云上一样通过匹配路径 /api-docs/** 在本地访问。在我的情况下,在谷歌云上任何资源重定向都将被拒绝。所有资源也必须从此路径加载,这

是我的解决方案:
springfox-swagger2 和 springfox-swagger-ui of version 2.9.2

@EnableSwagger2
@Configuration
public class SwaggerCommonConfig implements WebMvcConfigurer {
    public static final String PATH = "/api-docs";

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

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController(PATH, "/");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(PATH + "/**").addResourceLocations("classpath:/META-INF/resources/");
    }
}

and as springfox don't have any possibilities to do it by another way, in my case, we just will create simple controller that will be translating resource requests from our custom path to standard springfox. (it's not very elegant part but as it is :))

并且由于 springfox 没有任何可能通过其他方式做到这一点,在我的情况下,我们将创建简单的控制器,将资源请求从我们的自定义路径转换为标准 springfox。(这不是很优雅的部分,但它是:))

@RestController
@RequestMapping(SwaggerGatewayCommonConfig.PATH)
@RequiredArgsConstructor
public class SwaggerController {
    private final RestTemplate restTemplate;
    private final static String V2_API_DOCS = "/v2/api-docs";
    private final static String SWAGGER_RESOURCES_CONFIGURATION_UI = "/swagger-resources/configuration/ui";
    private final static String SWAGGER_RESOURCES_CONFIGURATION_SECURITY = "/swagger-resources/configuration/security";
    private final static String SWAGGER_RESOURCES = "/swagger-resources";
    private final static Pattern pattern = Pattern.compile("http[s]*://([^/]+)", Pattern.CASE_INSENSITIVE);

    @Value("${server.port}")
    private String port;

    @GetMapping(V2_API_DOCS)
    @SuppressWarnings("unchecked")
    public Map<String, Object> getV2ApiDocs(HttpServletRequest request) {
        Matcher matcher = pattern.matcher(request.getRequestURL().toString());
        matcher.find();

        Map<String, Object> resp = (Map<String, Object>) restTemplate.getForObject(toLocalSwaggerUrl(V2_API_DOCS), Map.class);
        //we have to replace standard host, to requested host. as swagger UI make api requests from this host
        resp.put("host", matcher.group(1));

        return resp;
    }

    @GetMapping(SWAGGER_RESOURCES_CONFIGURATION_UI)
    public Object getSwaggerResourcesConfigurationUi() {
        return restTemplate.getForObject(toLocalSwaggerUrl(SWAGGER_RESOURCES_CONFIGURATION_UI), Object.class);
    }

    @GetMapping(SWAGGER_RESOURCES_CONFIGURATION_SECURITY)
    public Object getSwaggerResourcesConfigurationSecurity() {
        return restTemplate.getForObject(toLocalSwaggerUrl(SWAGGER_RESOURCES_CONFIGURATION_SECURITY), Object.class);
    }

    @GetMapping(SWAGGER_RESOURCES)
    public Object getSwaggerResources() {
        return restTemplate.getForObject(toLocalSwaggerUrl(SWAGGER_RESOURCES), Object.class);
    }

    private String toLocalSwaggerUrl(String path) {
        return "http://localhost:" + port + path;
    }
}

I hope it will save time to somebody faced it also =) Good luck

我希望它也能为遇到它的人节省时间 =) 祝你好运

回答by Uta Alexandru

Swagger base access url is constructed from your base application path.So if you change your base application path , you will get the desired behavior.But also all your apis will be changed to that path. You can find how to change it here How to set base url for rest in spring boot?.

Swagger 基本访问 url 是根据您的基本应用程序路径构造的。因此,如果您更改基本应用程序路径,您将获得所需的行为。但您的所有 api 也将更改为该路径。您可以在此处找到如何更改它如何在 Spring Boot 中设置用于休息的基本 url?.

What you did was too change how swagger call other apis from your application, not to change his base url. There are some tricks to change the swagger base url without changing application base path (moving manually all swagger resources), but i do not recommend that.

您所做的太改变了招摇从您的应用程序调用其他 api 的方式,而不是更改他的基本 url。有一些技巧可以在不更改应用程序基本路径的情况下更改 swagger 基本 url(手动移动所有 swagger 资源),但我不建议这样做。

回答by veben

You can edit your SwaggerConfigurationlike that:

您可以像这样编辑SwaggerConfiguration

Take care to replace the package(which need to be the one containing your REST controllers), the host, and the PATHyou need

小心替换package(必须是包含您的 REST 控制器的)host、 和PATH您需要的

@Configuration
@EnableSwagger2
public class SwaggerConfiguration implements WebMvcConfigurer {

    public static final String PATH = "/myapi";

    @Bean
    public Docket api() {
        final var package = "com.julia.rest";
        final var host = "localhost:8080";

        return new Docket(DocumentationType.SWAGGER_2)
                .host(host)
                .select()
                .apis(RequestHandlerSelectors.basePackage(package))
                .paths(PathSelectors.any())
                .build();
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        final var apiDocs = "/v2/api-docs";
        final var configUi = "/swagger-resources/configuration/ui";
        final var configSecurity = "/swagger-resources/configuration/security";
        final var resources = "/swagger-resources";

        registry.addRedirectViewController(PATH + apiDocs, apiDocs).setKeepQueryParams(true);
        registry.addRedirectViewController(PATH + resources, resources);
        registry.addRedirectViewController(PATH + configUi, configUi);
        registry.addRedirectViewController(PATH + configSecurity, configSecurity);
        registry.addRedirectViewController(PATH, "/");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(PATH + "/**").addResourceLocations("classpath:/META-INF/resources/");
    }
}

Another solution is by changing the spring-boot URL context-path:

另一种解决方案是更改 spring-boot URL context-path

Edit pour application.propertiesfile:

编辑浇筑application.properties文件:

server.servlet.context-path=/myapi

Or if you have an application.ymlfile:

或者,如果您有一个application.yml文件:

server:
  servlet:
    context-path: /myapi

Warning: It will change the base path of all your web services, not only Swagger

警告:它会改变所有 Web 服务的基本路径,而不仅仅是 Swagger