spring boot 获取客户端ip信息

增加顶级过滤器

`@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 失效

posted @ 2024-11-27 09:38  hyiam  阅读(48)  评论(0编辑  收藏  举报