一、使用背景

    在Spring框架中, 你可以直接使用注解@Autowired来注入一个HttpServletRequest,只要在被spring管理的类中,然后你就可以从request的headers中获取到来访的请求客户IP地址。

二、具体获取IP代码

WebUtils.java:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class WebUtils {

    private HttpServletRequest request;

    @Autowired
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    private static String getClientIp() {

        String remoteAddr = "";

        if (request != null) {
            remoteAddr = request.getHeader("X-FORWARDED-FOR");
            if (remoteAddr == null || "".equals(remoteAddr)) {
                remoteAddr = request.getRemoteAddr();
            }
        }

        return remoteAddr;
    }

}

三、使用IP工具类

最常使用的地方可能是你的controller中,例如
public GetIpController{
   @Autowired
   WebUtils webUtils;

   @GetMapping("/getIp.do")
   public String getClientIP(HttpServletRequest request){
    return webUtils.getClientIp();
   }
}