Jersey REST扩展方法 [英] Jersey REST extending methods

查看:142
本文介绍了Jersey REST扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用泽西宁静资源执行以下技巧:

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?

Thx!

推荐答案

使用泽西岛2可以使用 ContainerRequestFilter

With Jersey 2 can use ContainerRequestFilter.

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

    }  
}

我们可以通过 ResourceInfo class

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

这篇关于Jersey REST扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆