JAX-RS filters can be used to modify request or response parameters like headers. It can also be used for things like authentication, logging, auditing, data conversion/transformation/compression, localization targeting etc.
To add filters, we need to implement ContainerRequestFilter and/or ContainerResponseFilter, they are individually used for request and response respectively.
For automatic discovery, we should use @Provider annotation on the filters.
By default, request filters are invoked at the point when a resource method has been selected already but has not been called yet. We can change this behavior by using @PreMatching so that a filter will be called before resource matching (next tutorial).
By default, just like all the other providers, a single instance of each Filter is instantiated for each JAX-RS application.
Let's see a quick example how to use filters in JAX-RS
Example
Implementing Filter
@Provider
public class LogFilter implements ContainerRequestFilter, ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext reqContext) throws IOException {
System.out.println("-- req info --");
log(reqContext.getUriInfo(), reqContext.getHeaders());
}
@Override
public void filter(ContainerRequestContext reqContext,
ContainerResponseContext resContext) throws IOException {
System.out.println("-- res info --");
log(reqContext.getUriInfo(), resContext.getHeaders());
}
private void log(UriInfo uriInfo, MultivaluedMap<String, ?> headers) {
System.out.println("Path: " + uriInfo.getPath());
headers.entrySet().forEach(h -> System.out.println(h.getKey() + ": " + h.getValue()));
}
}
A JAX-RS resource
@Path("/")
public class MyResource {
@GET
@Path("{path:.*}")
public String getResponse(@PathParam("path") String path) {
return "dummy-response for " + path;
}
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Output
Using HTTPie to access the resource:
On Server console:
-- req info --
Path: app
host: [localhost:8080]
connection: [keep-alive]
accept-encoding: [gzip, deflate]
accept: [*/*]
user-agent: [HTTPie/0.9.9]
-- res info --
Path: app
Content-Type: [text/plain]
Example ProjectDependencies and Technologies Used: - jersey-server 2.25.1: Jersey core server implementation.
- jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
- JDK 1.8
- Maven 3.3.9
|