使用SessionListener统计在线人数

1.编辑监听类:
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
import org.apache.log4j.Logger;

/***/ /**
*Session监听器
*/


public class SessionListener implements HttpSessionListener ... {
privateLoggerlogger=Logger.getLogger(this.getClass());

privatelongcount=0;
publicsynchronizedvoidsessionCreated(HttpSessionEventse)...{
this.count=this.count+1;
se.getSession().getServletContext().setAttribute(
"count",this.count+"");
}

publicsynchronizedvoidsessionDestroyed(HttpSessionEventse)...{
this.count=this.count-1;
se.getSession().getServletContext().setAttribute(
"count",this.count+"");
}

}

2.注册监听到web.xml:

< web - app >
...
< listener >
< listener - class > com.link2friend.friend.sessionlistener.SessionListener </ listener - class >
</ listener >
...
</ web - app >

3.网页上使用:

<%=application.getAttribute("count")%>

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