谈谈Listener Servlet的应用

来源:互联网 发布:波士顿矩阵图实例 编辑:程序博客网 时间:2024/05/16 03:25
谈谈Listener Servlet的应用
作者:刘晓华 发文时间:2004.11.23
    Listener是Servlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。当增加一个HttpSession时,就激发sessionCreated(HttpSessionEvent se)方法,这样就可以给在线人数加1。常用的监听接口有以下几个:
    
  • ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改属性。
        
  • ServletContextListener监听ServletContext。当创建ServletContext时,激发contextInitialized(ServletContextEvent sce)方法;当销毁ServletContext时,激发contextDestroyed(ServletContextEvent sce)方法。
        
  • HttpSessionListener监听HttpSession的操作。当创建一个Session时,激发session Created(HttpSessionEvent se)方法;当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法。
        
  • HttpSessionAttributeListener监听HttpSession中的属性的操作。当在Session增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se) 方法;当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。

        下面我们开发一个具体的例子,这个监听器能够统计在线的人数。在ServletContext初始化和销毁时,在服务器控制台打印对应的信息。当ServletContext里的属性增加、改变、删除时,在服务器控制台打印对应的信息。

        要获得以上的功能,监听器必须实现以下3个接口:
        
  • HttpSessionListener
        
  • ServletContextListener
        
  • ServletContextAttributeListener

        我们看具体的代码,见示例14-9。

        【程序源代码】

    1// ==================== Program Discription =====================2// 程序名称:示例14-9 : EncodingFilter .java3// 程序目的:学习使用监听器4// ==============================================================5import javax.servlet.http.*;6import javax.servlet.*;78public class OnLineCountListener implements HttpSessionListener,ServletContextListener,ServletContextAttributeListener9{10private int count;11private ServletContext context = null;1213public OnLineCountListener()14{15count=0;16//setContext();17}18//创建一个session时激发19public void sessionCreated(HttpSessionEvent se) 20{21count++;22setContext(se);2324}25//当一个session失效时激发26public void sessionDestroyed(HttpSessionEvent se) 27{28count--;29setContext(se);30}31//设置context的属性,它将激发attributeReplaced或attributeAdded方法32public void setContext(HttpSessionEvent se)33{34se.getSession().getServletContext().setAttribute("onLine",new Integer(count));35}36 //增加一个新的属性时激发37public void attributeAdded(ServletContextAttributeEvent event) {3839log("attributeAdded('" + event.getName() + "', '" +40    event.getValue() + "')");4142    }43    44   //删除一个新的属性时激发45    public void attributeRemoved(ServletContextAttributeEvent event) {4647log("attributeRemoved('" + event.getName() + "', '" +48    event.getValue() + "')");4950    }5152//属性被替代时激发53    public void attributeReplaced(ServletContextAttributeEvent event) {5455log("attributeReplaced('" + event.getName() + "', '" +56    event.getValue() + "')");57    }58    //context删除时激发59     public void contextDestroyed(ServletContextEvent event) {6061log("contextDestroyed()");62this.context = null;6364    }6566    //context初始化时激发67    public void contextInitialized(ServletContextEvent event) {6869this.context = event.getServletContext();70log("contextInitialized()");7172    }73    private void log(String message) {7475    System.out.println("ContextListener: " + message);76    }   77}


        【程序注解】
        在OnLineCountListener里,用count代表当前在线的人数,OnLineCountListener将在Web服务器启动时自动执行。当OnLineCountListener构造好后,把count设置为0。每增加一个Session,OnLineCountListener会自动调用sessionCreated(HttpSessionEvent se)方法;每销毁一个Session,OnLineCountListener会自动调用sessionDestroyed(HttpSessionEvent se)方法。当调用sessionCreated(HttpSessionEvent se)方法时,说明又有一个客户在请求,此时使在线的人数(count)加1,并且把count写到ServletContext中。ServletContext的信息是所有客户端共享的,这样,每个客户端都可以读取到当前在线的人数。

    为了使监听器生效,需要在web.xml里进行配置,如下所示:

    <listener>        <listener-class>OnLineCountListener</listener-class>    </listener>


    测试程序:

    <%@ page contentType="text/html;charset=gb2312" %>


    目前在线人数:

    <font color=red><%=getServletContext().getAttribute("onLine")%></font><br>


    退出会话:

    <form action="exit.jsp" method=post><input type=submit value="exit"></form>


    getServletContext().getAttribute("onLine")获得了count的具体值。客户端调用

    <%session.invalidate() ;%>


        使Session失效,这样监听器就会使count减1。

        【运行程序】
        web.xml做好以上的配置,把OnLineCountListener放在WEB-INF/class目录下,启动Web服务器,在浏览器里输入以下URL(根据具体情况不同):http://127.0.0.1:8080/ch14/listener.jsp

        浏览器将会打印目前在线人数。在服务器端有以下输出:

    …ContextListener: contextInitialized()ContextListener: attributeReplaced('org.apache.catalina.WELCOME_FILES', '[Ljava.lang.String;@1d98a')…ContextListener: attributeAdded('onLine', '1')ContextListener: attributeReplaced('onLine', '1')ContextListener: attributeReplaced('onLine', '0')ContextListener: attributeReplaced('onLine', '1')ContextListener: attributeReplaced('onLine', '2')


    (T111)

    本文选自飞思图书《精通Java核心技术》
  • 原创粉丝点击