Java Reference
In-Depth Information
Generally, you use these types of filters to decorate the response by adding or modifying re-
sponse headers. One example is if you wanted to set a default Cache-Control header for
each response to a GET request. Here's what it might look like:
import
import javax.ws.rs.container.ContainerResponseFilter
javax.ws.rs.container.ContainerResponseFilter ;
import
import javax.ws.rs.container.ContainerRequestContext
javax.ws.rs.container.ContainerRequestContext ;
import
import javax.ws.rs.container.ContainerResponseContext
javax.ws.rs.container.ContainerResponseContext ;
import
import javax.ws.rs.core.CacheControl
javax.ws.rs.core.CacheControl ;
@Provider
public
public class
class CacheControlFilter
CacheControlFilter implements
implements ContainerResponseFilter {
public
public void
void filter ( ContainerRequestContext req , ContainerResponseContext res )
throws
throws IOException
{
iif ( req . getMethod (). equals ( "GET" )) {
CacheControl cc = new
new CacheControl ();
cc . setMaxAge ( 100 );
req . getHeaders (). add ( "Cache-Control" , cc );
}
}
}
The ContainerResponseFilter.filter() method has two parameters. The Container-
RequestContext parameter gives you access to information about the request. Here we're
checking to see if the request was a GET. The ContainerResponseContext parameter al-
lows you to view, add, and modify the response before it is marshalled and sent back to the
client. In the example, we use the ContainerResponseContext to set a Cache-Control re-
sponse header.
Reader and Writer Interceptors
While filters modify request or response headers, reader and writer interceptors deal with
message bodies. They work in conjunction with a MessageBodyReader or Mes-
sageBodyWriter and are usable on both the client and server. Reader interceptors implement
the ReaderInterceptor interface. Writer interceptors implement the WriterInterceptor
interface.
package
package javax . ws . rs . ext ;
public
public interface
interface ReaderInterceptor
ReaderInterceptor {
public
public Object aroundReadFrom ( ReaderInterceptorContext context )
throws
throws java . io . IOException , javax . ws . rs . WebApplicationException ;
}
Search WWH ::




Custom Search