Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible in Jersey to have access to an injected HttpServletRequest, instead of to a proxy

When injecting HttpServletRequest in Jersey/JAX-RS resources, the injected value is a proxy. E.g.:

@Path("/myResource") 
class MyResource {
    @Inject 
    HttpServletRequest request;
    ...
}

Will inject a Proxy object for the requested HttpServletRequest. I need access to the actual HttpServletRequest instance object, because I want to use some container specific features that are not in the proxied HttpServletRequest interface.

Is there a way in jersey to have access to the actual object via injection? I know that in older versions of Jersey you could inject a ThreadLocal<HttpServletRequest> to achieve this. But that doesn't seem to be supported in jersey 2.15 anymore.

Rationale: My code depends on functionality in org.eclipse.jetty.server.Request which implements HttpRequest, and adds functionality for HTTP/2 push. I would like to use that with Jersey/JAX-RS.

like image 638
Gerrit Avatar asked Apr 03 '15 14:04

Gerrit


1 Answers

Don't make your resource class a singleton. If you do this, there is no choice but to proxy, as the request is in a different scope.

@Singleton
@Path("servlet")
public class ServletResource {

    @Context
    HttpServletRequest request;

    @GET
    public String getType() {
        return request.getClass().getName();
    }
}

With @Singleton

C:\>curl http://localhost:8080/api/servlet
com.sun.proxy.$Proxy41

Without @Singleton

C:\>curl http://localhost:8080/api/servlet
org.eclipse.jetty.server.Request

There are other ways your class can become a singleton, like registering it as an instance

You can aslo inject it as a method parameter. Singleton or not, you will get the actual instance

@GET
public String getType(@Context HttpServletRequest request) {
    return request.getClass().getName();
}

See Also

  • Injecting Request Scoped Objects into Singleton Scoped Object with HK2 and Jersey
like image 159
Paul Samsotha Avatar answered Sep 18 '22 10:09

Paul Samsotha