programing

스프링부츠 + 스웨거 + 커스텀 스웨거 -ui.html

padding 2023. 10. 15. 17:04
반응형

스프링부츠 + 스웨거 + 커스텀 스웨거 -ui.html

전쟁 응용 프로그램을 스프링 부트 병 응용 프로그램으로 마이그레이션하는 데 문제가 있습니다.

스프링부츠 1.4.1과 스웨거 2.6.0을 사용하고 있습니다.

전쟁에서 swaggerui를 사용자 지정하려면 /webapp 디렉토리에 사용자 지정 swagger-ui.html을 넣어야 합니다.spring boot에서는 webapp 디렉토리가 번들 병에서 작동하지 않으므로 사용하지 않는 것이 좋습니다.그러나 /resources/static에 사용자 지정 swagger-ui.html을 넣는 것은 swagger에서 무시됩니다.

애플리케이션에 전체 스웩 분포를 추가하는 대신 간단한 해결책이 있습니까?

내 맞춤형 swagger-ui.html은 다음과 같습니다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>API</title>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
<link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
<link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>
<script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/handlebars-2.0.0.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/underscore-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/highlight.7.3.pack.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>

<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>

<style>
    .swagger-section #header {
        background-color: #ff5722;
    }
</style>
</head>

<body class="swagger-section">
<div id='header'>
    <div class="swagger-ui-wrap">
        <a id="logo" href="http://www.my-app.com">my-app.com API</a>

        <form id='api_selector'>
            <div class='input' style="display: none">
                <select id="select_baseUrl" name="select_baseUrl"/>
            </div>
            <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl"
                                  type="text"/>
            </div>
            <!--
            <div class='input'><input placeholder="Enter authorization token" id="input_apiKey" name="apiKey" type="text"/></div>
            <div class='input' style="display: none"><a id="explore" href="#" data-sw-translate>Explore</a></div>
            -->
        </form>
    </div>
</div>

<script type="text/javascript">
    function addApiKeyAuthorization() {
        var key = $('#input_apiKey')[0].value;
        console.log("key: " + key);
        if (key && key.trim() != "") {
            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("Authorization", key, "header");
            window.swaggerUi.api.clientAuthorizations.add("bearer", apiKeyAuth);
            //window.authorizations.add("Authorization", new ApiKeyAuthorization("Authorization", key, "query"));
        console.log("Set authorization token: " + key);
        }
    }
    $('#input_apiKey').change(function () {
        addApiKeyAuthorization();
    });
</script>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>

원래의 springfox-swagger-ui에서 복사한 두 개의 파일만으로 Swagger를 Springboot 애플리케이션에 사용자 지정할 수 있는 간단한 방법을 찾았습니다.

먼저 SwaggerConfig.java에서 @Configuration을 비활성화했습니다.

//@Configuration <-- Attention, disable Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .ignoredParameterTypes(Pageable.class)
                .select().apis(RequestHandlerSelectors.any())
                .paths(regex("/v1/.*"))
                .build();

    }
}

그런 다음 WebMvcConfigurerAdapter를 확장했습니다.

@Configuration
@Import(SwaggerConfig.class)
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc/v1/**").addResourceLocations("classpath:/doc/v1/");
        registry.addResourceHandler("/doc/v1/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

그럼 간단한 수정만으로 src/main/resource/doc/v1/api.html 원본 파일 swagger-ui.html을 복사했습니다.저는 이 줄로 대체했습니다.

<script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>

다음 행과 함께:

<script src='js/swagger.js' type='text/javascript'></script>

이것은 나의 api.html 입니다.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
    <link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>

    <script src='webjars/springfox-swagger-ui/lib/object-assign-pollyfill.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/handlebars-4.0.5.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/lodash.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>

    <script src='js/springfox.js' type='text/javascript'></script>
</head>

<body class="swagger-section">
<div id='header'>
    <div class="swagger-ui-wrap">
        <a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30" src="webjars/springfox-swagger-ui/images/logo_small.png" /><span class="logo__title">swagger</span></a>
        <form id='api_selector'>
            <div class='input'>
                <select id="select_baseUrl" name="select_baseUrl"/>
            </div>
            <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
            <div id='auth_container'></div>
            <div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
        </form>
    </div>
</div>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>

그 후 원래 springfox.js를 src/main/resource/doc/v1/js/springfox.js로 복사하여 다음 줄을 변경했습니다.

"baseUrl": function() {
      var urlMatches = /(.*)\/swagger-ui.html.*/.exec(window.location.href);
      return urlMatches[1];
    },

다음 행과 함께:

"baseUrl": function() {
            return window.location.origin;
        },

이것은 나의 완전한 springfox.js입니다.

$(function() {
    var springfox = {
        "baseUrl": function() {
            return window.location.origin;
        },
        "securityConfig": function(cb) {
            $.getJSON(this.baseUrl() + "/swagger-resources/configuration/security", function(data) {
                cb(data);
            });
        },
        "uiConfig": function(cb) {
            $.getJSON(this.baseUrl() + "/swagger-resources/configuration/ui", function(data) {
                cb(data);
            });
        }
    };
    window.springfox = springfox;
    window.oAuthRedirectUrl = springfox.baseUrl() + '/webjars/springfox-swagger-ui/o2c.html';

    window.springfox.uiConfig(function(data) {
        window.swaggerUi = new SwaggerUi({
            dom_id: "swagger-ui-container",
            validatorUrl: data.validatorUrl,
            supportedSubmitMethods: data.supportedSubmitMethods || ['get', 'post', 'put', 'delete', 'patch'],
            docExpansion: data.docExpansion || 'none',
            jsonEditor: JSON.parse(data.jsonEditor) || false,
            apisSorter: data.apisSorter || 'alpha',
            defaultModelRendering: data.defaultModelRendering || 'schema',
            showRequestHeaders: data.showRequestHeaders || true,
            timeout: data.requestTimeout,
            onComplete: function(swaggerApi, swaggerUi) {

                initializeSpringfox();

                if (window.SwaggerTranslator) {
                    window.SwaggerTranslator.translate();
                }

                $('pre code').each(function(i, e) {
                    hljs.highlightBlock(e)
                });

            },
            onFailure: function(data) {
                log("Unable to Load SwaggerUI");
            },
        });

        initializeBaseUrl();

        function addApiKeyAuthorization(security) {
            var apiKeyVehicle = security.apiKeyVehicle || 'query';
            var apiKeyName = security.apiKeyName || 'api_key';
            var apiKey = security.apiKey || '';
            if (apiKey && apiKey.trim() != "") {
                var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization(apiKeyName, apiKey, apiKeyVehicle);
                window.swaggerUi.api.clientAuthorizations.add(apiKeyName, apiKeyAuth);
                log("added key " + apiKey);
            }
        }

        function log() {
            if ('console' in window) {
                console.log.apply(console, arguments);
            }
        }

        function oAuthIsDefined(security) {
            return security.clientId
                && security.clientSecret
                && security.appName
                && security.realm;
        }

        function initializeSpringfox() {
            var security = {};
            window.springfox.securityConfig(function(data) {
                security = data;
                addApiKeyAuthorization(security);
                if (typeof initOAuth == "function" && oAuthIsDefined(security)) {
                    initOAuth(security);
                }
            });
        }
    });

    $('#select_baseUrl').change(function() {
        window.swaggerUi.headerView.trigger('update-swagger-ui', {
            url: $('#select_baseUrl').val()
        });
    });

    function maybePrefix(location, withRelativePath) {
        var pat = /^https?:\/\//i;
        if (pat.test(location)) {
            return location;
        }
        return withRelativePath + location;
    }

    function initializeBaseUrl() {
        var relativeLocation = springfox.baseUrl();

        $('#input_baseUrl').hide();

        $.getJSON(relativeLocation + "/swagger-resources", function(data) {

            var $urlDropdown = $('#select_baseUrl');
            $urlDropdown.empty();
            $.each(data, function(i, resource) {
                var option = $('<option></option>')
                    .attr("value", maybePrefix(resource.location, relativeLocation))
                    .text(resource.name + " (" + resource.location + ")");
                $urlDropdown.append(option);
            });
            $urlDropdown.change();
        });

    }

});

이것이 내 폴더 구조입니다.

이제 응용 프로그램을 실행하고 http://localhost:8080/doc/v1/api.html로 이동하면 됩니다.

maven을 사용하는 경우 해결 방법:

  • 복사해야 합니다.swagger-ui.html안으로src/main/webapp

  • 판을 만들거나 바꿉니다.screen.css당신에 의해서theme.css

이 코드들을 당신의 것에 추가하는 것 보다.pom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <webResources>
                    <resource>
                        <directory>${basedir}/src/main/webapp</directory>
                        <filtering>true</filtering>
                        <includes>
                            <include>*.css</include>
                            <include>*.html</include>
                        </includes>
                    </resource>
                </webResources>
            </configuration>
        </plugin>
    </plugins>
</build>

언급URL : https://stackoverflow.com/questions/39976369/spring-boot-swagger-custom-swagger-ui-html

반응형