O'Reilly logo

RESTful Java with JAX-RS 2.0, 2nd Edition by Bill Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required