Close

JAX-RS - Interceptors

[Updated: Aug 1, 2017, Created: Jul 28, 2017]

A JAX-RS interceptor is used to manipulate the message body (entity), by intercepting input/output streams.

To add interceptors, we need to implement ReaderInterceptor and/or WriterInterceptor, they are individually used for request and response respectively.

For automatic discovery, we should use @Provider annotation on the interceptors.

Let's see a quick example how to use interceptors in JAX-RS

Example

Implementing Filter

@Provider
public class MyInterceptor implements WriterInterceptor, ReaderInterceptor {

  @Override
  public Object aroundReadFrom(ReaderInterceptorContext context)
          throws IOException, WebApplicationException {
      System.out.println("-- in MyInterceptor#aroundReadFrom() --");
      System.out.println("request message body:");
      InputStream is = context.getInputStream();
      String body = new Scanner(is, "UTF-8").useDelimiter("\\A").next();
      System.out.println(body);
      context.setInputStream(new ByteArrayInputStream(
              (body+"\nMy appended message in request body.\n").getBytes()));
      Object result = context.proceed();
      return result;
  }

  @Override
  public void aroundWriteTo(WriterInterceptorContext context)
          throws IOException, WebApplicationException {
      System.out.println("-- in MyInterceptor#aroundWriteTo() --");
      OutputStream os = context.getOutputStream();
      os.write("My output message.\n".getBytes());
      context.proceed();
  }
}

A JAX-RS resource

@Path("/")
public class MyResource {

  @POST
  @Path("{path:.*}")
  public String getResponse(@PathParam("path") String path, String entity) {
      System.out.println("-- In the resource method, getResponse() --");
      System.out.println("request message body: "+entity);
      return "dummy-response for " + path;
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

The Client

public class MyClient {
  public static void main(String[] args) {
      Client client = ClientBuilder.newClient();
      WebTarget target = client.target("http://localhost:8080/app");
      String response = target.request().post(Entity.text("my test request body"), String.class);
      System.out.println(response);
  }
}

Output

My output message.
dummy-response for app

Output On Server console

-- in MyInterceptor#aroundReadFrom() --
request message body:
my test request body
-- In the resource method, getResponse() --
request message body: my test request body
My appended message in request body.

-- in MyInterceptor#aroundWriteTo() --

Other Features of Interceptors

Similar to Filters, we can do the followings with Interceptor:

Overall Execution Order

Following is the overall order of filters and interceptors on the server side:

ClientThe Server receives the requestRequest Filters
Reader InterceptorsMessageBodyReaderThe Resource method Invocation
Response FiltersWriter InterceptorsMessageBodyWriter
Server dispatches the responseClient

Example Project

Dependencies 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

JAX-RS Filter Example Select All Download
  • interceptor-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also