泽西岛2-ContainerRequestFilter获取方法注释 [英] Jersey 2 - ContainerRequestFilter get method annotation
问题描述
我正在尝试在ContainerRequestFilter对象中获取方法注释.
Im trying to get the Method annotation in ContainerRequestFilter object.
控制者:
@GET
@RolesAllowed("ADMIN")
public String message() {
return "Hello, rest12!";
}
ContainerRequestFilter:
@Provider
public class SecurityInterceptor implements javax.ws.rs.container.ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext) {
//Here I need To get the @RolesAllowed("ADMIN") annotation value
}
应用程序:
@ApplicationPath("/rest")
public class ExpertApp extends Application {
private final HashSet<Object> singletons = new LinkedHashSet<Object>();
public ExpertApp() {
singletons.add(new SecurityInterceptor());
}
@Override
public Set<Object> getSingletons() {
return singletons;
}
public Set<Class<?>> getClasses() {
return new HashSet<Class<?>>(Arrays.asList(UserControler.class, SearchController.class));
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- Servlet declaration can be omitted in which case it would be automatically
added by Jersey -->
<servlet>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>javax.ws.rs.core.Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
如何设置@RolesAllowed("ADMIN")值,
How do I ge the @RolesAllowed("ADMIN") value,
推荐答案
您可以 ...
如此处所示,注入到过滤器@Context ResourceInfo
中,并从Method
获取注释.>
You could...
Inject into your filter @Context ResourceInfo
, as seen here, and get the annotation from the Method
RolesAllowed annot = resourceInfo.getResourceMethod().getAnnotation(RolesAllowed.class);
但是 ...
Jersey已经具有在您的应用程序中注册该功能
But...
Jersey already has a RolesAllowedDynamicFeature
that implements the access control for the annotations @RolesAllowed
, @PermitAll
and @DenyAll
. You just need to register the feature with your application
在ResourceConfig
public class MyApplication extends ResourceConfig {
public MyApplication() {
super(MyResource.class);
register(RolesAllowedDynamicFeature.class);
}
}
在web.xml
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>
org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature
</param-value>
</init-param>
或者在您的Application
子类中,可以将其添加到您的getSingletons()
或getClasses()
集中.哪一个没有多大区别.没有注入发生,因此将其实例化并将其添加到单例中将是安全的.
Or in your Application
subclass, you can add it to your getSingletons()
or getClasses()
set. Doesn't make much difference which one. No injections occur, so it would be safe to just instantiate it and add it to the singletons.
注意:第一个选项可以在任何JAX-RS 2.0应用程序中完成,而第二个则是针对Jersey的.
Note: The first option can be done in any JAX-RS 2.0 application, while the second is Jersey specific.
这篇关于泽西岛2-ContainerRequestFilter获取方法注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!