如何在Spring MVC Controller获取呼叫中提取IP地址?

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

以下是我从浏览器进行GET调用的网址-

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地址。这可能吗?

回答:

解决方法是

@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文档在这里说

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

以上是 如何在Spring MVC Controller获取呼叫中提取IP地址? 的全部内容, 来源链接: utcz.com/qa/431030.html

回到顶部