JAXRS-2.0 过滤器:如何添加指向 ContainerResponse 的链接



我正在实现一个ContainerResponseFilter,它将向响应添加超媒体链接。

ContainerResponseFilter中的方法签名为:

public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException

不幸的是,ContainerResponseContext不允许我设置Response对象,虽然有getLinks()方法,但没有addLink(Link)setLinks(Link...)方法。

我试过了

responseContext.setEntity(Response.ok().links(link).build());

但这导致了一个例外,说他们可以找到ResponseImplMessageBodyWriter。也尝试过

responseContext.getLinks().add(link);

这也行不通。

有人这样做过吗?

你应该注入:

@Context HttpServletResponse r;

作为本地字段。所有更改都应通过那里完成。

所以我找到了一种方法来做到这一点,通过替换实体:

URI uri = uriInfo.getBaseUriBuilder().path(RESOURCE_CLASS).path(RESOURCE_METHOD).build(domain_object.getId());
JaxbLink jaxbLink = new JaxbLink(uri);
responseContext.setEntity(jaxbLink);

不确定这是 100% 正确的,但它似乎有效。

相关内容

  • 没有找到相关文章

最新更新