Spring MVC如何获取客户端IP地址呢?
下文笔者讲述使用Spring MVC代码获取客户端IP地址的方法分享,如下所示
Spring MVC获取客户端IP地址的实现思路: 1.使用Autowired将HttpServletRequest注入到指定的变量上 2.编写相应的方法即可获取客户端IP地址例:
WebUtils.java
package com.java265.web; 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; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。