分ip统计网站的访问次数
统计工作需要在所有资源之前都执行,那么就可以放到Filter中了
我们的过滤器不打算做拦截操作。因为只是统计的
用什么来装载统计的数据? Map<String,Integer>
只要一个Map即可
Map什么时候创建?(使用ServletContextListener,在服务器启动时完成创建,并保存到ServletContext中)保存在?(Map保存到ServletContxt中 )
Map需要在Filter中用来保存数据
Map需要在页面中使用,打印Map中的数据
因为一个网站可能有多个页面,无论那个页面被访问,都要统计访问次数,所以使用过滤器最为方便
因为需要分ip统计,所以可以在过滤器中创建一个Map,使用ip为key,访问次数为value。当有用户访问时,获取请求的ip,如果ip在map中存在,说明以前访问过,那么在访问次数上加1即可。如果不存在 设置次数为1
把Map放在ServletContxt
/**
* 进行统计工作,结果保存到map中
*
* @ClassName: AFilter
* @Description: TODO
* @author liuw
* @date 2018年11月8日 上午11:32:25
*
*/
public class AFilter implements Filter {
private FilterConfig config;
public AFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain filterChain) throws IOException, ServletException {
/*
* 1、得到application中的map 2、从request中获取当前客户端的ip地址
* 3、查看map中是否存在这个ip对应的访问次数,如果存在,把次数+1再保存回去
* 4、如果不存在这个ip,那么说明是第一次访问本站,设置访问次数为1
*/
/*
* 1、得到application
*/
ServletContext app = config.getServletContext();
Map<String, Integer> map = (Map<String, Integer>) app
.getAttribute("map");
/*
* 2、获取客户端的ip地址
*/
String ip = req.getRemoteAddr();
/*
* 3、进行判断
*/
// 这个ip在map中存在,说明不是第一次访问
if (map.containsKey(ip)) {
int cnt = map.get(ip);
map.put(ip, cnt + 1);
// 这个ip在map不存在,说明是第一次访问
} else {
map.put(ip, 1);
}
// 把map再放回到app中
app.setAttribute("map", map);
// 肯定放行
filterChain.doFilter(req, res);
}
/**
* 在服务器启动时执行本方法,且只执行一次
*/
public void init(FilterConfig fConfig) throws ServletException {
this.config = fConfig;
}
}
public class AListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
}
// 在服务器启动时创建map,保存到ServletContext中
public void contextDestroyed(ServletContextEvent servletContextEvent) {
// 创建map
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
// 得到ServletContext
ServletContext app = servletContextEvent.getServletContext();
// 把map保存到application中
app.setAttribute("map", map);
}
}
显示统计结果
<body>
<h1>显示结果</h1>
<table align="center" width="60%" border="1">
<tr>
<td>IP</td>
<td>次数</td>
</tr>
<c:forEach items="${applicationScope.map }" var="entry"/>
<tr>
<td>${entry.key }</td>
<td>${entry.value }</td>
</tr>
</table>
</body>