当前位置:主页 > 软件编程 > JAVA代码 >

java servlet获得客户端相关信息的简单代码

时间:2020-10-20 15:21:07 | 栏目:JAVA代码 | 点击:

java web很常用的功能代码,可以配合实现IP白名单控制,直接贴代码:

复制代码 代码如下:

import javax.servlet.http.HttpServletRequest;

public class ClientInfoUtil{

/**
* 获得客户端的IP地址
* @param request
* @return
*/
static public String getIP(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.getRemoteAddr();
    }
    return ip;
}


/**
* 获得客户端访问服务器的url地址
* @param request
* @return
*/
static public String getURL(HttpServletRequest request) {
    String url = request.getScheme()+"://";  
    url+=request.getHeader("host");  
    url+=request.getRequestURI();  
    if(request.getQueryString()!=null)  {
        url+="?"+request.getQueryString();  
    }
    return url;
}
}

您可能感兴趣的文章:

相关文章