package com.chen.filter; import java.io.IOException; import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class MyFilter implements Filter { private FilterConfig filterConfig; @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletContext context = filterConfig.getServletContext(); Map<String, Integer> ipMap = (Map<String, Integer>) context .getAttribute("ipMap"); String ip = request.getRemoteAddr(); // String ip = getIpAddr(request); if (ipMap.containsKey(ip)) { Integer count = ipMap.get(ip); ipMap.put(ip, count + 1); } else { ipMap.put(ip, 1); } context.setAttribute("ipMap", ipMap); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public String getIpAddr(HttpServletRequest request) { String ip = request.getHeader( " x-forwarded-for " ); if (ip == null || ip.length() == 0 || " unknown " .equalsIgnoreCase(ip)) { ip = request.getHeader( " Proxy-Client-IP " ); } if (ip == null || ip.length() == 0 || " unknown " .equalsIgnoreCase(ip)) { ip = request.getHeader( " WL-Proxy-Client-IP " ); } if (ip == null || ip.length() == 0 || " unknown " .equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }