Jersey REST extending methods

家住魔仙堡 提交于 2020-01-10 05:32:09

问题


I was wondering if it is possible to do the following trick with jersey restful resources:

I have an example jersey resource:

@Path("/example")
public class ExampleRessource {


  @GET
  @Path("/test")
  @CustomPermissions({"foo","bar"})
  public Response doStuff() {
    //implicit call to checkPermissions(new String[] {"foo","bar"}) 

  }  

  private void checkPermissions(String[] permissions) {
    //stuff happens here
  }

}

What I want to achieve is: before executing each resource's method to implicitly check the rights from the annotation by calling the checkPermissions method without actually writing the call inside the method body. Kind of "decorating" each jersey method inside this resource.

Is there an elegant solution? For example with jersey Provider?

Thx!


回答1:


With Jersey 2 can use ContainerRequestFilter.

@Provider
public class CheckPermissionsRequestFilter 
                                     implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext crc) throws IOException {

    }  
}

We can get the annotation on the called method through the ResourceInfo class

@Context
private ResourceInfo info;

@Override
public void filter(ContainerRequestContext crc) throws IOException {
    Method method = info.getResourceMethod();
    CheckPermissions annotation = method.getAnnotation(CheckPermissions.class);
    if (annotation != null) {
        String[] permissions = annotation.value();
    }
} 

You can use this annotation

@NameBinding
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckPermissions {
    String[] value();
}

And annotate the resource class or the resource method with @CheckPermissions({...})


  • See more at Filters and Interceptors

UPDATE

The annotation above allows for annotating classes also. Just for completeness, you'll want to check the class also. Something like

Class resourceClass = info.getResourceClass();
CheckPermissions checkPermissions = resourceClass.getAnnotation(CheckPermissions.class);
if (checkPermissions != null) {
   String[] persmission = checkPermissions.value();
}


来源:https://stackoverflow.com/questions/27862594/jersey-rest-extending-methods

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