简体   繁体   中英

JAXRS-2.0 Filter: How does one add links to ContainerResponse

I'm implementing a ContainerResponseFilter that would add hypermedia links to the response.

The method signature in the ContainerResponseFilter is:

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

Unfortunately ContainerResponseContext does not allow me to set a Response object, and while there are getLinks() methods, there are not addLink(Link) or setLinks(Link...) methods.

I tried

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

but that resulted in an exception that said they could find a MessageBodyWriter for ResponseImpl . Also tried

responseContext.getLinks().add(link);

which doesn not work either.

Anyone ever done this?

You should inject:

@Context HttpServletResponse r;

as a local field. All changes should be done through there.

So I found a way to do this, by replacing the entity:

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

Not certain this is a 100% correct, but it seems to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM