在Spring框架中,您可以直接@Autowired
在任何Spring托管Bean中直接使用HttpServletRequest
,然后再从请求标头中获取客户端的IP地址。
WebUtils.java
package com.mkyong.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;
}
}
参考文献
翻译自: https://mkyong.com/spring-mvc/spring-mvc-how-to-get-client-ip-address/