How to use Jersey's internal routing mechanism to extract a class/method reference?

拥有回忆 提交于 2020-01-01 06:33:08

问题


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.


回答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);


来源:https://stackoverflow.com/questions/31757458/how-to-use-jerseys-internal-routing-mechanism-to-extract-a-class-method-referen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!