监听器完成 - 统计在线人数

import java.util.List;
import java.util.Vector;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


/**
*
* @author db2admin
*
* 监听HttpSession对象,统计在线人数
*/
public class HttpSessionListenerHandle implements HttpSessionListener,
   HttpSessionAttributeListener
{
private String AttributeName;

private Object AttributeValue;

private List OnlineNumber=new Vector(10);// 保存sessionId的List

private static HttpSessionListenerHandle HttpSessionListenerInstence = new HttpSessionListenerHandle();

public static HttpSessionListenerHandle getInstence()
{
   return HttpSessionListenerInstence;
}

public List getSessionIdList()
{
   return this.OnlineNumber;
}

public Integer getOnlineNumber()
{
   return this.OnlineNumber.size();
}

public void attributeAdded(HttpSessionBindingEvent se)
{
   AttributeName = se.getName();
   AttributeValue = se.getValue();
   System.out.println("####Session增加一个属性:");
   System.out.println("AttributeName:" + AttributeName);
   System.out.println("AttributeValue:" + AttributeValue);

}

public void attributeRemoved(HttpSessionBindingEvent se)
{
   AttributeName = se.getName();
   AttributeValue = se.getValue();
   System.out.println("####Session删除一个属性:");
   System.out.println("AttributeName:" + AttributeName);
   System.out.println("AttributeValue:" + AttributeValue);

}

public void attributeReplaced(HttpSessionBindingEvent se)
{
   AttributeName = se.getName();
   AttributeValue = se.getValue();
   System.out.println("####Session替换一个属性:");
   System.out.println("AttributeName:" + AttributeName);
   System.out.println("AttributeValue:" + AttributeValue);

}

public void sessionCreated(HttpSessionEvent se)
{
   OnlineNumber.add(se.getSession().getId());
   System.out.println("####创建一个Session");
   System.out.println("Session Id:" + se.getSession().getId());
   System.out.println("当前在线人数:" + getOnlineNumber());

}

/**
* 可以用于统计用户在线数
*/
public void sessionDestroyed(HttpSessionEvent se)
{
   OnlineNumber.remove(se.getSession().getId());
   System.out.println("####销毁一个Session");
   System.out.println("Session id:" + se.getSession().getId());
   System.out.println("当前在线人数:" + getOnlineNumber());
}

}

在web.xml中配置如下:

.............

<listener>
   <listener-class>
    com.cq.web.listener.HttpSessionListenerHandle
   </listener-class>
</listener>

.........................

你可能感兴趣的:(xml,Web,servlet)