Jersey REST 扩展方法

2022-01-21 00:00:00 rest java jax-rs jersey webresource

我想知道是否可以使用 jersey restful 资源执行以下技巧:

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
  }

}

我想要实现的是:在执行每个资源的方法之前,通过调用 checkPermissions 方法来隐式检查注解中的权限,而无需在方法体中实际编写调用.有点装饰"这个资源中的每个球衣方法.

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?

谢谢!

推荐答案

搭配 Jersey 2 可以使用 ContainerRequestFilter.

With Jersey 2 can use ContainerRequestFilter.

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

    }  
}

我们可以通过ResourceInfo

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

你可以使用这个注解

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

并用@CheckPermissions({...})注释资源类或资源方法

  • 在 过滤器和拦截器
  • See more at Filters and Interceptors

上面的注释也允许注释类.为了完整起见,您还需要检查课程.类似的东西

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

相关文章