How to Pass Object from ContainerRequestFilter to Resource

对着背影说爱祢 提交于 2019-12-01 05:52:14

问题


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:


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.



来源:https://stackoverflow.com/questions/31866258/how-to-pass-object-from-containerrequestfilter-to-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!