Jersey REST extending methods(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 扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Jersey REST 扩展方法
基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01