FilterConfig 记录服务器被每ip访问多少次

@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		// 获取请求的ip地址
		String ip = request.getRemoteAddr();
		ServletContext servletContext = filterConfig.getServletContext();
		Map map = (Map) servletContext.getAttribute("countMap");
		// 从servletContext中取出存储的信息
		Integer count = map.get(ip);
		if (count == null) {
			count = 1;
		} else {
			count++;
		}

		map.put(ip, count);
		servletContext.setAttribute("countMap", map);
		System.out.println("已经被ip" + ip + "访问" + count + "次");
		// 放行
		filterChain.doFilter(request, response);

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 创建一个map存储访问信息
		Map map = new HashMap<>();
		ServletContext servletContext = filterConfig.getServletContext();
		servletContext.setAttribute("countMap", map);

		this.filterConfig = filterConfig;
	}

 

你可能感兴趣的:(FilterConfig 记录服务器被每ip访问多少次)