Servlet 5 监听

监听

    监听: 对某一些操作进行监视,那么就称为监听

    在web 中的监听主要的功能是永远对ServletContext、Session、Request进行监听的一种操作



1、对application 进行监听

      Application是Servlet 进行监听接口的对象,表示的是整个上下午的环境

      如果要想实现对application 监听则可以使用如下两个接口

      ServletContextListener 是对整个上下文环境的监控

      ServletContextAttributeListener  对属性的监听

  1. package org.gz.servlet.listener;  
  2. import javax.servlet.*;  
  3.   
  4. public class ServletContextListener implements ServleContextListener {  
  5.     public void contextInitialized(ServletContextEvent event) {  
  6.         System.out.println("========容器初始化--->" + event.getServletContext().getContextPath());  
  7.     }  
  8.     public void contextDestroyed(ServletContextEvent event) {  
  9.         System.out.println("=====容器销毁 ----->"+ event.getServletContext().getContextPath());  
  10.     }  
  11. }  
    此时的监听操作只是做了一个简单的输出

过滤器: <filter> 、<filter-mapping>

但是现在的监听器就省事了,直接编写<listener>

    如果现在一个web.xml文件之中包含简单Servlet 、过滤器、监听器,则建议的缩写配置的顺序

     <filter>

     <filter-mapping>

     <listener>

     <servlet>

     <servlet-mapping>

     监听器的配置

  1. <listener>  
  2.         <listener-class>  
  3.             org.gz.servlet.listener.ServletContextListenerdemo  
  4.         </listener-class>  
  5.     </listener  
         只要是容器的启动和关闭都要触发这些操作

         还可以实现 ServletContextAttributeListener 接口,此接口可以直接对属性监听

  1. package org.gz.servlet.listener.attribute;  
  2. import javax.servlet.*;  
  3.   
  4. public class ServletContextAttributeListenerdemo implements ServletContextAttributeListener {  
  5.     public void attributeAdded(ServletContextAttributeEvent scab) {  
  6.         System.out.println("增加属性名称--》" + scab.getName() + " ,属性内容————》" + scab.getValue());  
  7.     }  
  8.     public void attributeRemoved(ServletContextAttributeEvent scab) {  
  9.         System.out.println("删除属性名称--》" + scab.getName() + " ,属性内容————》" + scab.getValue());  
  10.     }  
  11.     public void attributeReplaced(ServletContextAttributeEvent scab) {  
  12.         System.out.println("替换属性名称--》" + scab.getName() + " ,属性内容————》" + scab.getValue());  
  13.     }  
  14. }  
  1. <%@ page contentType="text/html" pageEncoding="GBK"%>  
  2.   
  3. <html>  
  4. <head> <title>欢迎光临</title>  
  5. </head>  
  6. <body>  
  7. <%  
  8.     this.getServletContext().setAttribute("info","www.baidu.com");  
  9. %>  
  10. </body>  
  11. </html>  
  1. <%@ page contentType="text/html" pageEncoding="GBK"%>  
  2.   
  3. <html>  
  4. <head> <title>欢迎光临</title>  
  5. </head>  
  6. <body>  
  7. <%  
  8.     this.getServletContext().removeAttribute("info");  
  9. %>  
  10. </body>  
  11. </html>  

      监听器就是实现接口,覆写方法, 实际上这个与SWING中的操作都是非常类似的


2、对session 监听

在监听器中,针对于session的监听操作提供了三个接口:

      HttpSessionListener

      HttpSessionAttributeListener

      HttpSessionBindingListener

      Session 属于HTTP协议的范畴,所以这些接口肯定在javax.servlet.http 包中定义的。

      在Servlet中如果要想取得session 依靠HttpServletRequest 接口中的getSession()方法

  1. package org.gz.servlet.sesssionlistener;  
  2. import javax.servlet.http.*;  
  3. //  org.gz.servlet.sesssionlistener.HttpSessionListenerDemo  
  4. public class HttpSessionListenerDemo implements HttpSessionListener {  
  5.     public void sessionCreated(HttpSessionEvent se) {  
  6.         System.out.println("session创建,SESSION ID= " + se.getSession().getId());  
  7.     }  
  8.     public void sessionDestroyed(HttpSessionEvent se) {  
  9.                 System.out.println("session销毁,SESSION ID= " + se.getSession().getId());  
  10.     }  
  11. }  
  12. /* 
  13.     <listener> 
  14.         <listener-class> 
  15.             org.gz.servlet.sesssionlistener.HttpSessionListenerDemo 
  16.         </listener-class> 
  17.     </listener> 
  18.  
  19.  
  20. */  
    在讲解内置对象的时候一直强调,当客户端第一次连接到服务器上的时候服务器将会自动为用户创建一个新的session , 同时会分配一个新的 session id。

    现在session 已经被创建,在第一次访问的时候触发了事件,可是还有一点,什么时候销毁呢?

     如果现在想要让一个session 销毁的化,有两种方法,但是这两种方法并不是直接关闭服务器就可以实现的:

            session注销: invalidate()

           超时时间到了, 在tomcat中一般的超时时间是30 分钟。

  1. //D:\java rj\web\tomcat-6.0.18\conf\web.xml  
  2.   
  3.    <session-config>  
  4.         <session-timeout>30</session-timeout>  
  5.     </session-config>  
       当然: 也可以根据自己的情况修改,例如:将本想买中的超时时间修改为1 分钟
  1. //  E:\webdemo\WEB-INF\web.xml  
  2.      
  3. <session-config>  
  4.         <session-timeout>1</session-timeout>  
  5.     </session-config>  
  1. <%@ page contentType="text/html" pageEncoding="GBK"%>  
  2.   
  3. <html>  
  4. <head> <title>欢迎光临</title>  
  5. </head>  
  6. <body>  
  7. <%  
  8.     // 手工注销  
  9.     session.invalidate();  
  10. %>  
  11. </body>  
  12. </html>  

     之前一直强调,当调用invalidate() 方法的时候就意味着 session 的内容将被清空

      不过一般的销毁时间都是设置在30 分钟或更长的时间,如果时间保存长也就意味着占用空间的时间就长


  1. package org.gz.servlet.attributelistener;  
  2. import javax.servlet.http.*;  
  3. //   org.gz.servlet.attributelistener.HttpSessionAttributeListenerdemo   
  4. public class HttpSessionAttributeListenerdemo implements HttpSessionAttributeListener {  
  5.         public void attributeAdded(HttpSessionBindingEvent se) {  
  6.             System.out.println(se.getSession().getId() + " ,增加属性--->名称: " +  
  7.                 se.getName() + ", 属性内容: " + se.getValue() );  
  8.         }  
  9.         public void attributeRemoved(HttpSessionBindingEvent se) {  
  10.             System.out.println(se.getSession().getId() + " ,删除属性--->名称: " +  
  11.                 se.getName() + ", 属性内容: " + se.getValue() );  
  12.         }  
  13.         public void attributeReplaced(HttpSessionBindingEvent se) {  
  14.             System.out.println(se.getSession().getId() + " ,替换属性--->名称: " +  
  15.                 se.getName() + ", 属性内容: " + se.getValue() );  
  16.         }  
  17. }  
  1. <%@ page contentType="text/html" pageEncoding="GBK"%>  
  2.   
  3. <html>  
  4. <head> <title>欢迎光临</title>  
  5. </head>  
  6. <body>  
  7. <%  
  8.     // 手工注销  
  9.     session.removeAttribute("info");  
  10. %>  
  11. </body>  
  12. </html>  
  1. <%@ page contentType="text/html" pageEncoding="GBK"%>  
  2.   
  3. <html>  
  4. <head> <title>欢迎光临</title>  
  5. </head>  
  6. <body>  
  7. <%  
  8.     // 手工注销  
  9.     session.setAttribute("info","www.baidu.com");  
  10. %>  
  11. </body>  
  12. </html>  
    
  1. package org.gz.servlet.bindinglistener;  
  2. import javax.servlet.http.*;  
  3. //  org.gz.servlet.bindinglistener.HttpSessionBindingListenerdemo  
  4. public class HttpSessionBindingListenerdemo implements HttpSessionBindingListener {  
  5.     private String name;  
  6.     public HttpSessionBindingListenerdemo (String name) {  
  7.         this.name = name;  
  8.     }  
  9.       
  10.     public void valueBound(HttpSessionBindingEvent event) {  
  11.         System.out.println("在session中保存HttpSessionBindingListenerdemo 对象(name =  "  
  12.             + this.getName() + " ) , session id = " + event.getSession().getId());  
  13.     }  
  14.     public void valueUnbound(HttpSessionBindingEvent event) {  
  15.         System.out.println("在session中移除HttpSessionBindingListenerdemo 对象(name =  "  
  16.             + this.getName() + " ) , session id = " + event.getSession().getId());  
  17.     }  
  18.     public String getName() {  
  19.         return this.name;  
  20.     }  
  21.     public void setName(String name){  
  22.         this.name = name;  
  23.     }  
  24. }  
  25. /* 
  26.     此处根本就不需要任何配置文件的支持 
  27. */  
  1. <%@ page contentType="text/html" pageEncoding="GBK"%>  
  2. <%@ page import="org.gz.servlet.bindinglistener.*"%>  
  3. <html>  
  4. <head> <title>欢迎光临</title>  
  5. </head>  
  6. <body>  
  7. <%  
  8.     //由于此处需要手工绑定,所以才不需要做任何额外的配置  移除 session.removeAttribute("info");  
  9.     HttpSessionBindingListenerdemo binding = new HttpSessionBindingListenerdemo("gz");  
  10.     session.setAttribute("info",binding);  //直接保存 HttpSessionBindingListenerdemo 对象  
  11. %>  
  12. </body>  
  13. </html>  

3、对request监听

在Servlet 2.4 之后增加了对request 操作的监听,主要使用 ServletRequestListener、 ServletRequestAttributeListener 两个接口

  1. package org.gz.servlet.reqestlistener;  
  2. import javax.servlet.*;  
  3.   
  4. public class ServletRequestListenerdemo implements ServletRequestListener {  
  5.       
  6.     public void requestInitialized(ServletRequestEvent sre) {  
  7.         System.out.println("request 初始化 http://" +   
  8.             sre.getServletRequest().getRemoteAddr() +  
  9.             sre.getServletContext().getContextPath());  
  10.     }  
  11.     public void requestDestroyed(ServletRequestEvent sre) {  
  12.         System.out.println("request 销毁 http://" +   
  13.             sre.getServletRequest().getRemoteAddr() +  
  14.             sre.getServletContext().getContextPath());  
  15.     }   
  16. }  
  1. package org.gz.servlet.reqestattributelistener;  
  2. import javax.servlet.*;  
  3. public class ServletRequestAttributeListenerdemo implements ServletRequestAttributeListener {  
  4.     public void attributeAdded(ServletRequestAttributeEvent srae) {  
  5.         System.out.println("增加request属性-->属性名称: " + srae.getName() + ",属性内容:   " + srae.getValue());  
  6.     }  
  7.     public void attributeRemoved(ServletRequestAttributeEvent srae) {  
  8.         System.out.println("删除request属性-->属性名称: " + srae.getName() + ",属性内容:   " + srae.getValue());  
  9.     }  
  10.     public void attributeReplaced(ServletRequestAttributeEvent srae) {  
  11.         System.out.println("替换request属性-->属性名称: " + srae.getName() + ",属性内容:   " + srae.getValue());  
  12.       
  13.     }  
  14. }  
  15.   
  16. /* 
  17.  
  18. <%@ page contentType="text/html" pageEncoding="GBK"%> 
  19. <%@ page import="org.gz.servlet.bindinglistener.*"%> 
  20. <html> 
  21. <head> <title>欢迎光临</title> 
  22. </head> 
  23. <body> 
  24. <% 
  25.     request.setAttribute("info","www.baidu.com"); 
  26.     //request.setAttribute("info","www.baidu.com");  //将出现替换 
  27.     request.removeAttribute("info"); 
  28. %> 
  29. </body> 
  30. </html> 
  31.  
  32.     <listener> 
  33.         <listener-class> 
  34.             org.gz.servlet.reqestattributelistener.ServletRequestAttributeListenerdemo 
  35.         </listener-class> 
  36.     </listener> 
  37.  
  38. */  

       从实际来讲,对request 范围的监听操作并不是很常见的,用的最多的还是ServletContext、HttpSession监听

4、监听器的实例

     经常会在各个站点上看见一些在线人员的列表操作,实际上次操作就可以通过监听完成

  

         在整个的操作中,需要使用以下几个接口 :

         所有的人员列表应该用集合保存,但是这个集合所有的用户都可以看见,而且以后也要操作,

那么证明在整个监听中必然需要有一个 application 对象保存

        用户登录成功,增加属性,肯定要在属性监听接口中使用

       当用户离开之后,


  1. package org.gz.servlet.context;  
  2. import java.util.*;  
  3. import javax.servlet.*;  
  4. import javax.servlet.http.*;  
  5.   
  6. //  org.gz.servlet.context.OnlineUserList  
  7. public class OnlineUserList implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener {  
  8.     private ServletContext app = null;  
  9.       
  10.     //ServletContextListener  
  11.     public void contextInitialized(ServletContextEvent sce) {  
  12.         this.app = sce.getServletContext();  //初始化  
  13.         this.app.setAttribute("online",new TreeSet());  //设置内容,准备集合  TreeSet 按照 Comparable  二分法排序  
  14.     }  
  15.   
  16.     public void contextDestroyed(ServletContextEvent sce) { }  
  17.     // HttpSessionAttributeList   
  18.     public void attributeAdded(HttpSessionBindingEvent se) {  
  19.         Set all = (Set) this.app.getAttribute("online");    // 取出属性集合  
  20.         all.add(se.getValue());    // 保存属性名字  
  21.         this.app.setAttribute("online",all);  // 重新设置回去  
  22.     }  
  23.     public void attributeRemoved(HttpSessionBindingEvent se) {  
  24.         Set all = (Set) this.app.getAttribute("online");  
  25.         all.remove(se.getSession().getAttribute("userid"));     //用户离开删除  
  26.         this.app.setAttribute("online",all);  
  27.     }  
  28.     public void attributeReplaced(HttpSessionBindingEvent se) { }  
  29.   
  30.     //  HttpSessionListener  
  31.     public void sessionCreated(HttpSessionEvent se) { }   
  32.     public void sessionDestroyed(HttpSessionEvent se) {  
  33.         Set all = (Set) this.app.getAttribute("online");  
  34.         all.remove(se.getSession().getAttribute("userid"));     //用户离开删除  没有getValue()这个方法  
  35.         this.app.setAttribute("online",all);  //操作完了之后重新放回集合之中  
  36.     }  
  37. }  
  38. /* 
  39.  
  40. <%@ page contentType="text/html" pageEncoding="GBK"%> 
  41.  
  42. <html> 
  43. <head> <title>欢迎光临</title> 
  44. </head> 
  45. <% 
  46.     request.setCharacterEncoding("GBK"); 
  47. %> 
  48. <body> 
  49. <form action="online_listener.jsp" method="post"> 
  50.     用户ID: <input type="text" name="userid"> 
  51.     <input type="submit" value="登录"> 
  52. </form> 
  53. <% 
  54.     String userid = request.getParameter("userid"); 
  55.     if(!(userid == null || "".equals(userid)))  { //userid 不为空 
  56.         session.setAttribute("userid",userid); 
  57.         response.sendRedirect("online_list.jsp"); 
  58.     } 
  59. %> 
  60. </body> 
  61. </html> 
  62.  
  63.  
  64. <%@ page contentType="text/html" pageEncoding="GBK"%> 
  65. <%@ page import="java.util.*"%> 
  66. <html> 
  67. <head> <title>欢迎光临</title> 
  68. </head> 
  69. <body> 
  70. <% 
  71.     Set all = (Set)this.getServletContext().getAttribute("online"); 
  72.     Iterator iter = all.iterator(); 
  73.     while(iter.hasNext()) { 
  74. %> 
  75.         <h3><%=iter.next()%></h3> 
  76. <% 
  77.     } 
  78. %> 
  79. </body> 
  80. </html> 
  81.  
  82.  
  83.  
  84.  
  85. */  
  86.   
  87.   
  88.   
  89. /* 
  90.     <listener> 
  91.         <listener-class> 
  92.             org.gz.servlet.context.OnlineUserList 
  93.         </listener-class> 
  94.     </listener> 
  95.     <session-config> 
  96.         <session-timeout>1</session-timeout> 
  97.     </session-config> 
  98.  
  99.  
  100. E:\webdemo\WEB-INF\classes>javac -d . *.java 
  101. 注意:OnlineUserList.java 使用了未经检查或不安全的操作。 
  102. 注意:要了解详细信息,请使用 -Xlint:unchecked 重新编译。 (编译出现这样的情况是由于List集合没有加泛型) 
  103.  
  104. */  

使用监听器可以对application 、session、request 的属性范围进行监听

在web 中可以配置每一个session 的超时时间


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值