Dejell
Dejell

Reputation: 14337

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
    }
}

Upvotes: 26

Views: 24219

Answers (4)

Ori Marko
Ori Marko

Reputation: 58882

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

Upvotes: 1

Steven Benitez
Steven Benitez

Reputation: 11055

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

Upvotes: 7

huljas
huljas

Reputation: 147

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.

Upvotes: 4

Ryan Stewart
Ryan Stewart

Reputation: 128919

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;

Upvotes: 48

Related Questions