阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

分ip统计网站的访问次数

107次阅读
没有评论

共计 2284 个字符,预计需要花费 6 分钟才能阅读完成。

1、分 ip 统计网站的访问次数

分 ip 统计网站的访问次数

统计工作需要在所有资源之前都执行,那么就可以放到 Filter 中了。

我们这个过滤器不打算做拦截操作!因为我们只是用来做统计的。

用什么东西来装载统计的数据。Map<String,Integer>

整个网站只需要一个 Map 即可!

Map 什么时候创建(使用 ServletContextListener,在服务器启动时完成创建,并只在到 ServletContext 中),Map 保存到哪里!(Map 保存到 ServletContext 中!!!)

  • Map 需要在 Filter 中用来保存数据
  • Map 需要在页面使用,打印 Map 中的数据

2、说明

网站统计每个 IP 地址访问本网站的次数。

3、分析

因为一个网站可能有多个页面,无论哪个页面被访问,都要统计访问次数,所以使用过滤器最为方便。

因为需要分 IP 统计,所以可以在过滤器中创建一个 Map,使用 IP 为 key,访问次数为 value。当有用户访问时,获取请求的 IP,如果 IP 在 Map 中存在,说明以前访问过,那么在访问次数上加 1,即可;IP 在 Map 中不存在,那么设置次数为 1。

把这个 Map 存放到 ServletContext 中!

4、代码

监听器

public class AListener implements ServletContextListener {/** * 在服务器启动时创建 Map,保存到 ServletContext */ public void contextInitialized(ServletContextEvent sce) {// 创建 Map Map<String,Integer> map = new LinkedHashMap<String,Integer>(); // 得到 ServletContext ServletContext application = sce.getServletContext(); // 把 map 保存到 application 中 application.setAttribute("ipCountMap", map); } public void contextDestroyed(ServletContextEvent sce) {}}

配置监听器

<listener> <listener-class>com.tyschool.web.listener.AListener</listener-class> </listener>

index.jsp

<body> <h1> 分 IP 统计访问次数 </h1> <table align="center" width="50%" border="1"> <tr> <th>IP 地址 </th> <th> 次数 </th> </tr> <c:forEach items="${applicationScope.ipCountMap}" var="entry"> <tr> <td>${entry.key}</td> <td>${entry.value}</td> </tr> </c:forEach> </table> </body>

IPFilter

public class IPFilter implements Filter {private ServletContext context; public void init(FilterConfig fConfig) throws ServletException {context = fConfig.getServletContext(); Map<String, Integer> ipCountMap = Collections .synchronizedMap(new LinkedHashMap<String, Integer>()); context.setAttribute("ipCountMap", ipCountMap); } @SuppressWarnings("unchecked") public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; String ip = req.getRemoteAddr(); Map<String, Integer> ipCountMap = (Map<String, Integer>) context .getAttribute("ipCountMap"); Integer count = ipCountMap.get(ip); if (count == null) {count = 1; } else {count += 1; } ipCountMap.put(ip, count); context.setAttribute("ipCountMap", ipCountMap); chain.doFilter(request, response); } public void destroy() {}}
<filter> <display-name>IPFilter</display-name> <filter-name>IPFilter</filter-name> <filter-class>cn.itcast.filter.ip.IPFilter</filter-class> </filter> <filter-mapping> <filter-name>IPFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-06-06发表,共计2284字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中