How to Pass Object from ContainerRequestFilter to

2019-02-19 04:30发布

How can/should I pass an object from a ContainerRequestFilter to a (post-matching) resource in (JAX-RS) Resteasy version 3.0.11 that has undertow embedded and uses Guice?

1条回答
迷人小祖宗
2楼-- · 2019-02-19 05:33

The method ContainerRequestContext#setProperty stores values which are synced with the HttpServletRequest. So with plain JAX-RS you can store an attribute like this:

@Provider
public class SomeFilter implements ContainerRequestFilter {

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

}

And afterwards you can obtain it in your resource class:

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

With CDI you also can inject any bean in the filter and resource class:

@Provider
public class SomeFilter implements ContainerRequestFilter {

    @Inject
    private SomeBean someBean;

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

}

In your resource class:

@Inject
private SomeBean someBean;

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

I'd expect the same to be working with Guice.

Update: As @bakil pointed out correctly you should use a @RequestScoped bean if the object you want to pass should only be associated with the current request.

查看更多
登录 后发表回答