【问题标题】:Swagger, jersey, jax-rs, embedded jetty configuration problemSwagger、jersey、jax-rs、嵌入式码头配置问题
【发布时间】:2021-05-04 13:36:44
【问题描述】:

不确定这里是否适合提问。但我在文档或搜索(引擎)中找不到任何内容。

我正在尝试使用嵌入式码头服务器为生成的 swagger 类设置一个小型服务器。到目前为止,这适用于 Jetty 的以下配置:

ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/path");

QueuedThreadPool threadPool = getThreadPool();

jettyServer = new Server(threadPool);
jettyServer.setHandler(context);

// Shutdown gracefully
jettyServer.setStopAtShutdown(true);
// Set time until server get killed.
// jettyServer.setStopTimeout(30);

// Add a http config and a connector to set the port manually 
HttpConfiguration httpConfig = new HttpConfiguration();
ServerConnector http = new ServerConnector(jettyServer, new HttpConnectionFactory(httpConfig));
http.setPort(8080);

jettyServer.addConnector(http);

ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);

// Scans the package for new jersey controllers
jerseyServlet.setInitParameter(ServerProperties.PROVIDER_PACKAGES,
        "ch.company.ilp.clag.server.api" + "," + "ch.company.ilp.clag.controller" + ", " + "io.swagger.jaxrs.listing");

jerseyServlet.setInitParameter("jersey.config.server.wadl.disableWadl", "true");
// Finally start the server
jettyServer.start();

对 API 的调用按预期工作。另外,我的“自定义过滤器”可以正常工作。

要在正文中构建响应,我使用以下代码:

// this object is annotated with the jackson annotations. 
Response.status(Status.OK).entity(swaggerResponseObject).build()

我注意到,当我没有在 swagger 对象中设置值时,API 将它们返回为 null

示例 json 响应:

回复:

"global_response": {
    "result_state": "OK",
    "result_message": "",
    "result_code": "RESULT_STATE_OK",
    "result_attributes": null,
    "localizable_code": null
}

期望:

"global_response": {
    "result_state": "OK",
    "result_message": "",
    "result_code": "RESULT_STATE_OK",
}
  1. 这是 swagger 和 jaxrs 的默认行为吗?
  2. 这是可配置的吗?
  3. 怎么样?

我认为我尝试将类/包加载到我的 servlet 的方式有问题。如本问题所述: Null values on swagger JSON file

通过进一步搜索,我发现 SwaggerSerializers.writeTo() 永远不会被调用。而是调用 ProviderBase.writeTo()。

包中没有类:io.swagger.jaxrs.listing 被调用。

欢迎任何提示。

谢谢!

【问题讨论】:

    标签: java swagger jax-rs jetty


    【解决方案1】:

    根据您使用的 JSON 序列化程序,您需要以适当的方式配置 null 处理。

    在杰克逊中,它由以下人员完成:

    @JsonInclude(JsonInclude.Include.NON_NULL)
    class YourClass{
       ...
    }
    

    或者,如果您希望全局使用此行为,请配置您的 ObjectMapper:

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    

    【讨论】: