web.xml
OnlineCounter.java
HttpSessionListenerDemo.java
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<listener>
<listener-class>util.HttpSessionListenerDemo</listener-class>
</listener>
...
OnlineCounter.java
public class OnlineCounter implements Serializable
{
private static int online = 0;
// ** get
public static int getOnline()
{
return online;
}
public static void raise()
{
online++;
}
public static void reduce()
{
online--;
if(online < 0)
{
online = 0;
}
}
}
HttpSessionListenerDemo.java
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.log4j.Logger;
public class HttpSessionListenerDemo implements HttpSessionListener {
static Logger log = Logger.getLogger("blogjavabean");
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
OnlineCounter.raise();
log.debug("HttpSessionListenerDemo current position >> 【sessionCreated】() 执行了!!");
}
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
OnlineCounter.reduce();
log.debug("HttpSessionListenerDemo current position >> 【sessionDestroyed】() 执行了!!");
}
}