如何在 Spring MVC 控制器获取调用中提取 IP 地址?

新手上路,请多包涵

我正在从事 Spring MVC 控制器项目,在该项目中我正在从浏览器进行 GET URL 调用 -

下面是我从浏览器进行 GET 调用的 url -

 http://127.0.0.1:8080/testweb/processing?workflow=test&conf=20140324&dc=all

下面是点击浏览器后调用的代码 -

 @RequestMapping(value = "processing", method = RequestMethod.GET)
public @ResponseBody ProcessResponse processData(@RequestParam("workflow") final String workflow,
    @RequestParam("conf") final String value, @RequestParam("dc") final String dc) {

        System.out.println(workflow);
        System.out.println(value);
        System.out.println(dc);

        // some other code
    }

问题陈述:-

现在有什么办法,我可以从一些标头中提取 IP 地址吗?意思是我想知道来自哪个 IP 地址的呼叫来了,这意味着无论是谁在上面的 URL 上呼叫,我都需要知道他们的 IP 地址。这可能吗?

原文由 john 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 655
2 个回答

解决办法是

@RequestMapping(value = "processing", method = RequestMethod.GET)
public @ResponseBody ProcessResponse processData(@RequestParam("workflow") final String workflow,
    @RequestParam("conf") final String value, @RequestParam("dc") final String dc, HttpServletRequest request) {

        System.out.println(workflow);
        System.out.println(value);
        System.out.println(dc);
        System.out.println(request.getRemoteAddr());
        // some other code
    }

HttpServletRequest request 添加到您的方法定义中,然后使用 Servlet API

Spring Documentation 在这里

15.3.2.3 支持的处理程序方法参数和返回类型

Handler methods that are annotated with @RequestMapping can have very flexible signatures.
Most of them can be used in arbitrary order (see below for more details).

Request or response objects (Servlet API). Choose any specific request or response type,
for example ServletRequest or HttpServletRequest

原文由 Koitoer 发布,翻译遵循 CC BY-SA 3.0 许可协议

我来晚了,但这可能有助于寻找答案的人。通常 servletRequest.getRemoteAddr() 有效。

在许多情况下,您的应用程序用户可能正在通过代理服务器访问您的 Web 服务器,或者您的应用程序可能位于负载均衡器之后。

因此,在这种情况下,您应该访问 X-Forwarded-For http 标头以获取用户的 IP 地址。

例如 String ipAddress = request.getHeader("X-FORWARDED-FOR");

希望这可以帮助。

原文由 sunitkatkar 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题