利用监听器实现网站在线人数统计

ServletContextListenerImpl.java代码

public class ServletContextListenerImpl implements ServletContextListener {
public void contextDestroyed(ServletContextEvent event) {
ServletContext application = event.getServletContext();
application.removeAttribute("onLineNum");
}
public void contextInitialized(ServletContextEvent event) {
//利用servletContextEvent对象创建servletContext
int num = 0;
ServletContext application = event.getServletContext();
application.setAttribute("onLineNum", num);//初始默认在线人数为0
}
}

HttpSessionListnerImpl.java代码

public class HttpSessionListnerImpl implements HttpSessionListener {

public void sessionCreated(HttpSessionEvent event) {
//通过event获得servletContext对象
ServletContext application = event.getSession().getServletContext();
//拿到servletContext空间中储存的onLineNum
Integer num = (Integer)application.getAttribute("onLineNum");
if(num != null){
//如果存在,则将拿到的数量加一并到重新放入到servletContext空间中
num = num + 1;
application.setAttribute("onLineNum", num);
} else {
//如果不存在,则设置onLineNum为1
application.setAttribute("onLineNum", 1);
}
}

public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("一个session关闭了");
//通过event获得servletContext对象
ServletContext application = event.getSession().getServletContext();
//拿到servletContext空间中储存的onLineNum
Integer num = (Integer)application.getAttribute("onLineNum");
num = num - 1;
//将拿到的数量减一并到重新放入到servletContext空间中
application.setAttribute("onLineNum", num);
}
}

对应的在web.xml文件中进行监听器配置

<listener>
  <listener-class>
  com.hk.listener.ServletContextListenerImpl
  </listener-class>
  </listener>
  
  <listener>
  <listener-class>
  com.hk.listener.HttpSessionListnerImpl
  </listener-class>
  </listener>

jsp代码

<body>
  当前在线人数:${onLineNum }

</body>

测试结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值