Friday, September 23, 2011

Writing custom filter for jersey


If we want to intercept all the request coming to jersey controller. For example if we want to check if user is authenticated before each request, we will do this in each method. So to achieve this functionality we would prefer writing a filter, which will intercept each request and check for authentication.

Writing a filter:
We need to implement ContainerRequestFilter interface for creating Jersey filter. Following is the code sample for intercepting and modifying a request using jersey filter:



import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.log4j.Logger;
/**
 *
 * @author arnav
 */
public class MyAppFilter implements ContainerRequestFilter{


   public ContainerRequest filter(ContainerRequest request) {

      MultivaluedMap<String, String> headers = request.getRequestHeaders();

      headers.add("code", "MY_APP_CODE");
      request.setHeaders((InBoundHeaders)headers);

      return request;
   }
}

In the above class, I have intercepted the request and added a "code" into HTTP Header.


After adding this class, we need to register this filter for our web application. So now we will add following lines in our web.xml:



    
        Jersey Spring Web Application
        com.sun.jersey.spi.spring.container.servlet.SpringServlet
      
         com.sun.jersey.spi.container.ContainerRequestFilters
         package.MyAppFilter
              
    
@GET
	@Produces("application/xml")
	public PersonList getIt(@HeaderParam("code") String code) {

		System.out.println(code);
	}
This will have access to the "code", we have set in our MyAppFilter class.

4 comments:

  1. Thanks. This really helped in setting up logging filter for jersey app.

    ReplyDelete
  2. Good example..simple and effective. Thanks!

    ReplyDelete
  3. How can you register your filter without editing the web.xml file?

    ReplyDelete