gpt4 book ai didi

java - 如何在 Spring MVC Controller get call 中提取 IP 地址?

转载 作者:IT老高 更新时间:2023-10-28 13:52:53 28 4
gpt4 key购买 nike

我正在开发 Spring MVC Controller 项目,在该项目中我正在从浏览器进行 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
}

问题陈述:-

现在有什么方法可以从某个 header 中提取 IP 地址吗?这意味着我想知道来自哪个 IP 地址的调用,这意味着无论谁在 URL 上方调用,我都需要知道他们的 IP 地址。这可以吗?

最佳答案

解决办法是

@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 请求 添加到您的方法定义中,然后使用 Servlet API

Spring 文档 here

中说

15.3.2.3 Supported handler method arguments and return types

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

关于java - 如何在 Spring MVC Controller get call 中提取 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22877350/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com