监听器HttpSessionListener

类实现HttpSessionListener接口

重写这两个方法————————————

创建时机:当用户访问项目的时候

public void sessionCreated(HttpSessionEvent event){

  //从作用域中取值

  Integer num=(Integer) event.getSession().getServletContext().getAttribute("ONLINE_NUM");

  //第一次进入num=null;

  if(num==null){

  num=1;

  }else{

  num++

  }

  //把值放入作用域中

  event.getSession().getServletContext().setAttribute()

}

  

public void sessionDestroyed(HttpSessionEvent event){

 //从作用域中取值

  Integer num=(Integer) event.getSession().getServletContext().getAttribute("ONLINE_NUM");

  //第一次进入num=null;

  if(num==null){

  num=0;

  }else{

  num--

  }

  //把值放入作用域中

  event.getSession().getServletContext().setAttribute()

}

销毁时机:1.session失效   session.invalidate("ONLINE_NUM",num)  

    2.session 超时

注意

ServletContext,是一个全局的储存信息的空间,服务器开始,其就存在,服务器关闭,其才释放。

 没有实例化,需要在在Web.xml中配置

<!--配置HttpSessionListener的启动-->

<listener>

<listener-class>该类全类名</listener-class>

</listener>

原文地址:https://www.cnblogs.com/javaxiaodoufu/p/7381694.html