实现一个监听器的接口; (有N种)
1.编写一个监听器
实现监听器的接口
package com.allen.listener; import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; //统计网站在线人数:统计session public class OnlineCountListener implements HttpSessionListener { //创建session监听 //一旦创建session就会触发一次这个事件 public void sessionCreated(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); System.out.println(se.getSession().getId()); Integer onlineCount = (Integer) ctx.getAttribute("onlineCount"); if(onlineCount == null){ onlineCount = new Integer(1); }else{ int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } ctx.setAttribute("onlineCount", onlineCount); } //销毁session监听 //一旦销毁session就会触发一次这个事件 public void sessionDestroyed(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); Integer onlineCount = (Integer) ctx.getAttribute("onlineCount"); if(onlineCount == null){ onlineCount = new Integer(0); }else{ int count = onlineCount.intValue(); onlineCount = new Integer(count-1); } ctx.setAttribute("onlineCount", onlineCount); } }
2.web.xml注册监听器
<listener> <listener-class>com.allen.listener.OnlineCountListener</listener-class> </listener>
这里为了看到效果,我们把数据放到前台展示一下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h1>当前在线 <span style = "color:green;"><%=this.getServletConfig().getServletContext().getAttribute("onlineCount")%></span> 人</h1> </body> </html>
测试:
google浏览器打开:
safari浏览器打开:
后台也是两个sessionId: