Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

java - Jersey REST extending methods

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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({...})



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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...