java获取客户端ip, cookie

因为用户有可能通过apache,nginx等代理服务器访问,客户端和服务之间增加了中间层,因此服务器无法直接拿到客户端的IP,服务器端应用也无法直接通过转发请求的地址返回给客户端。但是在转发请求的HTTP头信息中,增加了X-FORWARDED-FOR信息。用以跟踪原有的客户端IP地址和原来客户端请求的服务器地址。

String ip  =  getRequest().getHeader( " x-forwarded-for " );
    if (ip  ==   null   ||  ip.length()  ==   0   ||   " unknown " .equalsIgnoreCase(ip))  {
        ip  =  getRequest().getHeader( " Proxy-Client-IP " );
    }
    if (ip  ==   null   ||  ip.length()  ==   0   ||   " unknown " .equalsIgnoreCase(ip))  {
        ip  =  getRequest().getHeader( " WL-Proxy-Client-IP " );
    }
    if (ip  ==   null   ||  ip.length()  ==   0   ||   " unknown " .equalsIgnoreCase(ip))  {
        ip  =  getRequest().getRemoteAddr();
    }
    System.out.println(ip);


Cookie []cookies = getRequest().getCookies();
    Cookie c = null;
    String usertype = null;
    if(cookies!=null) {
        for (int i = 0; i < cookies.length; i++) {
            c = cookies[i];
            if (c.getName().equals("usertype")) {
                System.out.println("usertype:" + c.getValue());
                usertype= c.getValue();
            }
        }
    }

你可能感兴趣的:(java获取客户端ip, cookie)