Change location to call swagger-ui in Spring

两盒软妹~` 提交于 2019-12-10 11:44:34

问题


How I can change location to call swagger api docs from http://localhost:8081/swagger-ui.html to http://localhost:8081/my-api-doc?

My SwaggerConfig is

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

And I use springfox-swagger2 and springfox-swagger-ui both with version 2.7.0.


回答1:


This is all I can did it.

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {

            registry.addRedirectViewController("/documentation/v2/api-docs", "/v2/api-docs?group=restful-api");
            registry.addRedirectViewController("/documentation/swagger-resources/configuration/ui","/swagger-resources/configuration/ui");
            registry.addRedirectViewController("/documentation/swagger-resources/configuration/security","/swagger-resources/configuration/security");
            registry.addRedirectViewController("/documentation/swagger-resources", "/swagger-resources");
            registry.addRedirectViewController("/documentation", "/documentation/swagger-ui.html");
    }


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

This methods is added in a configuration class that extend WebMvcConfigurerAdapter like that public class Configuration extends WebMvcConfigurerAdapter {...}

You can't remove swagger-ui.html or change because is hard-coded in source code.




回答2:


If using Spring Boot, you can add a mapping to redirect the request like:

@GetMapping("/swagger")
public void swaggerRedirect(HttpServletResponse response) {
    response.setHeader("Location", "/swagger-ui.html");
    response.setStatus(302);
}


来源:https://stackoverflow.com/questions/46180375/change-location-to-call-swagger-ui-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!