Chapter 12. Filters and Interceptors

Filters and interceptors are objects that are able to interpose themselves on client or server request 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 applied 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 examples.

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 (filter : preMatchFilters) {
   filter.filter(request);
}

jaxrs_method = match(request);

for (filter : postMatchFilters) {
   filter.filter(request);
}

response = jaxrs_method.invoke();

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 ...

Get RESTful Java with JAX-RS 2.0, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.