java监听器实现在线人数统计

本文实例为大家分享了java在线人数统计的具体代码,供大家参考,具体内容如下

1. 项目结构

2. 代码

package com;
 
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
 
/**
 * Application Lifecycle Listener implementation class MyContexxtLis
 *
 */
@WebListener
public class CountListen implements ServletContextListener {
 
  /**
   * Default constructor. 
   */
  public CountListen() {
    // TODO Auto-generated constructor stub
  }
 
 /**
   * @see ServletContextListener#contextInitialized(ServletContextEvent)
   */
  public void contextInitialized(ServletContextEvent arg0) { 
   arg0.getServletContext().setAttribute("count",100);
  }
 
 /**
   * @see ServletContextListener#contextDestroyed(ServletContextEvent)
   */
  public void contextDestroyed(ServletContextEvent arg0) { 
     // TODO Auto-generated method stub
  }
 
}
package com;
 
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
 
 
@WebListener
public class SessionListen implements HttpSessionListener, HttpSessionAttributeListener {
 
  public SessionListen() {
    // TODO Auto-generated constructor stub
  }
 
  public void attributeRemoved(HttpSessionBindingEvent arg0) { 
   System.out.println("remove"+"\t"+arg0.getName()+arg0.getValue());
  }
 
  public void attributeAdded(HttpSessionBindingEvent arg0) { 
   System.out.println("add"+"\t"+arg0.getName()+arg0.getValue());
  }
 
  public void attributeReplaced(HttpSessionBindingEvent arg0) { 
   System.out.println("replace"+"\t"+arg0.getName()+arg0.getValue());
  }
 
  public void sessionCreated(HttpSessionEvent arg0) { 
   System.out.println("session create");
 Integer i=(Integer)arg0.getSession().getServletContext().getAttribute("count");
 i++;
 arg0.getSession().getServletContext().setAttribute("count", i);
 
  }
 
  public void sessionDestroyed(HttpSessionEvent arg0) { 
 Integer i=(Integer)arg0.getSession().getServletContext().getAttribute("count");
 i--;
 arg0.getSession().getServletContext().setAttribute("count", i);
 System.out.println("session destroy"+i);
 
  }
 
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<%session.setMaxInactiveInterval(3); %>
当前在线人数:${count}
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持鸟哥教程(niaoge.com)。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。