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

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

问题描述

我想知道是否可以使用 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();
}

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

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