【问题标题】:Spring RestEasy interceptorSpring RestEasy 拦截器
【发布时间】:2017-02-25 22:41:49
【问题描述】:

我有一个带有 resteasy-spring-3.0.19 和 jboss-jaxrs-api_2.0_spec-1.0.0 的 Spring Boot 应用程序。

我想拦截所有其余的授权调用。

拦截器没有被调用。另外,如何在拦截器中获取目标方法@Path注解值。

我需要在 Spring Boot 应用中注册吗?

@Provider
public class AuthorizationtInterceptor implements ContainerRequestFilter{

    /**
     * 
     */
    public AuthorizationtInterceptor() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        String method = requestContext.getMethod();

        UriInfo uriInfo = requestContext.getUriInfo();

        // Need the target method @Path annotation value ....

    }

}

目标休息类,

@Named
@Singleton
@Path(ROOT_PATH)
public class WebController {

    @GET
    @Path(TEST_PATH)
    @Produces(MediaType.APPLICATION_JSON)
    public Response getUser(@Context final HttpServletRequest request) {
    }
}

【问题讨论】:

    标签: spring spring-mvc resteasy


    【解决方案1】:

    在后匹配过滤器(没有@PreMatching注解的过滤器)中,可以使用ResourceInfo获取匹配的资源类和资源方法。

    使用@Context 注解在您的过滤器中注入ResourceInfo

    @Context
    private ResourceInfo resourceInfo;
    

    然后获取资源类,提取@Path注解:

    Path path = resourceInfo.getResourceClass().getAnnotation(Path.class);
    

    要获取资源方法,请使用:

    Path path = resourceInfo.getResourceMethod().getAnnotation(Path.class);
    

    根据您要实现的目标,您可以考虑将过滤器绑定到一组资源类或方法,而不是比较 @Path 注释的值以进行授权。在answer 中查看更多详细信息。


    根据您设置应用程序的方式,您可能需要在 Application 子类或 web.xml 部署描述符中注册过滤器。

    【讨论】:

    • 它在注册过滤器后被调用,就好像我们在类中使用@Configuration 注解注册了其他过滤器一样。路径 path = resourceInfo.getResourceClass().getAnnotation(Path.class);返回类注解,而不是匹配的方法。我也需要 HttpServletRequest,所以我使用 Context private HttpServletRequest request;。这样可以吗?
    • @user1578872 是的,您可以使用@Context HttpServletRequest request 注入HttpServletRequest。有关可以使用@Context 注入的类型的完整列表,请参阅此answer
    猜你喜欢
    • 1970-01-01
    • 2018-08-09
    • 2014-05-19
    • 1970-01-01
    • 2017-05-17
    • 2015-10-21
    • 2018-03-05
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多