统计工作需要在所有资源之前都执行,那么就可以放到Filter中了。
我们这个过滤器不打算做拦截操作!因为我们只是用来做统计的。
用什么东西来装载统计的数据。Map<String,Integer>
整个网站只需要一个Map即可!
Map什么时候创建(使用ServletContextListener,在服务器启动时完成创建,并只在到ServletContext中),Map保存到哪里!(Map保存到ServletContext中!!!)
网站统计每个IP地址访问本网站的次数。
因为一个网站可能有多个页面,无论哪个页面被访问,都要统计访问次数,所以使用过滤器最为方便。
因为需要分IP统计,所以可以在过滤器中创建一个Map,使用IP为key,访问次数为value。当有用户访问时,获取请求的IP,如果IP在Map中存在,说明以前访问过,那么在访问次数上加1,即可;IP在Map中不存在,那么设置次数为1。
把这个Map存放到ServletContext中!
监听器
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>
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有