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>
测试结果