JERSEY: How to retrieve the calling IP or URI using injection annotation?

亡梦爱人 提交于 2019-12-12 08:24:54

问题


I have a REST- Server here using JERSEY. I must log the IP (better the DNS) of the calling client.

Can somebody point a direction which injection annotations to use ?

Searched "@Context", but could not find anything fitting.

Thanks Gerd


回答1:


you could add @Context HttpServletRequest request as a parameter to your request handler method. And then get a hold of the client IP with request.getRemoteAddr()




回答2:


In case you use Grizzly-Jersey combo, thats the way to do it:

@Context
private java.lang.ThreadLocal<org.glassfish.grizzly.http.server.Request> grizzlyRequest;



回答3:


Option 2 for Grizzly-Jersey combo. Place in the declaration of the class (extender of ContainerRequestFilter in my case)

 @Inject
 private javax.inject.Provider<org.glassfish.grizzly.http.server.Request> request;

and later in the code use this.

request.get().getRemoteAddr()

I dug around and I've found the resolution in the jersey's jira. Note that they recommend to be used @Inject instead of @Context

I've tried to use

  @Context
  private HttpServletRequest servletRequest;

which is recommended widely but servletRequest was always null.

*comment servletRequest was null because I was used GrizzlyHttpServerFactory for creating HttpServer. If you want to have servletRequest then you need to deploy it with WebappContext. Take a look here for details



来源:https://stackoverflow.com/questions/9499596/jersey-how-to-retrieve-the-calling-ip-or-uri-using-injection-annotation

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