如何在 Jersey WADL 中包含类型同时返回响应

sli*_*fty 6 java rest jax-rs jersey-2.0

情况

我有一个返回User对象的 Jersey 2.18 API 端点。我的利益相关者需要 API 来生成一个 WADL 文件,该文件不仅反映 API 路径,还反映返回的对象类型。

截至 2015 年,Jersey 通过使用以下端点定义开箱即用地涵盖了这一点:

@GET
@Path("/")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public User getExampleUser() {
    User exampleUser = new User();
    return exampleUser;
}
Run Code Online (Sandbox Code Playgroud)

jersey 生成的结果 WADL 文件正确包含端点以及返回类型:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<application xmlns="http://wadl.dev.java.net/2009/02">
    <doc xmlns:jersey="http://jersey.java.net/" jersey:generatedBy="Jersey: 2.18 2015-06-05 02:28:21"/>
    <doc xmlns:jersey="http://jersey.java.net/" jersey:hint="This is simplified WADL with user and core resources only. To get full WADL with extended resources use the query parameter detail. Link: http://localhost:8080/example/api/v3/application.wadl?detail=true"/>
    <grammars>
        <include href="application.wadl/xsd0.xsd">
            <doc title="Generated" xml:lang="en"/>
        </include>
    </grammars>
    <resources base="http://localhost:8080/example/api/v3/">
        <resource path="/">
            <method id="getExampleUser" name="GET">
                <request>
                </request>
                <response>
                    <ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="user" mediaType="application/json"/>
                    <ns2:representation xmlns:ns2="http://wadl.dev.java.net/2009/02" xmlns="" element="user" mediaType="application/xml"/>
                </response>
            </method>
        </resource>    
    </resources>
</application>
Run Code Online (Sandbox Code Playgroud)

但大多数 Jersey 社区似乎都有端点返回一个更通用的Response对象,它允许各种好东西,包括E-TAG 缓存、HTTP 状态代码操作、错误消息传递等等。

例如:

@GET
@Path("/")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getExampleUser()  {
    User exampleUser = new User();
    return Response.ok(exampleUser).build();
}
Run Code Online (Sandbox Code Playgroud)

生成的 WADL 看起来相同,但响应部分现在没有显示返回类型和模式的证据。

<response>
    <representation mediaType="application/json"/>
    <representation mediaType="application/xml"/>
</response>
Run Code Online (Sandbox Code Playgroud)

我的问题

是否可以从丰富的自动生成的 WADL 文件中受益,同时还可以让我的端点返回更灵活的Response对象?

或者,如何处理重定向、缓存和其他基本 API 功能,同时仍从我的端点定义返回特定对象类型?

小智 1

我遇到了完全相同的问题,并且能够像这样解决它:

  • 我的所有实体都必须进行注释@XmlRootElement并发送到虚拟休息端点,以便它们显示在application.wadl/xsd0.xsd.
  • 我将Swagger包含在我的项目中,并使用它来生成包含响应代码和响应对象的文档。
  • 然后我运行现有的 wadl 生成工具application.wadl.
  • 最后一步是编写一个方法,将 Swagger 文件中的响应代码和对象插入到 wadl 文件中。

最后三个步骤在休息服务中组合在一起。结果是通过调用rest服务自动生成了wadl,你可以Response像以前一样继续使用。