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

五迷三道 提交于 2019-12-06 01:41:48

问题


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.


回答1:


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



回答2:


As Op said that

I know that in older versions of Jersey you could inject a ThreadLocal to achieve this.

I just want to add some code here which could implement this for those who are still using an older version of jersey like I do:

@Context ThreadLocal<HttpServletRequest> treq;

And a link for this:Thread access to @Context objects? Hope that would help.



来源:https://stackoverflow.com/questions/29434312/is-it-possible-in-jersey-to-have-access-to-an-injected-httpservletrequest-inste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!