简体   繁体   中英

How to retrieve Jersey ContainerRequest properties?

I have a Java 1.6 web app in Tomcat with a REST api using Jersey 1.x. In a ContainerRequestFilter, I want to set a property and then retrieve it later.

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."

When I try to retrieve the property, I have a handle to the HttpServletRequest object, but that object doesn't have a ".getProperties()" method.

To solve this, I ended up adding a line like this to my filter class: HttpServletRequest.setAttribute("programId", "foo");

Which I was able to pull out later with (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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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