JAX-RS - PreMatching Filters

[Last Updated: 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.


Implementing Filter

public class RedirectFilter implements ContainerRequestFilter {

  public void filter(ContainerRequestContext reqContext) throws IOException {

      // redirect conditionally
      if (shouldRedirect(reqContext)) {

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

A JAX-RS resource

public class MyResource {

  public String getResponse() {
      return "dummy-response from /app";

  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


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(
	at com.logicbig.example.RedirectFilter.filter(

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