1.设计监听器类
OnlineListener.java
package com.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnlineListener implements HttpSessionListener {
private static int onlineCount=0;
public void sessionCreated(HttpSessionEvent sessionEvent) {onlineCount++;}
public void sessionDestroyed(HttpSessionEvent sessionEvent) {
if(onlineCount>0) onlineCount–;
}
public static int getOnlineCount() {return onlineCount;}
}
2.修改web.xml
<listener>
<listener-class>com.listener.OnlineListener</listener-class>
</listener>
3.显示在线人数的页面
online.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="com.listener.OnlineListener" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>在线人数显示页面</title>
</head>
<body>
<h2>当前在线人数:<%=OnlineListener.getOnlineCount() %></h2>
</body>
</html>
评论