如何将对象从 ContainerRequestFilter 传递到资源

How to Pass Object from ContainerRequestFilter to Resource

我如何can/should将对象从 ContainerRequestFilter 传递到 (JAX-RS) Resteasy 版本 3.0.11 中的(post-匹配)资源,该版本嵌入了 undertow 并使用了 Guice?

方法 ContainerRequestContext#setProperty 存储与 HttpServletRequest 同步的值。因此,使用普通的 JAX-RS,您可以存储这样的属性:

@Provider
public class SomeFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        requestContext.setProperty("someProperty", "someValue");
    }

}

之后你可以在你的资源中获取它class:

@GET
public Response someMethod(@Context org.jboss.resteasy.spi.HttpRequest request) {
    return Response.ok(request.getAttribute("someProperty")).build();
}

使用 CDI,您还可以在过滤器和资源中注入任何 bean class:

@Provider
public class SomeFilter implements ContainerRequestFilter {

    @Inject
    private SomeBean someBean;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        someBean.setFoo("bar");
    }

}

在您的资源中 class:

@Inject
private SomeBean someBean;

@GET
public Response someMethod() {
    return Response.ok(someBean.getFoo()).build();
}

我希望与 Guice 一起工作。

Update:正如@bakil 正确指出的那样,如果您要传递的对象只应与当前请求相关联,则您应该使用 @RequestScoped bean。