在Jersey中是否可以访问注入的HttpServletRequest,而不是代理 [英] Is it possible in Jersey to have access to an injected HttpServletRequest, instead of to a proxy

查看:466
本文介绍了在Jersey中是否可以访问注入的HttpServletRequest,而不是代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Jersey/JAX-RS资源中注入HttpServletRequest时,注入的值是代理.例如:

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

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

将为请求的HttpServletRequest注入Proxy对象.我需要访问实际的HttpServletRequest实例对象,因为我想使用某些不在容器HttpServletRequest界面中的特定于容器的功能.

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.

球衣中是否可以通过注入方式访问实际对象?我知道在较旧版本的Jersey中,您可以注入ThreadLocal<HttpServletRequest>来实现此目的.但这似乎在jersey 2.15中不再受支持.

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.

合理性:我的代码取决于实现HttpRequestorg.eclipse.jetty.server.Request中的功能,并为HTTP/2推送添加了功能.我想在Jersey/JAX-RS上使用它.

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();
    }
}

使用@Singleton

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

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

没有@Singleton

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

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();
}


另请参见

这篇关于在Jersey中是否可以访问注入的HttpServletRequest,而不是代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆