⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 onlinelistener.java

📁 JSP+JavaBean+Servlet 办公自动化管理系统由前台管理和后台管理两大部分组成。 前台管理模块实现:公告管理、公文管理、员工管理、部门信息、收发信息和优秀员工管理6部分。 后台管理
💻 JAVA
字号:
/*
*使用Servlet监听器可以统计在线用户,具体实现方法如下:
*通过ServletContext监听初始化一个application对象,保存在线用户列表;
*通过Session监听当用户登录成功设置Session属性时将用户名保存在列表中;
*通过Session监听当用户注销登录时将用户名从列表中删除。
*/
package com.listener;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class OnlineListener implements ServletContextListener,ServletContextAttributeListener,HttpSessionListener,HttpSessionAttributeListener {
    private ServletContext application = null ;
    private HttpSession session = null ;
    private static int count = 0;
    public void contextInitialized(ServletContextEvent sce) {
        
        //初始化一个application对象
        this.application=sce.getServletContext() ;
        //设置一个列表属性,用于保存在线用户名
        this.application.setAttribute("online", new ArrayList()) ;
    }
    public void contextDestroyed(ServletContextEvent sce) {
    }
    public void attributeAdded(ServletContextAttributeEvent scab) {
    }
    public void attributeRemoved(ServletContextAttributeEvent scab) {
    }
    public void attributeReplaced(ServletContextAttributeEvent scab) {
    }
    public void sessionCreated(HttpSessionEvent se) {
    	count++;
    	System.out.println("****************你是第 "+count+" 位用户******************");
    }
    public void sessionDestroyed(HttpSessionEvent se) {
        count--;
        //取得用户名列表
        List online=(List)this.application.getAttribute("online") ;
        //取得当前用户ID
        String userId=(String)se.getSession().getAttribute("id") ;
        //将此用户名从列表中删除
        online.remove(userId) ;
        System.out.println("=======================欢迎下次再来!================================");
        //将删除后的列表重新设置到application属性中
        this.application.setAttribute("online", online) ;
    }
    public void attributeAdded(HttpSessionBindingEvent se) {
        //取得用户名列表
        List online=(List)this.application.getAttribute("online") ;
        //将当前用户名添加到列表中
        online.add(se.getValue()) ;
        System.out.println("=====================你是第 "+online.size()+" 位登录用户,谢谢你的光临!===============================");
        //将添加后的列表重新设置到application属性中
        this.application.setAttribute("online", online) ;
    }
    public void attributeRemoved(HttpSessionBindingEvent se) {
    }
    public void attributeReplaced(HttpSessionBindingEvent se) {
    }
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -