一般這樣取一個IP:request.getRemoteAddr(),但有時候取出來的是不對的,特別是在應用前加了Nginx之類的軟件,下面的方法能夠取出訪問的IP地址spa
public static String getRemoteAddrIp(HttpServletRequest request) { String ipFromNginx = getHeader(request, "X-Real-IP"); //System.out.println("ipFromNginx:" + ipFromNginx); //System.out.println("getRemoteAddr:" + request.getRemoteAddr()); return StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx; } private static String getHeader(HttpServletRequest request, String headName) { String value = request.getHeader(headName); return !StringUtils.isBlank(value) && !"unknown".equalsIgnoreCase(value) ? value : ""; }