SpringMVC怎样获取客户端的ip地址

2023-05-04 20:52:53 浏览数 (1)

SpringMVC怎样获取客户端的ip地址

在spring框架管理下,你可以在任意一个spring管理的bean中使用 @Autowired注解来注入一个 HttpServletRequest,然后就可以从请求头中获取ip地址了。

示例代码如下:

代码语言:javascript复制
@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;
    }

}

0 人点赞