【问题标题】:Java Jersey Declarative Hyperlinking @Ref Annotation UseJava Jersey 声明式超链接 @Ref 注解使用
【发布时间】:2012-03-25 21:40:54
【问题描述】:

我一直在尝试扩展 Jersey 1.12 文档第 6 章(声明性超链接)中提供的示例,但在使用 @Ref 注释方面似乎遇到了困难。

我的代码如下:

@Path("/offerings/{offeringId}/widgets")
@Produces(MediaType.APPLICATION_JSON)
public class WidgetsResource {
  @GET
  @Path("/{widgetId}")
  public Response get(@PathParam("offeringId") String offeringId, @PathParam("widgetId") String widgetId) {
    Widgets widgets = new Widgets();
    widgets.setOfferingId(Integer.valueOf(offeringId));
    Widget widget = new Widget();
    widget.setId(Integer.valueOf(widgetId));
    widgets.setWidgets(Arrays.asList(widget));
    return Response.status(200).entity(widgets).build();
  }
}

public class Widgets {
    @Ref(resource = WidgetsResource.class, style=Style.ABSOLUTE)
    URI uri;
    @JsonIgnore
    private int offeringId;
    private Collection<Widget> widgets;

    public Collection<Widget> getWidgets() {
        return widgets;
    }

    public void setWidgets(Collection<Widget> widgets) {
        this.widgets = widgets;
    }

    public URI getUri() {
        return uri;
    }

    public int getOfferingId() {
        return offeringId;
    }

    public void setOfferingId(int id) {
        this.offeringId = id;
    }
}

public class Widget {
    @Ref(resource = WidgetsResource.class, style=Style.ABSOLUTE, bindings={
    @Binding(name="offeringId", value="${entity.offeringId}")}
    )
    URI uri;
    private int id;

    public URI getUri() {
        return uri;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

这适用于为 Widgets 集合对象的实例生成的 URL:

"uri": "http://localhost:65080/<app>/offerings/9999/widgets"

但是,我想知道如何将集合中的 Widget 实例的 id 附加到每个 Widget 的 URL。因此,生成的 URI 将类似于:

"uri": "http://localhost:65080/<app>/offerings/9999/widgets/1234"

如果不开始硬编码 Widget 类中的整个路径值,我似乎找不到使用 Ref 注释的方法来实现这一点,如果可能的话,我想避免这种情况。

是否有实现此目的的标准方法?

【问题讨论】:

    标签: java rest annotations jersey hypermedia


    【解决方案1】:

    我对该文档的阅读表明您可以执行以下操作(未经测试!):

    @Ref(value="/offerings/{offeringId}/widgets/{widgetId}", style=ABSOLUTE)
    URI uri;
    

    【讨论】:

    • 您应该仍然可以使用这种方法进行绑定,尽管这里的悲剧是您现在在表示需要子资源 URI 的每个地方复制硬编码路径。如果您在大型应用程序中执行真正的或接近于真正的 REST,那么如果这些 URI 发生变化,这可能会很麻烦。
    猜你喜欢
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多