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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With