简体   繁体   中英

How can I extract request attributes from Jersey's ContainerRequest?

HttpServletRequest has a method setAttribute(String, Object) .

How can I extract this attribute from ContainterRequest ?

I didn't find: getAttribute method!

Code

public class AuthenticationFilter implements Filter {
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) servletRequest;
        // .... ....
        httpReq.setAttribute("businessId", businessId);
    }
}

In Jersey Filter:

private class Filter implements ResourceFilter, ContainerRequestFilter {
    public ContainerRequest filter(ContainerRequest request) {
        // ..extract the attribute from the httpReq
    }
}

You can't. They're not exposed through the Jersey API in any way. If you search the Jersey codebase, you'll find that there are no uses of HttpServletRequest.getAttributeNames() , which you'd expect to be used if they were being copied en masse. You'll also find that there are only a handful of uses of HttpServletRequest.getAttribute() , and it's strictly for internal bookkeeping.

Note, however, that when deployed in a Servlet Context, JAX-RS allows you to inject the original HttpServletRequest using the @Context annotation. I'm not certain whether you can do this in a Jersey filter, but it works in MessageBodyReaders/Writers and in resource classes.

Update: I've checked, and you can, in fact, inject the HttpServletRequest into a Jersey ContainerRequestFilter by simply including:

@Context private HttpServletRequest httpRequest;

I got the @Context working, but have the problem is that my ContainerRequestFilter is singleton.

I had to implement a custom javax.servlet.Filter and use a ThreadLocal to store the HttpServletRequest .

If you're using Jersey 2, which implements JAX-RS 2.0, you can implement a ContainerRequestFilter which defines a filter method as follows:

public void filter(ContainerRequestContext requestContext) throws IOException;

ContainerRequestContext has getProperty(String) and setProperty(String, Object) methods, which in a Servlet environment ( ServletPropertiesDelegate ), map to the servlet request's getAttribute(String) and setAttribute(String, Object) methods.

See: Jersey on GitHub

I wanted to add to previous answers my solution, in addition to adding context:

@Context
private HttpServletRequest httpRequest;

You should set and get attributes from the session .

Set:

 httpRequest.getSession().setAttribute("businessId", "yourId");

Get:

Object attribute = httpRequest.getSession().getAttribute("businessId");

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