获取客户端IP的两种语法

一,实习看到项目里这样写,第一次见到,整理笔记。^_^

      第一种方法通过

RequestContextHolder获取request对象,RequestContextHolder用于在其他层获取请求响应对象。
 第二种方法通过
RequestContextHolder返回的ServletRequestAttributes不存在时,可以通过WebServiceContextImpl构建一个MessageContent对象,获取request对象
// 通过RequestContextHolder获取请求对象。不需要传入请求的对象。
            ServletRequestAttributes attributes= (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request=null;
            if(null!=attributes) {
                 request = attributes.getRequest();
            }else {
                // 当attributes不存在时
                webServiceContext = new WebServiceContextImpl();
                // 返回在MessageContext此方法时提供的请求的MessageContext
                MessageContext mc = (MessageContext) webServiceContext.getMessageContext();
                // 通过MessageContext构建一个request对象。
                request = (HttpServletRequest) (mc.get(MessageContext.SERVLET_REQUEST));
            }

 之后通过request对象的getHeader("X-Forwarded-For")获取本地的真实Ip

public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        /*
         * //这里主要是获取本机的ip,可有可无 if (ip.equals("127.0.0.1") ||
         * ip.endsWith("0:0:0:0:0:0:1")) { // 根据网卡取本机配置的IP InetAddress inet =
         * null; try { inet = InetAddress.getLocalHost(); } catch
         * (UnknownHostException e) { e.printStackTrace(); } ip =
         * inet.getHostAddress(); }
         */
        return ip;
    }

 

上一篇:jsp大文件(视频)上传源码


下一篇:WEB 项目文件夹上传下载解决方案