简体   繁体   English

如何检索Jersey ContainerRequest属性?

[英]How to retrieve Jersey ContainerRequest properties?

I have a Java 1.6 web app in Tomcat with a REST api using Jersey 1.x. 我在Tomcat中有一个Java 1.6 Web应用程序,带有一个使用Jersey 1.x的REST api。 In a ContainerRequestFilter, I want to set a property and then retrieve it later. 在ContainerRequestFilter中,我想设置一个属性,然后稍后再检索它。

I started with this code in my filter class: 我在过滤器类中以以下代码开始:

containerRequest.getProperties().setProperty("programId","foo");

But how exactly do I retrieve this later? 但是我以后如何准确检索呢?

The spec says, "In a Servlet container, the properties are synchronized with the ServletRequest and expose all the attributes available in the ServletRequest. Any modifications of the properties are also reflected in the set of properties of the associated ServletRequest." 规范说:“在Servlet容器中,属性与ServletRequest同步,并公开ServletRequest中可用的所有属性。对属性的任何修改也反映在关联的ServletRequest的属性集中。”

When I try to retrieve the property, I have a handle to the HttpServletRequest object, but that object doesn't have a ".getProperties()" method. 当我尝试检索该属性时,我具有HttpServletRequest对象的句柄,但该对象没有“ .getProperties()”方法。

To solve this, I ended up adding a line like this to my filter class: HttpServletRequest.setAttribute("programId", "foo"); 为了解决这个问题,我最终在过滤器类中添加了如下一行: HttpServletRequest.setAttribute("programId", "foo");

Which I was able to pull out later with (String)request.getAttribute("programId") . 我后来能够使用(String)request.getAttribute("programId") But I'm curious how those properties are supposed to be retrieved. 但是我很好奇应该如何检索这些属性。

I've been trying to find the answer to this myself for most of the day - the end result of which is I don't think there's an out-of-the-box mechanism other than to inject the request and cast it to a ContainerRequest, as in the following: 我一直试图在一天中的大部分时间里找到解决问题的方法-最终结果是,我认为除了注入请求并将其转换为一个请求外,没有其他现成的机制ContainerRequest,如下所示:

public Response resourceMethod(@Context Request request) {
    ContainerRequest containerRequest = (ContainerRequest) request;
    MyProperty prop = (MyProperty) containerRequest.getProperties().get("myPropertyName");

I didn't really like having to do this in the resources so then went on to using custom injection as detailed in Custom annotation injection with Jersey 1.x 我真的不喜欢在资源中执行此操作,因此继续使用自定义注入,如Jersey 1.x的自定义注释注入中所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM