如何在 Jersey 2.25.1 应用程序中获取调用方的 IP 地址



我在这里尝试过这种方法,但没有运气:正如答案中的注释提到的那样,HttpServletRequest只是null.

这是我的过滤器:

public void myFilter(ContainerRequestContext request) throws IOException 
  {
   // I don't see a way to get the IP address from the ContainerRequestContext
 }

如果我尝试使用 @Context HttpServletRequest httpServletRequest ,正如另一个问题的答案所暗示的那样,我只会得到一个NullPointerException.

另一个类似的问题:如何从ContainerResponseFilter内部获取源地址/ip

空指针异常只发生在我们的测试中。 Peeskillet帮助我意识到,只要我们使用jersey-test-framework-provider-jetty进行测试,注射HttpServletRequest就不起作用(例如参见 https://github.com/jersey/jersey/issues/2764 或 https://github.com/jersey/jersey/issues/3092(。如果我们使用了类似的东西 GrizzlyWebTestContainerFactory ,那么注入HttpServletRequest就可以了,因为那时我们会有一个ServletDeploymentContext

我们在测试中采用了这个解决方案,即只是在需要时模拟HttpServletRequest

最新更新