分ip统计访问次数

1、创建一个过滤器

public class AFilter implements Filter {
private FilterConfig filterconfig;

@Override
public void destroy() {
System.out.println("死翘翘了");
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
/**
* 从application中得到map
* 从request中获取客户端ip
* 查看map中是否存在这个IP,进行计算
*/
//得到application

ServletContext app=filterconfig.getServletContext();
Map<String ,Integer> map=(Map<String ,Integer>)app.getAttribute("map");
//获取客户端的ip
String ip=request.getRemoteAddr();
//判断
if(map.containsKey(ip)){
int count=map.get(ip);
map.put(ip, count+1);
}else{
map.put(ip, 1);


}

app.setAttribute("map", map);

chain.doFilter(request, response); //至进行统计,放行
}

@Override
public void init(FilterConfig fconfig) throws ServletException {
System.out.println("过滤器畜生");
//创建之后马上执行,用作初始化,服务器启动就会执行,而且指执行一次


this.filterconfig=fconfig;
}

-----------------------------------------------------------------------

2、新建一个监听

public class Alisten implements ServletContextListener {

public Alisten() {

}

/**
* 在服务器启动时创建Map,保存到ServletContext
*/

public void contextInitialized(ServletContextEvent sce) {
// 创建map

Map<String, Integer> map = new LinkedHashMap<String, Integer>();
// 得到ServletContext
ServletContext application = sce.getServletContext();
application.setAttribute("map", map);
}

public void contextDestroyed(ServletContextEvent arg0) {

}

-------------------------------------------------------------------

3、写一个jsp页面

<body>
<h1 align="center">显示结果</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>
</c:forEach>
</table>
</body>

 

posted @ 2017-04-21 09:34  贱贱的小帅哥  阅读(299)  评论(0编辑  收藏  举报