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?
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.