Setting response header using interceptor?

2.9k views Asked by At

I'm writing jax-rs end points. For some set of end points (existing code), I want to set an extra response header which was actually generated in @AroundInvoke interceptor and set to HttpServletRequest attribute. In @AroundInvoke I'm able to access HttpServletRequest using @Inject. But it seems I cannot access HttpServletResponse in the same interceptor itself.

It seems I can do with PostProcessorInterceptor but again I'm confused with the following doc.

The org.jboss.resteasy.spi.interception.PostProcessInterceptor runs after the JAX-RS method was invoked but before MessageBodyWriters are invoked. They can only be used on the server side. Use them if you need to set a response header when there might not be any MessageBodyWriter invoked.

I'm using resteasy, jackson. If I use PostProcessorInterceptor can I inject HttpServletResponse? Or Can I set new http header there some how?

Any code example/direction would be appreciated.

1

There are 1 answers

4
Max Fichtelmann On BEST ANSWER

With JaxRS 2 (which comes with javaEE 7) you can use a ContainerResponseFilter see also

public class PoweredByResponseFilter implements ContainerResponseFilter {

    @Inject
    HttpServletRequest request;

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {
            String name = "X-My-Header";
            String value = "";// some data from request
            responseContext.getHeaders().add(name, value);
    }
}