Set JAX-RS response headers in implementation with

2019-01-20 13:12发布

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?

3条回答
姐就是有狂的资本
2楼-- · 2019-01-20 13:16

So injecting HttpServletResponse seems like a no go. Only certain proxy-able types are inject-able into singletons. I believe the complete list is as follows:

HttpHeaders, Request, UriInfo, SecurityContext

This is somewhat pointed out in the JAX-RS spec, but is explained more clearly in the Jersey reference guide

The exception exists for specific request objects which can injected even into constructor or class fields. For these objects the runtime will inject proxies which are able to simultaneously server more request. These request objects are HttpHeaders, Request, UriInfo, SecurityContext. These proxies can be injected using the @Context annotation.

SecurityContext may be Jersey specific, as it's not stated in the spec, but I'm not sure.

Now those types mentioned above don't really do much for you because they are all request contexts and nothing to set the response.

One Idea though is to use a javax.ws.rs.container.ContainerResponseFilter, along with the HttpHeaders to set a temporary request header. You can access that header through the ContainerRequestContext passed to the filter method. Then just set the response header through the ContainerResponseContext, also passed to the filter method. If the the header is not specific to the context of that resource method, then it's even easier. Just set the header in the filter.

But let's say the header is dependent on the execution of the resource method. Then you could do something like

@Singleton
@Path("/singleton")
public class SingletonResource {

    @Context
    javax.ws.rs.core.HttpHeaders headers;

    @GET
    public String getHello() {

        String result = resultFromSomeCondition(new Object());
        headers.getRequestHeaders().putSingle("X-HELLO", result);
        return "Hello World";
    }

    private String resultFromSomeCondition(Object condition) {
        return "World";
    }
}

Then the ContainerResponseFilter might look something like this

@Provider
public class SingletonContainerResponseFilter 
                            implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext crc, 
            ContainerResponseContext crc1) throws IOException {
        String header = crc.getHeaderString("X-HELLO");
        crc1.getHeaders().putSingle("X-HELLO", "World");
    } 
}

And just so only the singleton classes run through this filter, we can simply use a @NameBinding annotation

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.ws.rs.NameBinding;

@NameBinding
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SingletonHeader {}

...

@SingletonHeader
public class SingletonResource {

...

@SingletonHeader
public class SingletonContainerResponseFilter 
                        implements ContainerResponseFilter {

This is the only way I can think to handle this situation.


Resources:

查看更多
戒情不戒烟
3楼-- · 2019-01-20 13:28

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.

查看更多
Luminary・发光体
4楼-- · 2019-01-20 13:39
@Path("/foo")
public interface FooResource {

    @GET
    @Path("{id}")
    public Response getBar(@PathParam("id") int id) {
        Bar bar = new Bar();
        //Do some logic on bar
        return Response.ok().entity(bar).header("header-name", "header-value").build()
    }
}

Returns a JSON representation of the instance of bar with a status code 200 and header header-name with value header-value. It should look something along the lines of:

{
    "bar-field": "bar-field-value",
    "bar-field-2": "bar-field-2"
}
查看更多
登录 后发表回答