JAX-RS - PreMatching Filters

[Updated: Jul 17, 2017, Created: Jul 17, 2017]

In JAX-Rs, filters can be divided into two categories: pre-matching filters and post-matching filters.

A post-matching filter is applied only after a suitable resource method has been selected to process the request. Such filters can not influence the resource method matching process. We have seen such filter example in the last tutorial.

A pre-matching filter (annotated with @RequestMatching) is executed before the request matching process is started. This filter can influence which resource method will be matched e.g. by changing the HTTP method or by changing the URI etc.

Note that resource matching is the process of finding a resource method that should be executed based on the request path and other request parameters.

Let's see an example how to use pre-Matching filter.

Example

Implementing Filter

@Provider
@PreMatching
public class RedirectFilter implements ContainerRequestFilter {

  @Override
  public void filter(ContainerRequestContext reqContext) throws IOException {

      // redirect conditionally
      if (shouldRedirect(reqContext)) {
          reqContext.setRequestUri(URI.create("/temp"));
      }
  }

  private boolean shouldRedirect(ContainerRequestContext reqContext) {
      //todo it should be conditional return
      return true;
  }
}

A JAX-RS resource

@Path("/")
public class MyResource {

  @GET
  @Path("/app")
  public String getResponse() {
      return "dummy-response from /app";
  }

  @GET
  @Path("/temp")
  public String getTempResponse() {
      return "dummy-response from /temp";
  }
}

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:

As seen in the output body, the request URI '/app' has been redirected to '/temp' successfully.

Note that, if we don't use @PreMatching on our filter and still attempt to change the URI, we will have following exception:

java.lang.IllegalStateException: Method could be called only in pre-matching request filter.
	at org.glassfish.jersey.server.ContainerRequest.setRequestUri(ContainerRequest.java:412)
	at com.logicbig.example.RedirectFilter.filter(RedirectFilter.java:19)

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
  • filter-pre-matching-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also