1. 程式人生 > >使用ServletContextListener和HttpSessionListener兩種監聽器實現記錄當前網站線上人數

使用ServletContextListener和HttpSessionListener兩種監聽器實現記錄當前網站線上人數

web.xml中配置:

 <listener>
   <listener-class>com.mcm.listener.ServletContextListenerImpl</listener-class>
  </listener>
  <listener>
   <listener-class>com.mcm.listener.HttpSessionListenerImpl</listener-class>
  </listener>

ServletContextListenerImpl類:

package com.mcm.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ServletContextListenerImpl implements ServletContextListener {

public void contextDestroyed(ServletContextEvent event) {
  ServletContext application = event.getServletContext();
  application.removeAttribute("onLineNum");
}

public void contextInitialized(ServletContextEvent event) {
  int num = 0;
  ServletContext application = event.getServletContext();
  application.setAttribute("onLineNum", num);
}

}

HttpSessionListenerImpl類:

package com.mcm.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class HttpSessionListenerImpl implements HttpSessionListener {

 public void sessionCreated(HttpSessionEvent event) {
  ServletContext application = event.getSession().getServletContext();
  Integer num = (Integer) application.getAttribute("onLineNum");
  if(num != null){
   int count = num;
   count = count + 1;
   application.setAttribute("onLineNum", count);
  }
 }

 public void sessionDestroyed(HttpSessionEvent event) {
  ServletContext application = event.getSession().getServletContext();
  Integer num = (Integer) application.getAttribute("onLineNum");
  int count = num;
  count = count - 1;
  application.setAttribute("onLineNum", count);
  
 }

}

index.jsp中:

當前線上人數:${onLineNum }

結果: