更新时间:2023-11-09 23:26:52
方法 ContainerRequestContext#setProperty 存储的值与 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.