我正在实现一个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());
但这导致了一个例外,说他们可以找到ResponseImpl
的MessageBodyWriter
。也尝试过
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% 正确的,但它似乎有效。