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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1979419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:01:25  来源:igfitidea点击:

How to get Client IP address in Spring bean

javaspringclient-server

提问by

I have define a Spring bean.

我已经定义了一个 Spring bean。

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

Is there any way to get the IP address of client in this class? Similarly as available in the servlet request.getRemoteAddr();

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

回答by skaffman

The simplest (and ugliest) approach is to use RequestContextHolder:

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

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

Without knowing more about your bean and how it's wired up, that's the best I can suggest. If your bean is a controller (either subclassing AbstractControlleror being annotated with @Controller) then it should be able to get direct access to the request object.

在不了解您的 bean 及其连接方式的情况下,这是我能建议的最好方法。如果您的 bean 是控制器(子类化AbstractController或使用 注释@Controller),那么它应该能够直接访问请求对象。

回答by ümit ?ak?r

Construct this:

构造这个:

@Autowired(required = true)
private HttpServletRequest  request;

and use like this:

并像这样使用:

request.getRemoteAddr()

回答by syed

The best way to get client ip is to loop through the headers

获取客户端 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();
}