如何在Serverlet请求中获取客户端系统IP地址

时间:2016-12-29 11:07:43

标签: java servlets

    @GET
        @Produces(MediaType.APPLICATION_JSON)
        public Response login(@Context HttpHeaders headers, @Context HttpServletRequest request) {
            System.out.println(getClientIpAddress(request));
            String ipAddress = request.getHeader("X-FORWARDED-FOR");
            if (ipAddress == null) {
                ipAddress = request.getRemoteAddr();
            }
            System.out.println("ip:" + ipAddress);
            return new LoginUtils().performLogin(headers.getRequestHeaders());
        }  

  public static String getClientIpAddress(HttpServletRequest request) {
            for (String header : HEADERS_TO_TRY) {
                String ip = request.getHeader(header);
                if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                    return ip;
                }
            }
            return request.getRemoteAddr();
        }

但我没有得到IP地址我从每个请求获得相同的127.0.0.1这个值不同系统可以告诉我如何获取IP地址。

1 个答案:

答案 0 :(得分:-1)

你可以这样做:

使HttpServletRequest Autowired可以在你的控制器的任何功能中使用:

@Autowired
private HttpServletRequest request;

然后只需在你的控制器中使用它:

 String remoteAddr = request.getRemoteAddr();
 String localAddres = request.getLocalAddr();