Jersey 2 - ContainerRequestFilter get 方法注解

MoS*_*She 4 java rest jax-rs jersey jersey-2.0

我试图获取 ContainerRequestFilter 对象中的方法注释。

控制器:

@GET
@RolesAllowed("ADMIN")
public String message() {
    return "Hello, rest12!";
}
Run Code Online (Sandbox Code Playgroud)

容器请求过滤器:

@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
}
Run Code Online (Sandbox Code Playgroud)

应用 :

@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));

}
Run Code Online (Sandbox Code Playgroud)

}

网页.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>
Run Code Online (Sandbox Code Playgroud)

如何获取 @RolesAllowed("ADMIN") 值,

Pau*_*tha 5

你可以...

注入到您的过滤器中@Context ResourceInfo,如此处所示并从Method

RolesAllowed annot = resourceInfo.getResourceMethod().getAnnotation(RolesAllowed.class);
Run Code Online (Sandbox Code Playgroud)

...

Jersey 已经有一个RolesAllowedDynamicFeature实现注释@RolesAllowed@PermitAll和的访问控制@DenyAll。您只需在您的应用程序中注册该功能

ResourceConfig

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        super(MyResource.class);
        register(RolesAllowedDynamicFeature.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

或者在您的Application子类中,您可以将其添加到您的getSingletons()getClasses()集中。选哪一个并没有多大区别。不会发生注入,因此只需实例化它并将其添加到单例中是安全的。

注意:第一个选项可以在任何 JAX-RS 2.0 应用程序中完成,而第二个选项是 Jersey 特定的。