Download Jersey 2.10 User Guide
Transcript
Chapter 9. Filters and Interceptors
9.1. Introduction
This chapter describes filters, interceptors and their configuration. Filters and interceptors can be used
on both sides, on the client and the server side. Filters can modify inbound and outbound requests and
responses including modification of headers, entity and other request/response parameters. Interceptors are
used primarily for modification of entity input and output streams. You can use interceptors for example
to zip and unzip output and input entity streams.
9.2. Filters
Filters can be used when you want to modify any request or response parameters like headers. For example
you would like to add a response header "X-Powered-By" to each generated response. Instead of adding
this header in each resource method you would use a response filter to add this header.
There are filters on the server side and the client side.
Server filters:
ContainerRequestFilter
ContainerRequestFilter.html]
ContainerResponseFilter
ContainerResponseFilter.html]
Client filters:
ClientResponseFilter
ClientResponseFilter.html]
ClientResponseFilter
ClientResponseFilter.html]
[http://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/container/
[http://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/container/
[http://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/client/
[http://jax-rs-spec.java.net/nonav/2.0/apidocs/javax/ws/rs/client/
9.2.1. Server filters
The following example shows a simple container response filter adding a header to each response.
Example 9.1. Container response filter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import
import
import
import
import
java.io.IOException;
javax.ws.rs.container.ContainerRequestContext;
javax.ws.rs.container.ContainerResponseContext;
javax.ws.rs.container.ContainerResponseFilter;
javax.ws.rs.core.Response;
public class PoweredByResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerRespons
throws IOException {
responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
}
}
129