【问题标题】:JERSEY: How to retrieve the calling IP or URI using injection annotation?JERSEY:如何使用注入注解检索调用 IP 或 URI?
【发布时间】:2012-02-29 12:58:07
【问题描述】:

我在这里有一个使用 JERSEY 的 REST 服务器。我必须记录调用客户端的 IP(最好是 DNS)。

有人可以指出使用注入注释的方向吗?

已搜索“@Context”,但找不到合适的内容。

谢谢 格尔德

【问题讨论】:

    标签: java jersey


    【解决方案1】:

    您可以将@Context HttpServletRequest request 作为参数添加到您的请求处理程序方法中。然后通过request.getRemoteAddr()获取客户端IP

    【讨论】:

    • RemoteUser 为我返回 null,但 RemoteHost 和 RemoteAddr 按计划工作
    • 我尝试了解决方案,但得到“类型不匹配:无法从上下文转换为注释”。我该如何解决?
    • @JeffreyLin 从远处很难说 :) 也许您导入了不同的 Context 类?确保你有import javax.ws.rs.core.Context
    • @rompetroll 非常感谢!
    【解决方案2】:

    如果您使用 Grizzly-Jersey 组合,这就是这样做的方法:

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

    【讨论】:

      【解决方案3】:

      灰熊-球衣组合的选项 2。 放置在类的声明中(在我的例子中是 ContainerRequestFilter 的扩展器)

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

      在后面的代码中使用这个。

      request.get().getRemoteAddr()
      

      我四处寻找,找到了resolution in the jersey's jira。 请注意,他们建议使用 @Inject 而不是 @Context

      我尝试过使用

        @Context
        private HttpServletRequest servletRequest;
      

      广泛推荐,但 servletRequest 始终为空。

      *comment servletRequest 为空,因为我使用 GrizzlyHttpServerFactory 来创建 HttpServer。如果你想拥有 servletRequest,那么你需要使用 WebappContext 来部署它。 Take a look here for details

      【讨论】:

        猜你喜欢
        • 2014-02-06
        • 1970-01-01
        • 2012-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-15
        • 2014-12-09
        相关资源
        最近更新 更多