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;
2  
3  import java.io.IOException;
4  
5  import javax.ws.rs.NotAuthorizedException;
6  import javax.ws.rs.container.ContainerRequestContext;
7  import javax.ws.rs.container.ContainerRequestFilter;
8  import javax.ws.rs.container.PreMatching;
9  import javax.ws.rs.ext.Provider;
10 
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;
2  
3  import javax.ws.rs.GET;
4  import javax.ws.rs.Path;
5  import javax.ws.rs.QueryParam;
6  import javax.ws.rs.core.MediaType;
7  import javax.ws.rs.core.Response;
8  
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.

http://localhost:8080/JAXRSConcepts/myresources/webresource10/prematching

Leave a Reply