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("map", map);
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
public class AFilter implements Filter {
private FilterConfig config;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
/*
* 1. 得到application中的map
* 2. 从request中获取当前客户端的ip地址
* 3. 查看map中是否存在这个ip对应访问次数,如果存在,把次数+1再保存回去
* 4. 如果不存在这个ip,那么说明是第一次访问本站,设置访问次数为1
*/
/*
* 1. 得到appliction
*/
ServletContext app = config.getServletContext();
Map<String,Integer> map = (Map<String, Integer>) app.getAttribute("map");
/*
* 2. 获取客户端的ip地址
*/
String ip = request.getRemoteAddr();
/*
* 3. 进行判断
*/
if(map.containsKey(ip)) {//这个ip在map中存在,说明不是第一次访问
int cnt = map.get(ip);
map.put(ip, cnt+1);
} else {//这个ip在map中不存在,说明是第一次访问
map.put(ip, 1);
}
app.setAttribute("map", map);//把map再放回到app中
chain.doFilter(request, response);//肯定放行
}
<h1 align="center">显示结果</h1>
<table align="center" width="60%" border="1">
<tr>
<th>IP</th>
<th>次数</th>
</tr>
<c:forEach items="${applicationScope.map }" var="entry">
<tr>
<td>${entry.key }</td>
<td>${entry.value }</td>
</tr>
</c:forEach>
</table>