How to Pass Object from ContainerRequestFilter to Resource

后端 未结 1 1800
予麋鹿
予麋鹿 2021-01-14 17:28

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条回答
  • 2021-01-14 18:07

    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.

    0 讨论(0)
提交回复
热议问题