分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>

 

转载于:https://www.cnblogs.com/danyuzhu11/p/6741942.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值