Get resource class annotation values inside ContainerRequestFilter

后端 未结 1 1896
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 14:51

I\'m struggling a bit with understanding how rest interceptor annotations can add different values that are later visible in the filter. Given the code below I would expect

相关标签:
1条回答
  • 2020-12-03 15:24

    Look at this in your filter

    Class<?> clazz = this.getClass();
    FortressProtected annotation = clazz.getAnnotation(FortressProtected.class);
    

    this.getClass() corresponds to the filter class (whose annotation has no values). You instead need to get the annotation on the ResourceImpl

    A couple options. You could explicitly use ResourceImpl.class.getAnnotation(...). But the problem with this is that once you bind more than one class, how do you match which class corresponds to which request. For that reason, the next option is more viable.

    What you do is inject ResourceInfo. With this, you can call it's getResourceMethod or getResourceClass methods. These methods return the matched method and class, respectively. You could then check for the annotation at the class level as well as the method level (as we are also allowed to bind at the method level). So you might have something more like:

    @Provider
    @FortressProtected
    public class FortressAuthorizer implements ContainerRequestFilter {
    
      @Context
      ResourceInfo resourceInfo;
    
      @Override
      public void filter(ContainerRequestContext requestContext) throws IOException {
    
        Class<?> resourceClass = resourceInfo.getResourceClass();
        FortressProtected classAnnot = resourceClass.getAnnotation(FortressProtected.class);
        if (classAnnot != null) {
          // do something with annotation
        }
    
        Method resourceMethod = resourceInfo.getResourceMethod();
        FortressProtected methodAnnot = resourceMethod.getAnnotation(FortressProtected.class);
        if (methodAnnot != null) {
          // do something with annotation
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题