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