码迷,mamicode.com
首页 > 其他好文 > 详细

Listener监听器详解(转)

时间:2015-12-03 23:01:35      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

在Servlet技术中已经定义了一些事件,并且我们可以针对这些事件来编写相关的事件监听器,从而对事件作出相应处理。Servlet事件主要有3类:Servlet上下文事件、会话事件与请求事件。下面具体讲解这3类事件的监听器实现。

1.对Servlet上下文进行监听

可以监听ServletContext对象的创建和删除以及属性的添加、删除和修改等操作。该监听器需要使用到如下两个接口类:

   ● ServletContextAttributeListener:监听对ServletContext属性的操作,如增加、删除、修改操作。

   ● ServletContextListener:监听ServletContext。

当创建ServletContext时,激发contextInitialized (ServletContextEvent sce)方法;

当销毁ServletContext时,激发contextDestroyed(ServletContext- Event sce)方法。

2.监听Http会话

可以监听Http会话活动情况、Http会话中属性设置情况,也可以监听Http会话的active、paasivate情况等。

该监听器需要使用到如下多个接口类:

   ● HttpSessionListener:监听HttpSession的操作。

当创建一个Session时,激发session Created (SessionEvent se)方法;

当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)    方法。

   ● HttpSessionActivationListener:用于监听Http会话active、passivate情况。

   ● HttpSessionAttributeListener:监听HttpSession中属性的操作。

当在Session增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se) 方法;

当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;

在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。

3.对客户端请求进行监听

对客户端的请求进行监听是在Servlet 2.4规范中新添加的一项技术,使用的接口类如下:

   ● ServletRequestListener接口类。

   ● ServletRequestAttrubuteListener接口类。

Servlet上下文监听器实例

下面编写一个实例,使它能够对ServletContext以及属性进行监听。由以上介绍可知,该类需要实现ServletContextAttributeListener和ServletContextListener接口类,其详细代码如下:

[java] view plaincopy技术分享技术分享
 
  1. package servlet;  
  2.   
  3. import java.io.FileOutputStream;  
  4.   
  5. import java.io.PrintWriter;  
  6.   
  7. import javax.servlet.ServletContext;  
  8.   
  9. import javax.servlet.ServletContextAttributeEvent;  
  10.   
  11. import javax.servlet.ServletContextAttributeListener;  
  12.   
  13. import javax.servlet.ServletContextEvent;  
  14.   
  15. import javax.servlet.ServletContextListener;  
  16.   
  17. public class MyServletContextListener   
  18.   
  19.              implements ServletContextListener,ServletContextAttributeListener{  
  20.   
  21.          private ServletContext context = null;                                              //定义一个ServletContext对象变量,赋为null  
  22.   
  23.          public void contextInitialized(ServletContextEvent s) {  
  24.   
  25.                    //TODO 该方法实现了ServletContextListener接口定义的方法,对ServletContext进行初始化  
  26.   
  27.                    this.context = s.getServletContext();                              //初始化一个ServletContext对象  
  28.   
  29.                    print("ServletContext初始化......");                                 //打印出该方法的操作信息  
  30.   
  31.          }  
  32.   
  33.          public void contextDestroyed(ServletContextEvent s) {  
  34.   
  35.                    //TODO 该方法实现了ServletContextListener接口类定义方法,用于释放ServletContext对象  
  36.   
  37.                    this.context = null;  
  38.   
  39.                    print("ServletContext被释放......");  
  40.   
  41.          }  
  42.   
  43.          public void attributeAdded(ServletContextAttributeEvent sa) {  
  44.   
  45.                    //TODO 当上下文添加属性时,将调用该方法。这里只是将添加的属性信息打印出来  
  46.   
  47.                    print("增加ServletContext对象的一个属性:attributeAdded(‘"+sa.getName()+"‘,‘ "+sa.getValue()+"‘)");  
  48.   
  49.          }  
  50.   
  51.          public void attributeRemoved(ServletContextAttributeEvent sa) {  
  52.   
  53.                    //TODO 当把ServletContext中的某个属性删除时,调用该方法  
  54.   
  55.                    print("删除ServletContext对象的某一个属性:attributeRemoved(‘  
  56.   
  57.                             "+sa.getName()+"‘,‘")");  
  58.   
  59.          }  
  60.   
  61.          public void attributeReplaced(ServletContextAttributeEvent sa) {  
  62.   
  63.                    //TODO 当上下文进行属性值更新时,将调用该方法  
  64.   
  65.                    print("更改ServletContext对象的某一个属性:attributeReplaced(‘  
  66.   
  67.                             "+sa.getName()+"‘,‘"+sa.getValue()+"‘)");     
  68.   
  69.          }          
  70.   
  71.          private void print(String message){  
  72.   
  73.                    //调用该方法在txt文件中打印出message字符串信息  
  74.   
  75.                    PrintWriter out = null;  
  76.   
  77.                    try{  
  78.   
  79.                             out = new PrintWriter(new FileOutputStream("D:\\output.txt",true));  
  80.   
  81.                             out.println(new java.util.Date().toLocaleString()+" ContextListener: "+message);  
  82.   
  83.                             out.close();  
  84.   
  85.                    }  
  86.   
  87.                    catch(Exception e)  
  88.   
  89.                    {  
  90.   
  91.                             e.printStackTrace();  
  92.   
  93.                    }  
  94.   
  95.          }  
  96.   
  97. }  

 

程序说明:该监听器类实现了ServletContextAttributeListener和ServletContextListener两个接口类中的5个方法:

   ● contextInitialized(ServletContextEvent s)方法用来初始化ServletContext对象。

   ● contextDestroyed(ServletContextEvent s)方法在上下文中删除某个属性时调用。

   ● attributeAdded(ServletContextAttributeEvent sa)方法在上下文中添加一个新的属性时调用。

   ● attributeReplaced(ServletContextAttributeEvent sa)方法在更新属性时调用。

   ● attributeRemoved(ServletContextAttributeEvent sa)方法在上下文中删除某个属性时会被调用。

在使用这个监听器之前还需要在Web模块中的web.xml配置文件中进行声明,代码如下:

[java] view plaincopy技术分享技术分享
 
  1. <listener>  
  2.   
  3. <listener-class>servlet.MyServletContextListener</listener-class>  
  4.   
  5. </listener>  


 

接下来就编写JSP程序来操作ServletContext的属性,看看监听器程序作出什么反应,该JSP的一段代码如下:

[java] view plaincopy技术分享技术分享
 
  1. <%  
  2.   
  3. out.println(“Test ServletContextListener”);  
  4.   
  5. application.setAttribute(“userid”,”zzb”);                    //添加一个属性  
  6.   
  7. application.setAttribute(“userid”,”zzb2”);                           //替换掉已经添加的属性  
  8.   
  9. application.removeAttribute(“userid”);                      //删除该属性  
  10.   
  11. %>  


 

代码说明:当第一次添加属性userid时,监听器调用contextInitialized(ServletContextEvent s)初始化监听方法和attributeAdded(ServletContextAttributeEvent sa)添加属性监听方法。

可以查看D根目录下的output.txt文件内容,如下:

2006-7-12 14:07:50 ContextListener: ServletContext初始化......

2006-7-12 14:13:55 ContextListener: 增加ServletContext对象的一个属性:attributeAdded(‘userid‘,‘zzb‘)

2006-7-12 14:13:55 ContextListener: 更改ServletContext对象的某一个属性:attributeReplaced (‘userid‘,‘zzb2‘)

2006-7-12 14:13:55 ContextListener: 删除ServletContext对象的某一个属性:attributeRemoved (‘userid‘)

该log文件记录了监听器所做的动作。

12.2.2 Http会话监听器实例

通过上一个监听器实例,读者应该对监听器的实现过程有所了解,本小节将要介绍基于Http会话的监听器。首先创建监听器类MySessionListener.java,其源代码如下:

[java] view plaincopy技术分享技术分享
 
  1. package servlet;  
  2.   
  3. import java.io.FileOutputStream;  
  4.   
  5. import java.io.PrintWriter;  
  6.   
  7. import javax.servlet.ServletContext;  
  8.   
  9. import javax.servlet.ServletContextEvent;  
  10.   
  11. import javax.servlet.ServletContextListener;  
  12.   
  13. import javax.servlet.http.HttpSessionActivationListener;  
  14.   
  15. import javax.servlet.http.HttpSessionAttributeListener;  
  16.   
  17. import javax.servlet.http.HttpSessionBindingEvent;  
  18.   
  19. import javax.servlet.http.HttpSessionEvent;  
  20.   
  21. import javax.servlet.http.HttpSessionListener;  
  22.   
  23. public class MySessionListener   
  24.   
  25.        implements HttpSessionActivationListener,HttpSessionAttributeListener,  
  26.   
  27.                   HttpSessionListener,ServletContextListener{  
  28.   
  29.     ServletContext context = null;  
  30.   
  31.          int users = 0;  
  32.   
  33.          public void sessionWillPassivate(HttpSessionEvent arg0) {  
  34.   
  35.                    //监听Http会话的passivate情况  
  36.   
  37.                    print("sessionWillPassivate("+arg0.getSession().getId()+")");  
  38.   
  39.          }  
  40.   
  41.          public void sessionDidActivate(HttpSessionEvent arg0) {  
  42.   
  43.                    //监听Http会话的active情况  
  44.   
  45.                    print("sessionDidActivate("+arg0.getSession().getId()+")");  
  46.   
  47.          }  
  48.   
  49.          public void attributeAdded(HttpSessionBindingEvent arg0) {  
  50.   
  51.                    //监听Http会话中的属性添加  
  52.   
  53.          print("attributeAdded(‘"+arg0.getSession().getId()+"‘,‘"+arg0.getName()+"‘,‘"+arg0.getValue()+"‘)");  
  54.   
  55.          }  
  56.   
  57.          public void attributeRemoved(HttpSessionBindingEvent arg0) {  
  58.   
  59.                    //监听Http会话中的属性删除  
  60.   
  61.          print("attributeRemoved(‘"+arg0.getSession().getId()+"‘,‘"+arg0.getName()+"‘,‘"+arg0.getValue()+"‘)");  
  62.   
  63.          }  
  64.   
  65.          public void attributeReplaced(HttpSessionBindingEvent arg0) {  
  66.   
  67.                    //监听Http会话中的属性更改操作  
  68.   
  69.          print("attributeReplaced(‘"+arg0.getSession().getId()+"‘,‘"+arg0.getName()+"‘,‘"+arg0.getValue()+"‘)");  
  70.   
  71.          }  
  72.   
  73.          public void sessionCreated(HttpSessionEvent arg0) {  
  74.   
  75.                    //Http会话的创建监听  
  76.   
  77.                    users++;                                                                              //创建一个会话,把users变量加1  
  78.   
  79.                    print("sessionCreated(‘"+arg0.getSession().getId()+"‘),目前拥有"+users+"个用户");  
  80.   
  81.                    context.setAttribute("users",new Integer(users));        //把会话数设置到ServletContext的属性users中  
  82.   
  83.          }  
  84.   
  85.          public void sessionDestroyed(HttpSessionEvent arg0) {  
  86.   
  87.                    //Http会话的释放监听  
  88.   
  89.                    users--;                                                                                //释放一个会话,把users变量减1  
  90.   
  91.                    print("sessionDestroyed(‘"+arg0.getSession().getId()+"‘),目前拥有"+users+"个用户");  
  92.   
  93.                    context.setAttribute("users",new Integer(users));        //把会话数设置到ServletContext的属性users中  
  94.   
  95.          }  
  96.   
  97.          public void contextInitialized(ServletContextEvent arg0) {  
  98.   
  99.                    //该方法实现了ServletContextListener接口定义的方法,对ServletContext进行初始化  
  100.   
  101.                    this.context = arg0.getServletContext();                       //初始化ServletContext对象  
  102.   
  103.                    print("ServletContext初始化......");                                 //打印出该方法的操作信息  
  104.   
  105.          }  
  106.   
  107.          public void contextDestroyed(ServletContextEvent arg0) {  
  108.   
  109.                    //监听Servlet上下文被释放  
  110.   
  111.                    this.context = null;                                                             //释放ServletContext对象  
  112.   
  113.                    print("ServletContext被释放......");                                 //打印出该方法的操作信息  
  114.   
  115.          }  
  116.   
  117.          private void print(String message){  
  118.   
  119.                    //调用该方法在txt文件中打印出message字符串信息  
  120.   
  121.                    PrintWriter out = null;  
  122.   
  123.                    try{  
  124.   
  125.                             out = new PrintWriter(new FileOutputStream("d:\\output.txt",true));  
  126.   
  127.                             out.println(new java.util.Date().toLocaleString()+" SessionListener: "+message);  
  128.   
  129.                             out.close();  
  130.   
  131.                    }  
  132.   
  133.                    catch(Exception e)  
  134.   
  135.                    {  
  136.   
  137.                             e.printStackTrace();  
  138.   
  139.                    }  
  140.   
  141.          }  
  142.   
  143. }  


 

程序说明:

(1)该程序实现了HttpSessionListener接口类中的两个方法:

   ● sessionCreated(HttpSessionEvent arg0)方法进行Http会话创建的监听,如果Http会话被创建将调用该方法。

   ● sessionDestroyed(HttpSessionEvent arg0)方法对Http会话销毁进行监听,如果某个Http会话被释放将调用该方法。

(2)实现HttpSessionActivationListener接口类中的如下两个方法:

   ● sessionDidActivate(HttpSessionEvent arg0)方法对Http会话处于active情况进行监听。

   ● sessionWillPassivate(HttpSessionEvent arg0)方法对Http会话处于passivate情况进行监听。

(3)实现HttpSessionAttributeListener接口类中的如下3种方法:

   ● attributeAdded(HttpSessionBindingEvent arg0)方法对Http会话中属性添加进行监听。

   ● attributeReplaced(HttpSessionBindingEvent arg0)方法对Http会话中属性修改进行监听。

   ● attributeRemoved(HttpSessionBindingEvent arg0)方法对Http会话中属性删除进行监听。

(4)另外,该程序中还实现了ServletContextListener接口类,该类的实现方法已经在12.2.1小节中有所介绍。

同样需要在web.xml配置文件进行该监听器的声明,配置方法如12.2.1小节介绍。该监听器实现了在线会话人数的统计,当一个会话创建时,users变量将加1;当销毁一个会话对象的时候,users变量将减1。

下面创建测试的JSP页面程序,代码如下:

[java] view plaincopy技术分享技术分享
 
  1. <%  
  2.   
  3. out.println("Test SessionListener");  
  4.   
  5. session.setAttribute("username","zzb1");                 //在Http会话中设置一个用户username属性  
  6.   
  7. session.setAttribute("username","zzb2");                 //修改之上添加的username属性  
  8.   
  9. session.removeAttribute("username");                    //删除创建的username属性  
  10.   
  11. session.invalidate();                                                     //passivate Http会话  
  12.   
  13. %>  


 

执行效果可以查看output.txt文档内容,如下:

2006-7-12 15:24:47 SessionListener: ServletContext初始化......

2006-7-12 15:25:47 SessionListener: sessionCreated(‘720C4654847ECE025DF6A8AF09117212‘),目前拥有1个用户

2006-7-12 15:25:47 SessionListener:

attributeAdded(‘720C4654847ECE025DF6A8AF09117212‘,‘username‘,‘zzb1‘)

2006-7-12 15:25:47 SessionListener:

attributeReplaced(‘720C4654847ECE025DF6A8AF09117212‘,‘username‘,‘zzb1‘)

2006-7-12 15:25:47 SessionListener:

attributeRemoved(‘720C4654847ECE025DF6A8AF09117212‘,‘username‘,‘zzb2‘)

2006-7-12 15:25:47 SessionListener: sessionDestroyed(‘720C4654847ECE025DF6A8AF09117212‘),目前拥有0个用户

12.2.3 客户端请求监听器实例

对客户端请求进行监听的技术是在Servlet 2.4版本之后才出现的。一旦监听程序能够获得客户端请求,就可以对所有客户端请求进行统一处理。例如,一个Web程序如果在本机访问,就可以不登录,如果是远程访问,即需要登录。这是通过监听客户端请求,从请求中获取到客户端地址,并通过地址来作出相应的处理。

 

Listener监听器详解(转)

标签:

原文地址:http://www.cnblogs.com/zxw0004/p/5017701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!