Set JAX-RS response headers in implementation without exposing HttpServletResponse in interface
httpresponse, java, jax-rs, rest
Solution
The correct answer seems to be to inject an `HttpServletResponse` in the member variable of the implementation, as I noted that another post had indicated.
@Context //injected response proxy supporting multiple threads
private HttpServletResponse servletResponse;
Even though peeskillet indicated that the semi-official list for Jersey doesn't list `HttpServletResponse` as one of the proxy-able types, when I traced through the code at least RESTEasy seems to be creating a proxy (`org.jboss.resteasy.core.ContextParameterInjector$GenericDelegatingProxy@xxxxxxxx`). So as far as I can tell, thread-safe injection of a singleton member variable seems to be occurring.
See also https://stackoverflow.com/a/10076327/421049 .
Problem
I have a RESTful server implementation as well as a library for clients to make the calls, all using JAX-RS. The server components are divided up into interface `FooResource` and implementation `FooResourceService`. In order for the client and server libraries to share RESTful path and other definitions, I wanted to split out the `FooResource` interface into its own project: ``` @Path(value = "foo") public interface FooResource { @GET public Bar getBar(@PathParam(value = "{id}") int id) { ``` I want to set some headers in the response. One easy way to do this is to use `@Context HttpServletResponse` in the method signature: ``` public Bar getBar(@PathParam(value = "{id}") int id, @Context HttpServletResponse servletResponse) { ``` But the problem is that this exposes implementation details in the interface. More specifically, it suddenly requires my REST definition project (which is shared between the client and server library) to pull in the `javax.servlet-api` dependency---something the client has no need up (or desire for). How can my RESTful resource service implementation set HTTP response headers without pulling in that dependency in the resource interface? I saw one post recommending I inject the HttpServletResponse as a class member. But how would this work if my resource service implementation is a singleton? Does it use some sort of proxy with thread locals or something that figures out the correct servlet response even though the singleton class is used simultaneously by multiple threads? Are there any other solutions?