如何在Spring bean中获取客户端IP地址

时间:2009-12-30 10:16:32

标签: java spring client-server

我已经定义了一个Spring bean。

<beans>
  <bean id="remoteService" class="edu.wustl.catissuecore.CaTissueApplictionServicImpl" />
</beans>

有没有办法在这个课程中获取客户端的IP地址?与servlet request.getRemoteAddr()中的可用类似;

3 个答案:

答案 0 :(得分:15)

最简单(也是最丑陋)的方法是使用RequestContextHolder

  String remoteAddress = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes())
       .getRequest().getRemoteAddr();

如果不了解更多关于你的bean以及它是如何接线的,那就是我能建议的最好的。如果你的bean是一个控制器(子类化AbstractController或用@Controller注释),那么它应该能够直接访问请求对象。

答案 1 :(得分:2)

获取客户端IP的最佳方法是遍历标题

   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 getClientIpAddress(HttpServletRequest request) {
    for (String header : IP_HEADER_CANDIDATES) {
        String ip = request.getHeader(header);
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
    }
    return request.getRemoteAddr();
}

答案 2 :(得分:-1)

构造这个:

@Autowired(required = true)
private HttpServletRequest  request;

并使用如下:

request.getRemoteAddr()