spring boot 獲取客戶端ip資訊

hyiam發表於2024-11-27

增加頂級過濾器

`@javax.servlet.annotation.WebFilter(filterName = "sessionFilter", urlPatterns = "/webSocket/*")
@Order(1)
@Slf4j
public class WebFilter implements Filter {

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
	HttpServletRequest req = (HttpServletRequest) servletRequest;
	HttpSession session = req.getSession();
	session.setAttribute("user_ip", req.getRemoteHost());
	log.info("user_ip===={}",req.getRemoteHost());
	filterChain.doFilter(servletRequest, servletResponse);
}
public String getIpAddr(HttpServletRequest request) {
	String ipAddress = null;
	try {
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")) {
				// 根據網路卡取本機配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 對於透過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
			// = 15
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
	} catch (Exception e) {
		ipAddress="";
	}
	return ipAddress;
}

}`
在啟動類上,需要加上@ServletComponentScan 用來註冊這個Filter,直接使用@Component會導致urlPatterns 失效

相關文章