Java Reference
In-Depth Information
Chapter 12. Filters and Interceptors
Filters and interceptors are objects that are able to interpose themselves on client or server re-
quest processing. They allow you to encapsulate common behavior that cuts across large
parts of your application. This behavior is usually infrastructure- or protocol-related code
that you don't want to pollute your business logic with. While most JAX-RS features are ap-
plied by application developers, filters and interceptors are targeted more toward middleware
and systems developers. They are also often used to write portable extensions to the JAX-RS
API. This chapter teaches you how to write filters and interceptors using real-world ex-
amples.
Server-Side Filters
On the server side there are two different types of filters:
request filters
and
response filters
.
Request filters execute before a JAX-RS method is invoked. Response filters execute after
the JAX-RS method is finished. By default they are executed for all HTTP requests, but can
be bound to a specific JAX-RS method too. Internally, the algorithm for executing an HTTP
on the server side looks something like this:
for
for
(
filter
:
preMatchFilters
) {
filter
.
filter
(
request
);
}
jaxrs_method
=
match
(
request
);
for
for
(
filter
:
postMatchFilters
) {
filter
.
filter
(
request
);
}
response
=
jaxrs_method
.
invoke
();
for
for
(
filter
:
responseFilters
) {
filter
.
filter
(
request
,
response
);
}
For those of you familiar with the Servlet API, JAX-RS filters are quite different. JAX-RS
breaks up its filters into separate request and response interfaces, while servlet filters wrap
around servlet processing and are run in the same Java call stack. Because JAX-RS has an
asynchronous API, JAX-RS filters cannot run in the same Java call stack. Each request filter
runs to completion before the JAX-RS method is invoked. Each response filter runs to com-
pletion only after a response becomes available to send back to the client. In the asynchron-