3

I have a Jersey 1.8 application running. Jersey is running as a Servlet.

I need to write a servlet filter that given a plain request/response, is able to figure out which REST resource/method will respond to the request and extract values from annotations.

For example, imagine I have the following resource:

@Path("/foo")
@MyAnnotation("hello")
public class FooResource {
   @GET
   @Path("/bar")
   @MyOtherAnnotation("world")
   public Response bar(){ 
      ... 
   }
}

When a request GET /foo/bar comes in, I need my servlet filter to be able to extract the values "hello" and "world" from MyAnnotation and MyOtherAnnotation before Jersey's own servlet processes the request.

This filter logic should be able to work for all requests and all resources registered.

Is there a way to access Jersey's internal routing mechanism to obtain a class/method reference where Jersey will dispatch the request?

I'm open to other suggestions as well, but ideally nothing like trying to hack my own routing mechanism by reading the @Path annotations myself.

Alejandro
  • 635
  • 1
  • 6
  • 16

1 Answers1

1
@Provider
@Priority(Priorities.AUTHORIZATION)
public class MyFilter implements ContainerRequestFilter
    @Context // request scoped proxy
    private ResourceInfo resourceInfo;

   @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        if (resourceInfo.getResourceClass().isAnnotationPresent(MyAnnotationion.class) ||
            resourceInfo.getResourceMethod().isAnnotationPresent(MyOtherAnnotation.class)) {

to register the filter use

bind(AuthFilter.class).to(ContainerRequestFilter.class).in(Singleton.class);
xeye
  • 1,250
  • 10
  • 15
  • Thanks, but this is a JAXRS filter. What i have to use is a servlet filter (implementing `doFilter(ServletRequest request, ServletResponse response, FilterChain chain)`) and from there, somehow obtain a reference to the resource class and method. Any idea how to do that? – Alejandro Aug 05 '15 at 17:33
  • 1
    you're almost going to implement another jersey in your filter :) may be just upgrade to Jersey2? – xeye Aug 05 '15 at 20:37
  • another way is to use class instrumentation. basically, attach an aspect to every resource method. – xeye Aug 05 '15 at 21:33
  • The issue is that this I'm working on a enterprise legacy framework that requires an identifier for the URI being requested to be provided (for monitoring reasons) BEFORE the request is handed over to the Jersey application. Changing/upgrading isn't an option here, so in order to avoid re-inventing the wheel, i wanted to see if Jersey could come to the rescue by using the routing component by itself and centralize URI-specific data in the resource. This seems not feasible, so i'll accept defeat and implement something else. – Alejandro Aug 06 '15 at 05:27