大摇大摆地处理多个基本路径

Handling multiple basepath in swagger

我正在使用 swagger-ui 为我们的客户提供 REST API 的良好文档。 在内部,我们有两个不同的环境 jenkin builds 项目。 例如。 swagger.json 在两种环境中都可以访问: http://www.myhost.com/xyz/rest/swagger.json https://www.myhost2.com/rest/swagger.json

文档可作为: http://www.myhost.com/xyz/dist/index.html https://www.myhost2.com/dist/index.html

swagger api web.xml 中的基本路径是:

<init-param>       
     <param-name>swagger.api.basepath</param-name>
     <param-value>/rest</param-value>
</init-param>

问题: 我正在尝试在文档页面上使用 "Try it out" 功能。 两台主机各自的请求url如下: http://www.myhost.com/rest/getAUser https://www.myhost2.com/rest/getAUser

它适用于 host2,因为它命中正确 url。但是它应该为 host1 命中 http://www.myhost.com/xyz/rest/getAUser 但它正在命中 url http://www.myhost.com/rest/getAUser.

有什么方法可以为不同的 url 指定多个基本路径。

我的招摇-ui html 看起来像这样。

$(function () {
var href = window.location.href;
var url = href.substring(0, href.lastIndexOf("/dist"));
console.log(url);
// Pre load translate...
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
window.swaggerUi = new SwaggerUi({
url: url + "/rest/swagger.json",
dom_id: "swagger-ui-container",
......
......
}

我能够通过在 web.xml

中使用 BeanConfig 而不是使用 Servlet 配置 swagger 来解决这个问题

BeanConfig class:

public class SwaggerBootstrap extends DefaultJaxrsConfig {

    /**
     *
     */
    private static final long serialVersionUID = myAutoGeneratedID;

    @Override
    public void init(ServletConfig config) throws ServletException {

        super.init(config);
        //contextPath will be null for host2 and /xyz for host1.
        String contextPath = config.getServletContext().getContextPath();

        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setVersion("1.0.0");
        beanConfig.setTitle("My API Documentation");
        beanConfig.setSchemes(new String[] {
                "http", "https"
        });
        beanConfig
        .setResourcePackage("com.example.my.rest.api.package");

        beanConfig.setBasePath(contextPath + "/rest");
        beanConfig.setScan(true);
    }
}

并在 web.xml 中:

<servlet>
        <servlet-name>SwaggerBootstrap</servlet-name>
        <servlet-class>my.package.to.SwaggerBootstrap</servlet-class>
        <init-param>
            <!-- This make sure that all resources are scanned whether or not they use Swagger Annotations. 
            https://github.com/swagger-api/swagger-samples/tree/master/java/java-jaxrs-no-annotations -->
            <param-name>scan.all.resources</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>

我更改了 pom.xml 以开始使用最新稳定版的 swagger-jersey2-jaxrs:

<dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-jersey2-jaxrs</artifactId>
            <version>1.5.3</version>
        </dependency>