Creating filters in JAX-RS

This post explains how to create filters in JAX-RS code. The filters can be placed before and after the web resource.

So we can use the filters for
1) modifying the request
2) restricting certain requests from reaching the webresource
3) modifying the response

In the below code I have created a custom filter, which checks whether each http request has header with key-value pair as “name=value1”.

If it is present the request is authorized and passed to the web resource. If not the request is not authorized and an exception is thrown.

1  package resource;
3  import;
5  import;
6  import;
7  import;
8  import;
9  import;
11 @Provider
12 @PreMatching
13 public class CustomPreMatchingFilter implements ContainerRequestFilter {
14  @Override
15  public void filter(ContainerRequestContext containerRequestContext) throws IOException {
16      String value = containerRequestContext.getHeaderString("name");
17      if((value == null) || (!value.equals("value1"))) {
18          throw new NotAuthorizedException("Not Authorized");
19      }
20  }
21 }

The custom filter class name is “CustomPreMatchingFilter” and implements ContainerRequestFilter class.

The class is annotated with @PreMatching annotation indicating that the filter will be placed before the web resource.

In other words all the request must first go through the filter and then directed to appropriate web resource.

We need to implement the filter method and place our logic. We can get the context information from the parameter containerRequestContext.

The web resource code is as shown below

1  package resource;
3  import;
4  import;
5  import;
6  import;
7  import;
9  @Path("webresource10")
10 public class WebResource10 {
11  @GET
12  @Path("prematching")
13  public Response handle() {
14      Response response = Response.ok("SUCCESS", MediaType.TEXT_PLAIN).build();
15      return response;
16  }
17 }

When the web resource is accessed using the below url and header information containing name=value1, we get the success as response.


Leave a Reply