我正在开发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
我来晚了,但这可能有助于寻找答案的人.通常servletRequest.getRemoteAddr()
工作.
在许多情况下,您的应用程序用户可能通过代理服务器访问您的Web服务器,或者您的应用程序可能在负载均衡器后面.
因此,在这种情况下,您应该访问X-Forwarded-For http标头以获取用户的IP地址.
例如 String ipAddress = request.getHeader("X-FORWARDED-FOR");
希望这可以帮助.
我用这种方法做到这一点
public class HttpReqRespUtils { private static final String[] IP_HEADER_CANDIDATES = { "X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP", "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR" }; public static String getClientIpAddressIfServletRequestExist() { if (RequestContextHolder.getRequestAttributes() == null) { return "0.0.0.0"; } HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); for (String header: IP_HEADER_CANDIDATES) { String ipList = request.getHeader(header); if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) { String ip = ipList.split(",")[0]; return ip; } } return request.getRemoteAddr(); } }
您可以通过以下方式静态获取IP地址RequestContextHolder
:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) .getRequest(); String ip = request.getRemoteAddr();