Liferay portlet 如何取得客户端的IP地址(portal get remote IP)

方案一

Liferay 屏蔽了获取remoteHost 方法,但request对象是保留在私有域

 

java.lang.reflect.Field f = request.getClass().getDeclaredField("_request");
f.setAccessible(true);//设置该变量可视
HttpServletRequest httpServletRequest = (HttpServletRequest) f.get(request); //拿到Request

 

/*  以下处理用代理时的情况 */
String ip = httpServletRequest.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = httpServletRequest.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = httpServletRequest.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = httpServletRequest.getRemoteAddr();
}
System.out.println("ip:="+ip);

 

方案二

 

HttpServletRequest httpServletRequest = com.liferay.portal.util.PortalUtil.getHttpServletRequest(renderRequest);

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

方案三

<%
java.lang.reflect.Field[] fs = request.getClass().getDeclaredFields(); 
java.lang.reflect.Field f = null ;
for(int i=0;i<fs.length;i++){
if ( fs[i].getName().equals("_request") ){
f = fs[i];
break;
}
}
f.setAccessible(true) ;//设置该变量可视
HttpServletRequest httpServletRequest = (HttpServletRequest) f.get(request);
String ip = httpServletRequest.getHeader("x-forwarded-for"); 
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
   ip = httpServletRequest.getHeader("Proxy-Client-IP"); 

if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
   ip = httpServletRequest.getHeader("WL-Proxy-Client-IP"); 

if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
   ip = httpServletRequest.getRemoteAddr(); 

System.out.println("ip:="+ip);
%>

 

你可能感兴趣的:(String,null,portlet)