Tuesday, April 30, 2013

Jersey Resource Filter example

  1. Create Filter class by implementing ResourceFilter and ContainerRequestFilter interfaces.
public class TestFilterFirst implements ResourceFilter, ContainerRequestFilter {

	@Context HttpServletRequest request;
	@Context HttpServletResponse response;
	
	@Override
	public ContainerRequest filter(ContainerRequest arg0) {
		//Filter logic goes here.
		return arg0;
	}

	@Override
	public ContainerRequestFilter getRequestFilter() {
		return this;
	}

	@Override
	public ContainerResponseFilter getResponseFilter() {
		return null;
	}
	
}

2.  Create Rest Service Class

@Path("/helloworld")
public class TestJersey {

	@GET
	@Produces("text/plain")
	@ResourceFilters({ TestFilterFirst.class })
	public String sayHello() {
		System.out.println("Hello");
		return "Hello World";
	}
}

Notice ResourceFilters Annotation. multiple classes can be added here as comma separated. Each class added here will be configured as filter to this service.

No specific configuration is required in web.xml to add filters if you are using ResourceFilters annotation.


 

2 comments:

  1. I'm trying to find a way to use the @Context param in the filter as you have done above, but instead use the FilterFactory that gets initialized in the web.xml. The @Context parameters keep ending up null and I can't figure out why they aren't getting injected when included in the filter. The work around I found was to add the @Context parameters in the FilterFactory and then initialize them in the filter using a setter. The filter is a singleton and is used across all the resources. Why can't I use the @Context param in the filters? It must have something to do with only resources having that information.

    In the example you gave you are including @Context params in the filter, but I can only assume it works because you are also including the @ResourceFilters annotation in the Resource class.

    Any ideas?

    ReplyDelete
  2. how to you access arg0 from the Rest Service class?

    ReplyDelete