监听session中人数

 

import java.io.FileOutputStream;

import java.io.PrintWriter;

 

import javax.servlet.ServletContext;

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

import javax.servlet.ServletException;

import javax.servlet.http.HttpSessionActivationListener;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

 

public final class SessionListener implements HttpSessionActivationListener,

       HttpSessionListener, ServletContextListener {

 

    private static final long serialVersionUID = 1L;

 

    ServletContext context;

 

    int users = 0;

 

    /**

     * Initialization of the servlet. <br>

     *

     * @throws ServletException

     *             if an error occure

     */

    public void init() throws ServletException {

       // Put your code here

    }

 

    public void sessionCreated(HttpSessionEvent event) {

       users++;

       log("sessionCreated(" + event.getSession().getId() + "),目前有" + users

              + "个用户");

       context.setAttribute("users", new Integer(users));

       System.out.println("sessionCreated(" + event.getSession().getId()

              + "),目前有" + users + "个用户");

    }

 

    public void sessionDestroyed(HttpSessionEvent event) {

       users--;

       log("sessionDestroyed(" + event.getSession().getId() + "),目前有" + users

              + "个用户");

    }

 

    public void contextDestroyed(ServletContextEvent sce) {

       log("contextDestroyed()-->ServletContext被销毁");

    }

 

    public void contextInitialized(ServletContextEvent sce) {

       this.context = sce.getServletContext();

       log("contextInitialized()-->ServletContext初始化了");

    }

 

    public void sessionDidActivate(HttpSessionEvent se) {

       log("sessionDidActivate(" + se.getSession().getId() + ")");

    }

 

    public void sessionWillPassivate(HttpSessionEvent se) {

       log("sessionWillPassivate(" + se.getSession().getId() + ")");

    }

 

    private void log(String message) {

       PrintWriter out = null;

       try {

           out = new PrintWriter(new FileOutputStream("c:\\logger.txt"), true);

           out.println(new java.util.Date().toLocaleString()

                  + "::Form ExampleListener:" + message);

           out.close();

       } catch (Exception e) {

           out.close();

           e.printStackTrace();

       }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值