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;
}
}