SessionListener统计在线人数

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

/**
* Session监听器
*/

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

  private long count=0;
  public synchronized void sessionCreated(HttpSessionEvent se) {
    this.count=this.count+1;
    se.getSession().getServletContext().setAttribute("count",this.count+"");
  }
  public synchronized void sessionDestroyed(HttpSessionEvent se) {
    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")%>

你可能感兴趣的:(Web)