Java监听器Listener使用详解

转载请注明原文地址: http://www.cnblogs.com/ygj0930/p/6374384.html

在我的项目中有具体应用:https://github.com/ygj0930/CoupleSpace

     监听器用于监听web应用中某些对象、信息的创建、销毁、增加,修改,删除等动作的发生,然后作出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用监听器对象中的方法。常用于统计在线人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等等。

    分类:

    按监听的对象划分,可以分为

  • ServletContext对象监听器
  • HttpSession对象监听器
  • ServletRequest对象监听器

    按监听的事件划分

  • 对象自身的创建和销毁的监听器
  • 对象中属性的创建和消除监听器
  • session中的某个对象的状态变化监听器

    示例:用监听器统计网站在线人数

    原理:每当有一个访问连接到服务器时,服务器就会创建一个session来管理会话。那么我们就可以通过统计session的数量来获得当前在线人数。

    所以这里用到的是HttpSessionListener。

    1:创建监听器类,实现HttpSessionListener接口。

    

   

    2:重写监听器类中的方法

复制代码
public class onLineCount implements HttpSessionListener {

    public int count=0;//记录session的数量
    public void sessionCreated(HttpSessionEvent arg0) {//监听session的创建
        count++;
        arg0.getSession().getServletContext().setAttribute("Count", count);

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {//监听session的撤销
        count--;
        arg0.getSession().getServletContext().setAttribute("Count", count);
    }

}
复制代码

    3:在web.xml中配置监听器。注意:监听器>过滤器>serlvet,配置的时候要注意先后顺序

  <listener>
     <listener-class>com.ygj.control.onLineCount</listener-class>
  </listener>

    在Servlet3.0中,监听器的配置可以直接在代码中通过注释来完成,无需在web.xml中再配置。

复制代码
@WebListener   //在此注明以下类是监听器
public class onLineCount implements HttpSessionListener {

    public int count=0;
    public void sessionCreated(HttpSessionEvent arg0) {
        count++;
        arg0.getSession().getServletContext().setAttribute("Count", count);

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {
        count--;
        arg0.getSession().getServletContext().setAttribute("Count", count);
    }
复制代码

    4:在显示在线人数处通过session.getAttribute("Count")即可获取在线人数值。

   

    附:常用监听器

    除了上面监听session建立与销毁的listener外,还有以下几个常用的监听器。

    1:监听session属性的增加、移除以及属性值改变的HttpSessionAttributeListener

    2:监听web上下文的初始化(服务器已准备好接收请求)与销毁的ServletContextListener

    3:监听web上下文属性的增加、删除、属性值变化的ServletContextAttributeListener

  

    4:监听request的创建与销毁的ServletRequestListener

    5:监听request的属性的增加、删除、属性值变化的ServletRequestAttributeListener

猜你喜欢

转载自www.cnblogs.com/zmwf/p/9103207.html