首页 > 编程 > Java > 正文

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

2019-11-26 15:51:18
字体:
来源:转载
供稿:网友

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;
}
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表