注射时HttpServletRequest
在 Jersey/JAX-RS 资源中,注入的值是代理。例如。:
@Path("/myResource")
class MyResource {
@Inject
HttpServletRequest request;
...
}
会注入一个Proxy
所请求的对象HttpServletRequest
。我需要访问实际的HttpServletRequest
实例对象,因为我想使用一些不在代理中的容器特定功能HttpServletRequest
界面。
jersey 有没有办法通过注入访问实际对象?我知道在旧版本的 Jersey 中你可以注入ThreadLocal<HttpServletRequest>
为了达成这个。但 jersey 2.15 似乎不再支持这一点。
理由:我的代码取决于中的功能org.eclipse.jetty.server.Request
它实现了HttpRequest
,并添加了 HTTP/2 推送功能。我想将其与 Jersey/JAX-RS 一起使用。
不要使您的资源类成为单例。如果您这样做,则别无选择,只能代理,因为请求位于不同的范围内。
@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
您的类还有其他方法可以成为单例,例如将其注册为实例
您也可以将其作为方法参数注入。无论是否单例,您都会得到实际的实例
@GET
public String getType(@Context HttpServletRequest request) {
return request.getClass().getName();
}
See Also
- 使用 HK2 和 Jersey 将请求范围对象注入单例范围对象 http://paulsamsotha.blogspot.com/2015/12/injecting-request-scoped-objects-into.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)