WEB项目-Filter过滤器(分IP统计用户访问次数)

本文介绍如何使用Servlet过滤器(Filter)技术实现IP访问次数的统计,通过自定义过滤器类CountFilter,对web服务器上的所有资源进行拦截,记录每个IP的访问次数,并展示实现代码及配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Filter简介

Filter也称之为过滤器,它是Servlet技术中最实用的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态 html 文件等进行拦截,从而实现一些特殊的功能。

特点: 过滤器不是目标资源,是在访问目标资源的前后执行的。 过滤器的拦截是双向的 可以有多个过滤器。 过滤器拦截是一堆目标资源。

分IP统计用户访问次数

自定义过滤器类的代码

package com.filter;

import java.io.IOException;
import java.util.HashMap;
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;

public class CountFilter implements Filter {
	private FilterConfig config;
	
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
		//获取ServletContext对象
		ServletContext context = config.getServletContext();
		//创建一个Map集合,用于存储用户的ip和访问次数
		Map<String,Integer> countMap = new HashMap<>();
		//将map存入ServletContext域中
		context.setAttribute("countMap", countMap);
		
	}
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//当请求发送来时,获取用户的ip
		String ip = request.getRemoteAddr();
		//获取map集合,判断集合中该ip的count值为多少
		ServletContext context = config.getServletContext();
		Map<String,Integer> countMap = (Map<String, Integer>) context.getAttribute("countMap");
		Integer count = countMap.get(ip);
		if(count == null){
			count = 1;
		}else{
			count++;
		}
		//将新的count值存入到map中
		countMap.put(ip, count);
		//将map存入到context中
		context.setAttribute("countMap", countMap);
		chain.doFilter(request, response);
	}
	public void destroy() {
		
	}

}

过滤器配置文件

 <!-- 配置访问计数的过滤器 -->
  <filter>
  	<filter-name>CountFilter</filter-name>
  	<filter-class>com.filter.CountFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>CountFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

用来显示IP和计数的JSP页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>欢迎</h3>
	<c:forEach var="entry" items="${countMap }">
		<h3>${entry.key }</h3><br>
		<h3>${entry.value }</h3>
	</c:forEach>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值