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