`
阅读更多
谈谈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 .java
3 // 程序目的:学习使用监听器
4 // ==============================================================
5 import javax.servlet.http.*;
6 import javax.servlet.*;
7
8 public class OnLineCountListener implements HttpSessionListener,
ServletContextListener,ServletContextAttributeListener
9 {
10 private int count;
11 private ServletContext context = null;
12
13 public OnLineCountListener()
14 {
15 count=0;
16 //setContext();
17 }
18 //创建一个session时激发
19 public void sessionCreated(HttpSessionEvent se)
20 {
21 count++;
22 setContext(se);
23
24 }
25 //当一个session失效时激发
26 public void sessionDestroyed(HttpSessionEvent se)
27 {
28 count--;
29 setContext(se);
30 }
31 //设置context的属性,它将激发attributeReplaced或attributeAdded方法
32 public void setContext(HttpSessionEvent se)
33 {
34 se.getSession().getServletContext().
setAttribute("onLine",new Integer(count));
35 }
36 //增加一个新的属性时激发
37 public void attributeAdded(ServletContextAttributeEvent event) {
38
39 log("attributeAdded('" + event.getName() + "', '" +
40     event.getValue() + "')");
41
42     }
43    
44    //删除一个新的属性时激发
45     public void attributeRemoved(ServletContextAttributeEvent event) {
46
47 log("attributeRemoved('" + event.getName() + "', '" +
48     event.getValue() + "')");
49
50     }
51
52 //属性被替代时激发
53     public void attributeReplaced(ServletContextAttributeEvent event) {
54
55 log("attributeReplaced('" + event.getName() + "', '" +
56     event.getValue() + "')");
57     }
58     //context删除时激发
59      public void contextDestroyed(ServletContextEvent event) {
60
61 log("contextDestroyed()");
62 this.context = null;
63
64     }
65
66     //context初始化时激发
67     public void contextInitialized(ServletContextEvent event) {
68
69 this.context = event.getServletContext();
70 log("contextInitialized()");
71
72     }
73     private void log(String message) {
74
75     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核心技术》
分享到:
评论
1 楼 zouzaibianyuan 2008-12-16  

相关推荐

Global site tag (gtag.js) - Google Analytics