import javax.servlet.http.HttpServletRequest; import com.tbtech.common.utils.StringUtils; public final class RequestHelper { /* * 获取访问者IP * 在通常状况下使用Request.getRemoteAddr()便可,可是通过nginx等反向代理软件后,这个方法会失效。 * 本方法先从Header中获取X-Real-IP,若是不存在再从X-Forwarded-For得到第一个IP(用,分割),* 若是还不存在则调用Request .getRemoteAddr()。 * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if(!StringUtils.isBlank(ip) && !"unKnown".equalsIgnoreCase(ip)){ //屡次反向代理后会有多个ip值,第一个ip才是真实ip int index = ip.indexOf(","); if(index != -1){ return ip.substring(0,index); }else{ return ip; } } ip = request.getHeader("X-Real-IP"); //StringUtils.isBlank只是一个判断非空字符的方法 if(!StringUtils.isBlank(ip) && !"unKnown".equalsIgnoreCase(ip)){ return ip; } return request.getRemoteAddr(); } }
参考博客:http://www.javashuo.com/article/p-xotjhvkq-dg.html
感谢大佬!!!html
.endjava