草庐IT

java - 无法将 Swagger-ui 链接到我的 Swagger Spring mvc 项目

coder 2024-04-01 原文

我目前正在使用 Eclipse、Spring Framework MVC 创建一个 API Rest,我刚刚添加到我的项目中。我可以访问 swagger 的 json 结果,但我需要添加 swagger ui。

这是我为 swagger-springmvc 创建的所有文件:

WebAppInitializer.java

public class WebAppInitializer implements WebApplicationInitializer {

    private AnnotationConfigWebApplicationContext ctx = null;

    @Override
    public void onStartup(final ServletContext sc) throws ServletException {

        System.setProperty("spring.profiles.active", "web");

        // Create the 'root' Spring application context
        ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringBaseWebConfiguration.class,
                SpringSwaggerConfiguration.class);

        // Manages the lifecycle
        sc.addListener(new ContextLoaderListener(ctx));
        sc.addListener(new ContextCleanupListener());

        // Spring WebMVC
        ServletRegistration.Dynamic springWebMvc = sc.addServlet("ws",
                new DispatcherServlet(ctx));
        springWebMvc.setLoadOnStartup(1);
        springWebMvc.addMapping("/ws/*");
        springWebMvc.setAsyncSupported(true);
    }

    @PreDestroy
    protected final void cleanup() {
        if (ctx != null) {
            ctx.close();
        }
    }
}

SpringSwaggerConfiguration.java

public class SpringSwaggerConfiguration {
    public static final List<String> DEFAULT_INCLUDE_PATTERNS = Arrays
            .asList(new String[]{"/com/sa/rnd/dark/resources/.*"});
    public static final String SWAGGER_GROUP = "ApiDark";
    public static final String RELATIVE_GROUP = "ApiDark";
    @Autowired
    private SpringSwaggerConfig springSwaggerConfig;

/**
 * Adds the jackson scala module to the MappingJackson2HttpMessageConverter
 * registered with spring Swagger core models are scala so we need to be
 * able to convert to JSON Also registers some custom serializers needed to
 * transform swagger models to swagger-ui required json format
 */
@Bean
public JacksonScalaSupport jacksonScalaSupport() {
    final JacksonScalaSupport jacksonScalaSupport = new JacksonScalaSupport();
    // Set to false to disable
    jacksonScalaSupport.setRegisterScalaModule(true);
    return jacksonScalaSupport;
}

/**
 * Global swagger settings
 */
@Bean
public SwaggerGlobalSettings swaggerGlobalSettings() {
    final SwaggerGlobalSettings swaggerGlobalSettings = new SwaggerGlobalSettings();
    swaggerGlobalSettings.setGlobalResponseMessages(springSwaggerConfig
            .defaultResponseMessages());
    swaggerGlobalSettings.setIgnorableParameterTypes(springSwaggerConfig
            .defaultIgnorableParameterTypes());
    return swaggerGlobalSettings;
}

/**
 * API Info as it appears on the swagger-ui page
 */
private ApiInfo apiInfo() {
    return new ApiInfo(
            "Swagger Spring MVC for Dark Api",
            "Sample application demonstrating how to use swagger-springmvc in a no-XML environment.",
            "http://en.wikipedia.org/wiki/Terms_of_service",
            "michael@laccetti.com", "Apache 2.0",
            "http://www.apache.org/licenses/LICENSE-2.0.html");
}

/**
 * Configure a SwaggerApiResourceListing for each swagger instance within
 * your app. e.g. 1. private 2. external apis Required to be a spring bean
 * as spring will call the postConstruct method to bootstrap swagger
 * scanning.
 *
 * @return
 */
@Bean
public SwaggerApiResourceListing swaggerApiResourceListing() {
    // The group name is important and should match the group set on
    // ApiListingReferenceScanner
    // Note that swaggerCache() is by DefaultSwaggerController to serve the
    // swagger json
    final SwaggerApiResourceListing swaggerApiResourceListing = new SwaggerApiResourceListing(
            springSwaggerConfig.swaggerCache(), SWAGGER_GROUP);

    // Set the required swagger settings
    swaggerApiResourceListing
            .setSwaggerGlobalSettings(swaggerGlobalSettings());

    // Supply the API Info as it should appear on swagger-ui web page
    swaggerApiResourceListing.setApiInfo(apiInfo());

    // Use the default path provider
    swaggerApiResourceListing.setSwaggerPathProvider(springSwaggerConfig
            .defaultSwaggerPathProvider());

    // Global authorization - see the swagger documentation
    swaggerApiResourceListing.setAuthorizationTypes(authorizationTypes());

    // Sets up an auth context - i.e. which controller request paths to
    // apply global auth to
    swaggerApiResourceListing
            .setAuthorizationContext(authorizationContext());

    // Every SwaggerApiResourceListing needs an ApiListingReferenceScanner
    // to scan the spring request mappings
    swaggerApiResourceListing
            .setApiListingReferenceScanner(apiListingReferenceScanner());
    return swaggerApiResourceListing;
}

@Bean
/**
 * The ApiListingReferenceScanner does most of the work.
 * Scans the appropriate spring RequestMappingHandlerMappings
 * Applies the correct absolute paths to the generated swagger resources
 */
public ApiListingReferenceScanner apiListingReferenceScanner() {
    ApiListingReferenceScanner apiListingReferenceScanner = new ApiListingReferenceScanner();

    // Picks up all of the registered spring RequestMappingHandlerMappings
    // for
    // scanning
    apiListingReferenceScanner
            .setRequestMappingHandlerMapping(springSwaggerConfig
                    .swaggerRequestMappingHandlerMappings());

    // Excludes any controllers with the supplied annotations
    apiListingReferenceScanner.setExcludeAnnotations(springSwaggerConfig
            .defaultExcludeAnnotations());

    //
    apiListingReferenceScanner
            .setResourceGroupingStrategy(springSwaggerConfig
                    .defaultResourceGroupingStrategy());

    // Path provider used to generate the appropriate uri's
    apiListingReferenceScanner
            .setSwaggerPathProvider(relativeSwaggerPathProvider());

    // Must match the swagger group set on the SwaggerApiResourceListing
    apiListingReferenceScanner.setSwaggerGroup(SWAGGER_GROUP);

    // Only include paths that match the supplied regular expressions
    apiListingReferenceScanner.setIncludePatterns(DEFAULT_INCLUDE_PATTERNS);

    return apiListingReferenceScanner;
}

private List<AuthorizationType> authorizationTypes() {
    final List<AuthorizationType> authorizationTypes = new ArrayList<>();
    authorizationTypes.add(new BasicAuth());
    return authorizationTypes;
}

@Bean
public AuthorizationContext authorizationContext() {
    final List<Authorization> authorizations = newArrayList();

    AuthorizationScope authorizationScope = new AuthorizationScope(
            "global", "accessEverything");

    AuthorizationScope[] authorizationScopes = new AuthorizationScope[]{authorizationScope};
    authorizations.add(new Authorization("basic", authorizationScopes));

    AuthorizationContext authorizationContext = new AuthorizationContext.AuthorizationContextBuilder(
            authorizations).withIncludePatterns(DEFAULT_INCLUDE_PATTERNS)
            .build();

    return authorizationContext;
}

// Relative path example
@Bean
public SwaggerApiResourceListing relativeSwaggerApiResourceListing() {
    SwaggerApiResourceListing swaggerApiResourceListing = new SwaggerApiResourceListing(
            springSwaggerConfig.swaggerCache(), RELATIVE_GROUP);
    swaggerApiResourceListing
            .setSwaggerGlobalSettings(swaggerGlobalSettings());
    swaggerApiResourceListing
            .setSwaggerPathProvider(relativeSwaggerPathProvider());
    swaggerApiResourceListing
            .setApiListingReferenceScanner(relativeApiListingReferenceScanner());
    return swaggerApiResourceListing;
}

@Bean
public ApiListingReferenceScanner relativeApiListingReferenceScanner() {

    ApiListingReferenceScanner apiListingReferenceScanner = 
            new ApiListingReferenceScanner();

    apiListingReferenceScanner
            .setRequestMappingHandlerMapping(springSwaggerConfig
                    .swaggerRequestMappingHandlerMappings());

    apiListingReferenceScanner.setExcludeAnnotations(springSwaggerConfig
            .defaultExcludeAnnotations());

    apiListingReferenceScanner
            .setResourceGroupingStrategy(springSwaggerConfig
                    .defaultResourceGroupingStrategy());

    apiListingReferenceScanner
            .setSwaggerPathProvider(relativeSwaggerPathProvider());

    apiListingReferenceScanner.setSwaggerGroup(RELATIVE_GROUP);
    apiListingReferenceScanner.setIncludePatterns(DEFAULT_INCLUDE_PATTERNS);
    return apiListingReferenceScanner;
}

@Bean
public SwaggerPathProvider relativeSwaggerPathProvider() {
    return new ApiRelativeSwaggerPathProvider();
}

private class ApiRelativeSwaggerPathProvider extends
        DefaultSwaggerPathProvider {
    @Override
    public String getAppBasePath() {
        return "/ApiDark/ws";
    }
}

SpringBaseWebConfiguration.java :

@Configuration
@ComponentScan(basePackages = {"com.sa.rnd.dark.resources",
        "com.mangofactory.swagger.configuration",
        "com.mangofactory.swagger.controllers"})

@EnableWebMvc
public class SpringBaseWebConfiguration extends WebMvcConfigurerAdapter {
    private List<HttpMessageConverter<?>> messageConverters;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/api-docs").setViewName("redirect:index.html");
    }

    /**
     * The message converters for the content types we support.
     *
     * @return the message converters; returns the same list on subsequent calls
     */
    private List<HttpMessageConverter<?>> getMessageConverters() {
        if (messageConverters == null) {
            messageConverters = new ArrayList<>();

            final MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
            final ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                    false);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                    false);
            mappingJacksonHttpMessageConverter.setObjectMapper(mapper);
            messageConverters.add(mappingJacksonHttpMessageConverter);
        }
        return messageConverters;
    }

    @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        converters.addAll(getMessageConverters());
    }

    @Bean
    public static PropertyPlaceholderConfigurer swaggerProperties() {
        final PropertyPlaceholderConfigurer swaggerProperties = new PropertyPlaceholderConfigurer();
        swaggerProperties.setLocation(new ClassPathResource(
                "swagger.properties"));
        return swaggerProperties;
    }
}

这是我的 3 个文件,用于将 swagger 添加到我的项目中,atm 我只决定检查一种方法,即:

@Api(description = "CRUD services for containers working with WebDark",
        value = "CRUD Services Containers")
@RestController
@RequestMapping(value = "/container", produces = MediaType.APPLICATION_JSON_VALUE)
public class ContainersResources {
    /**
     * Find all children of a container.
     *
     * @param containerId
     *            ID of the parent container
     * @return ApiResponse
     */


    @ApiOperation(response = ApiResponse.class,
            value = "Find all children containers of one container",
            notes = "Find all children containers of one container")
    @RequestMapping(method = RequestMethod.GET, value = "/{containerId}")
    @ResponseStatus(HttpStatus.OK)
    public @ResponseBody ApiResponse<List<ContainerModel>> getContainerChildren(
            @ApiParam(required = true, value = "The id of the container parent",
                    name = "containerId")@PathVariable("containerId") final String containerId) {
        ApiResponse<List<ContainerModel>> result = new ApiResponse<>();
        result.setMessage("getContainerChildren  method of new Api Dark");
        result.setSuccess(true);
        result.setTotal(9000);
        return result;
    }
}

我的结果:我可以访问以下 url http://localhost:8080/ApiDark/ws/api-docs 但我得到的 json 值如下:

{"apiVersion":"1","swaggerVersion":"1.2","authorizations":{"basicAuth":{"type":"basicAuth"}},"info":{"title":"Swagger Spring MVC for Dark Api","description":"Sample application demonstrating how to use swagger-springmvc in a no-XML environment.","termsOfServiceUrl":"http://en.wikipedia.org/wiki/Terms_of_service","contact":"michael@laccetti.com","license":"Apache 2.0","licenseUrl":"http://www.apache.org/licenses/LICENSE-2.0.html"}}

这就是我决定添加 swagger-ui 的原因。我将 dist 文件夹的内容(取自 swagger-ui )添加到我的 src/main/webapp 文件夹中。并修改 index.html 的内容指向我的 url :

<script type="text/javascript">
$(function () {
  window.swaggerUi = new SwaggerUi({
      url: "http://localhost:8080/ApiDark/ws/api-docs.json",
  dom_id: "swagger-ui-container",

但我无法访问 swagger-ui 界面,我只有 json 结果...需要帮助才能使其正常工作!

最佳答案

这个问题似乎很老,但只是为了分享,使用最新版本的 swagger-springmvc 和 springmvc-ui,将 swagger & swagger-ui 与您的 Web 服务集成以在生产 REST api 中查看变得非常容易和不那么复杂文档。

添加了@EnableSwagger 注释,可以开箱即用地启用 swagger-springmvc。可以在/api-docs 访问生成的 swagger json 资源列表。

您可以引用以下链接了解将 swagger-springmvc 和 swagger-ui 与您的 spring mvc 项目集成的步骤。 https://github.com/martypitt/swagger-springmvc

关于java - 无法将 Swagger-ui 链接到我的 Swagger Spring mvc 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23128303/

有关java - 无法将 Swagger-ui 链接到我的 Swagger Spring mvc 项目的更多相关文章

  1. ruby - i18n Assets 管理/翻译 UI - 2

    我正在使用i18n从头开始​​构建一个多语言网络应用程序,虽然我自己可以处理一大堆yml文件,但我说的语言(非常)有限,最终我想寻求外部帮助帮助。我想知道这里是否有人在使用UI插件/gem(与django上的django-rosetta不同)来处理多个翻译器,其中一些翻译器不愿意或无法处理存储库中的100多个文件,处理语言数据。谢谢&问候,安德拉斯(如果您已经在ruby​​onrails-talk上遇到了这个问题,我们深表歉意) 最佳答案 有一个rails3branchofthetolkgem在github上。您可以通过在Gemfi

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  4. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  5. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  6. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  7. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  8. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  9. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

  10. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

随机推荐