如何编辑Swagger UI页面的css/html? (春季启动)

问题描述 投票:0回答:2

嗨,我是 Swagger 和 Spring 的新手。我想知道如何编辑 swagger-ui.html 页面。我正在使用 Pojo 文件来提供与参数相关的信息。我该怎么做才能使它看起来更好、更合适?我认为发生这种情况的原因是因为我在许多对象中使用了许多对象。我的假设是,这应该使用 html 和 CSS 来解决,但从 swagger 内置依赖项中获取它,因此无法编辑。

spring spring-boot swagger swagger-ui swagger-2.0
2个回答
0
投票

假设 springdoc 有一个文档部分适合您:https://springdoc.org/#customizing-swagger-static-resources

您可以自定义位于以下位置的 swagger 文档静态资源 META-INF/resources/webjars/swagger-ui/{swagger.version}/。名单 资源包括:... swagger-ui.css

还有一个代码片段。


0
投票

您可以在将 CSS 提供给前端之前以编程方式执行此操作!! 这样你就不需要更改 swagger-ui.jar 中的 css。 我选择在此处调整将 ovveride 追加到 swagger-ui.css 中。但是您当然可以编辑资源中的任何文件,并选择是否要附加或添加您自己的文件! :)

import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springdoc.core.properties.SwaggerUiConfigParameters;
import org.springdoc.core.properties.SwaggerUiConfigProperties;
import org.springdoc.core.properties.SwaggerUiOAuthProperties;
import org.springdoc.core.providers.ObjectMapperProvider;
import org.springdoc.webmvc.ui.SwaggerIndexTransformer;
import org.springdoc.webmvc.ui.SwaggerWelcomeCommon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import java.util.Arrays;
import java.util.stream.Stream;

import static java.util.Arrays.stream;

@Configuration
public class OpenApiConfig {


private final String title;
private final Environment environment;

public OpenApiConfig(@Value("${spring.application.name}") String title,         
Environment environment ) {
    this.title = title;
    this.environment = environment;
}
@Bean
public SwaggerIndexTransformer swaggerIndexTransformer(
        SwaggerUiConfigProperties swaggerUiConfig,
        SwaggerUiOAuthProperties swaggerUiOAuthProperties,
        SwaggerUiConfigParameters swaggerUiConfigParameters,
        SwaggerWelcomeCommon swaggerWelcomeCommon,
        ObjectMapperProvider objectMapperProvider) {
    return new TransformSwaggerCSS(swaggerUiConfig,
            swaggerUiOAuthProperties,
            swaggerUiConfigParameters,
            swaggerWelcomeCommon,
            objectMapperProvider, environment);
}
@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
            .info(getInfo())
            .components(new Components()
                    .addSecuritySchemes("blabla", apiKeySecuritySchema()
                            .type(SecurityScheme.Type.HTTP)
                            .scheme("blabla").bearerFormat("blabla")
                            .in(SecurityScheme.In.HEADER).name("BlaBlaBla")))
            .addSecurityItem(new SecurityRequirement().addList("bearer-jwt", 
Arrays.asList("read", "write")));

//                .security(Collections.singletonList(new 
SecurityRequirement().addList("KEY")))
//                // Use relative path to avoid reverse proxy changing the 
scheme
//                .addServersItem(new Server().url("/"));

}

@Component
public static class GlobalHeaderOperationCustomizer implements 
OperationCustomizer {
    @Override
    public Operation customize(Operation operation, HandlerMethod handlerMethod) 
{
        return operation
                .addParametersItem(
                        new 
Parameter().in(ParameterIn.HEADER.toString()).schema(new 
StringSchema()).name("override-userId"))
                .addParametersItem(
                        new Parameter().in(ParameterIn.HEADER.toString()).schema(new StringSchema()).name("override-country"));
    }
}

public SecurityScheme apiKeySecuritySchema() {
    return new SecurityScheme()
            .name("blablabla") 
            .description("blablabla")
            .in(SecurityScheme.In.HEADER)
            .type(SecurityScheme.Type.APIKEY);
}

private Info getInfo() {
    return new Info()
            .title(title)
            .description(
                    "Active Profiles: %s".formatted(Arrays.toString(environment.getActiveProfiles())) + "<br/>"+
                    "Default Profiles: %s".formatted(Arrays.toString(environment.getDefaultProfiles())));
}
}



import jakarta.servlet.http.HttpServletRequest;
import org.springdoc.core.properties.SwaggerUiConfigParameters;
import org.springdoc.core.properties.SwaggerUiConfigProperties;
import org.springdoc.core.properties.SwaggerUiOAuthProperties;
import org.springdoc.core.providers.ObjectMapperProvider;
import org.springdoc.webmvc.ui.SwaggerIndexPageTransformer;
import org.springdoc.webmvc.ui.SwaggerWelcomeCommon;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.resource.ResourceTransformerChain;
import org.springframework.web.servlet.resource.TransformedResource;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.Arrays.stream;

public class TransformSwaggerCSS extends SwaggerIndexPageTransformer {

private final Environment environment;

public TransformSwaggerCSS(SwaggerUiConfigProperties swaggerUiConfig,
                           SwaggerUiOAuthProperties swaggerUiOAuthProperties,
                           SwaggerUiConfigParameters swaggerUiConfigParameters,
                           SwaggerWelcomeCommon swaggerWelcomeCommon,
                           ObjectMapperProvider objectMapperProvider,
                           Environment environment) {
    super(swaggerUiConfig, swaggerUiOAuthProperties, swaggerUiConfigParameters,     
swaggerWelcomeCommon, objectMapperProvider);
    this.environment = environment;
}


@Override
public Resource transform(HttpServletRequest request,
                          Resource resource,
                          ResourceTransformerChain transformer)
        throws IOException {
    Optional<String> color = currentEnvProfile();
    if (color.isPresent() && resource.toString().contains("swagger-ui.css")) {
        InputStream inputStream = resource.getInputStream();
        final InputStreamReader isr = new InputStreamReader(inputStream);
        try (BufferedReader br = new BufferedReader(isr)) {
            String css = br.lines().collect(Collectors.joining());
            final byte[] transformedContent = (css + 
append(color.get())).getBytes();
            return new TransformedResource(resource, transformedContent);
        } // AutoCloseable br > isr > is
    }
    return super.transform(request, resource, transformer);
}

private String append(String color) {
    return " body {margin:0;background-color: rgba(%s) 
!important;}".formatted(color);
}

private Optional<String> currentEnvProfile() {
    Map<String, String> colormap = Map.of(
            "local", "255, 0, 0, 0.15",
            "dev", "251, 231, 239, 0.15");
    return stream(environment.getActiveProfiles())
            .filter(p -> Stream.of("local", "dev", "test", "preprod", 
"prod").anyMatch(p::contains))
            .findFirst()
            .map(colormap::get);
}
}
© www.soinside.com 2019 - 2024. All rights reserved.