Injecting a custom response header in RESTEasy JAX-RS
I have RESTEasy (JAX-RS) server with about 60 services (so far). I would like to 开发者_开发问答automatically inject a custom response header to provider callers with the server build time: X-BuildTime: 20100335.1130
.
Is there an easy way to do this without modifying each of my services?
I am trying to use a class that implements org.jboss.resteasy.spi.interception.PostProcessInterceptor
with annotations @Provider
and @ServerInterceptor
, but I can't figure out how to modify the ServerResponse that is passed into my postProcess()
method.
Although MessageBodyWriterInterceptor
does the trick, it is better to use PostProcessInterceptor
, as it will intercept responses that do not call MessageBodyWriters (such as Response.created(URI.create("/rest/justcreated")).build()
).
For more info, see the official documentation.
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;
import org.jboss.resteasy.annotations.interception.ServerInterceptor;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
@Provider
@ServerInterceptor
public class MyPostProcessInterceptor implements PostProcessInterceptor {
@Override
public void postProcess(ServerResponse response) {
MultivaluedMap<String, Object> headers = response.getMetadata();
List<Object> domains = headers.get("X-BuildTime");
if (domains == null) { domains = new ArrayList<Object>(); }
domains.add("20100335.1130");
headers.put("X-BuildTime", domains);
}
}
I think using javax.servlet.Filter
will be a much easier solution:
public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse)response;
httpResponse.setHeadder(header, headerValue);
chain.doFilter(request, response);
}
configure it in web.xml for the relevant urls, and you are done.
How about using javax.ws.rs.core.Response ; this way you can set the header in the same place where you create the response-data.
@GET
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public Response test( ){
HashMap<String,String> ret = new HashMap<String,String>();
ret.put("foo","bar");
return Response
.status(Response.Status.OK)
.entity(ret)
.header("X-say", "Hello world!")
.build();
}
You can also change header by MessageBodyInterceptors
( check the example at the end of section 30.1 )
@Provider
@ServerInterceptor
public class MyHeaderDecorator implements MessageBodyWriterInterceptor {
public void write(MessageBodyWriterContext context) throws IOException, WebApplicationException
{
context.getHeaders().add("My-Header", "custom");
context.proceed();
}
}
精彩评论