package com.fdw.listener;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
//统计网站在线人数
public class OnLine implements HttpSessionListener {
public OnLine() {
super();
}
//创建session的监听
//一旦创建Session,就会触发这个事件
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
System.out.println(httpSessionEvent.getSession().getId());
Integer onlineCount = (Integer)servletContext.getAttribute("onlineCount");
if(onlineCount==null){
onlineCount = new Integer(1);
}else{
int count = onlineCount.intValue();
onlineCount = new Integer(count+1);
}
servletContext.setAttribute("onlineCount",onlineCount);
}
//销毁session监听
//一旦销毁Session,就会触发这个事件
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
}
}
web.xml中注册
com.fdw.listener.OnLine
index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/5/14 0014
Time: 19:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
$Title$
主页面
当前有<%=application.getContext("/").getAttribute("onlineCount")%>人在线
GUI:
适配器模式,继承子类就可以选择性的实现父类的方法



