Jersey REST extending methods

时间秒杀一切 提交于 2019-11-29 15:59:18

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