java servlet获得客户端相关信息的简单代码
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;
}
}