Spring MVC How to get client IP address
By:Roy.LiuLast updated:2019-08-11
In Spring framework, you can @Autowired a HttpServletRequest in any Spring managed bean directly, and later get the client’s IP address from the request headers
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;
References
From:一号门
Previous:Java How to shuffle an ArrayList
COMMENTS