ContainerRequestFilter传递给Resourc

ContainerRequestFilter传递给Resourc

本文介绍了如何将对象从ContainerRequestFilter传递给Resource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何/应该将一个对象从ContainerRequestFilter传递到(JAX-RS)Resteasy版本3.0.11中的(后匹配)资源,该版本已嵌入并使用Guice?

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?

推荐答案

方法存储的值与 HttpServletRequest 同步。因此,使用普通的JAX-RS,您可以存储如下属性:

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();
}

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

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");
    }

}

在您的资源类中:

@Inject
private SomeBean someBean;

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

我希望与Guice一起工作。

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

更新:正如@bakil指出的那样,如果对象是你,你应该使用 @RequestScoped bean想传递只应与当前请求相关联。

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.

这篇关于如何将对象从ContainerRequestFilter传递给Resource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:36