JBoss.orgCommunity Documentation

Chapter 2. Filters and Interceptors

Interceptors are another facility from Resteasy 2 that now appear in JAX-RS 2.0 but in a rather different form. There were four kinds of interceptors in Resteasy 2:

  1. reader/writer interceptors
  2. server side PreProcessInterceptor
  3. server side PostProcessInterceptor
  4. ClientExecutionInterceptor

Of these, reader/writer interceptors, which wrap around the reading or writing of entities, carry over essentially unchanged, except for class and method names. javax.ws.rs.ext.ReaderInterceptor and javax.ws.rs.ext.WriterInterceptor replace the old MessageBodyReaderInterceptor and MessageBodyWriterInterceptor.

The two kinds of server side interceptors are replaced by filters, which behave similarly. There are four kinds of filters:

  1. ContainerRequestFilter
  2. ContainerResponseFilter
  3. ClientRequestFilter
  4. ClientResponseFilter

Like the old PreProcessInterceptors, ContainerRequestFilters can access requests. A

public interface PreProcessInterceptor
{
   ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws Failure, WebApplicationException;
}
   

can modify the HttpRequest and then return a response or null. If it returns a response, then the execution process is interrupted and that response is returned. Similarly, a new

public interface ContainerRequestFilter
{
    public void filter(ContainerRequestContext requestContext) throws IOException;
}
   

can access and modify a JAX-RS Request by calling ContainerRequestContext.getRequest(), and it can supply a response by calling ContainerRequestContext.abortWith(Response).

An old

public interface PostProcessInterceptor
{
   void postProcess(ServerResponse response);
}
   

can modify the response, as can a new

public interface ContainerResponseFilter
{
   public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException;
}
   

by calling, for example, ContainerResponseContext.setStatus() or ContainerResponseContext.setEntity().

The situation is somewhat different with the old ClientExecutionInterceptor. Unlike PreProcessInterceptor and PreProcessInterceptor, this one really wraps the invocation process on the client side. That is, it can examine and/or modify the request and return by calling ClientRequestContext.abortWith(Response), or proceed with the invocation and examine and/or modify the response. Two client side filters, ClientRequestFilter and ClientResponseFilter, are required to replace the functionality of ClientExecutionInterceptor. The former can access the request, and the latter can access both the request and response.