JavaWeb-监视器

一、监听器

实现一个监听器的接口;

监听器类

package com.kuang.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();
        // 打印每个 Session的 ID
		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销毁:
	 * 1. 手动销毁 se.getSession().invalidate();
	 * 2. 自动销毁 在 web.xml中添加
	 * 		<session-config>
	 * 			<session-timeout>1</session-timeout>
	 * 		</session-config>
	 */
	// 一旦销毁 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);
	}
}

在 web.xml中配置监听器

<!-- 注册监听器 -->
<listener>
    <listener-class>com.kuang.listener.OnlineCountListener</listener-class>
</listener>
  • 注意:
    • 如果数据错误,可以清理浏览器的 Cookie记录
posted @ 2021-02-21 09:48    阅读(87)  评论(0)    收藏  举报