gpt4 book ai didi

java - Jersey 2 - ContainerRequestFilter 获取方法注解

转载 作者:行者123 更新时间:2023-12-01 14:14:53 37 4
gpt4 key购买 nike

我正在尝试获取 ContainerRequestFilter 对象中的方法注释。

Controller :

@GET
@RolesAllowed("ADMIN")
public String message() {
return "Hello, rest12!";
}

容器请求过滤器:

@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") 值,

最佳答案

你可以...

注入(inject)过滤器@Context ResourceInfo,如here所示,并从 Method

获取注解
RolesAllowed annot = resourceInfo.getResourceMethod().getAnnotation(RolesAllowed.class);

但是...

Jersey 已经有一个 RolesAllowedDynamicFeature实现对注解@RolesAllowed@PermitAll@DenyAll 的访问控制。你只需要 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() 集合中。哪个没有太大区别。不会发生注入(inject),因此只需实例化它并将其添加到单例中是安全的。

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

关于java - Jersey 2 - ContainerRequestFilter 获取方法注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31974857/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com