简单的java web 统计在线人数实现方法

建立一个class页面 实现ServletContextListener和HttpSessionListener接口

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

import com.sun.org.apache.bcel.internal.generic.NEW;

public class OnLineUser implements ServletContextListener,HttpSessionListener{

 private int counts;
 private ServletContext cxt;
 public void contextDestroyed(ServletContextEvent arg0) {
  // TODO Auto-generated method stub
  
 }

 public void contextInitialized(ServletContextEvent e) {
  // TODO Auto-generated method stub
  cxt=e.getServletContext();//拿到ServletContext
 }

 public void sessionCreated(HttpSessionEvent arg0) {
  // TODO Auto-generated method stub
  counts ++;
  cxt.setAttribute("counts", new Integer(counts));//setAttribute(字符串,对象型)
 }

 public void sessionDestroyed(HttpSessionEvent arg0) {
  // TODO Auto-generated method stub
  counts--;
  cxt.setAttribute("counts", new Integer(counts));
 }

}

 

 

建立一个servlet 其中共享变量注意:

int counts1 = Integer.parseInt(cxt.getAttribute("counts").toString());//Object型不能直接转换成 Int型,要先转换成String型再转Int型

你可能感兴趣的:(java,Web,servlet,Integer,Class,import)