zoukankan      html  css  js  c++  java
  • 实现session监听器

    监听器概述   

    1.Listener是Servlet的监听器    
    2.可以监听客户端的请求、服务端的操作等。   
    3.通过监听器,可以自动激发一些操作,如监听在线用户数量,当增加一个HttpSession时,给在线人数加1。   
    4.编写监听器需要实现相应的接口   
    5.编写完成后在web.xml文件中配置一下,就可以起作用了   
    6.可以在不修改现有系统基础上,增加web应用程序生命周期事件的跟踪   


    常用的监听接口   

    Java代码

    1. 1.ServletContextAttributeListener      
    2. 监听对ServletContext属性的操作,比如增加/删除/修改      
    3. 2.ServletContextListener      
    4. 监听ServletContext,当创建ServletContext时,激发 contextInitialized(ServletContextEvent sce)方法;当销毁ServletContext时,激发contextDestroyed(ServletContextEvent sce)方法。      
    5. 3.HttpSessionListener      
    6. 监听HttpSession的操作。当创建一个 Session时,激发session Created(SessionEvent se)方法;当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法。      
    7. 4.HttpSessionAttributeListener      
    8. 监听HttpSession中的属性的操作。当在Session增加一个属性时,激发 attributeAdded(HttpSessionBindingEvent se) 方法;当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。    

    1.ServletContextAttributeListener 监听对ServletContext属性的操作,比如增加/删除/修改 2.ServletContextListener 监听ServletContext,当创建ServletContext时,激发 contextInitialized(ServletContextEvent sce)方法;当销毁ServletContext时,激发contextDestroyed(ServletContextEvent sce)方法。 3.HttpSessionListener 监听HttpSession的操作。当创建一个 Session时,激发session Created(SessionEvent se)方法;当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法。 4.HttpSessionAttributeListener 监听HttpSession中的属性的操作。当在Session增加一个属性时,激发 attributeAdded(HttpSessionBindingEvent se) 方法;当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。

    使用范例:   
    由监听器管理共享数据库连接   

    生命周期事件的一个实际应用由context监听器管理共享数据库连接。在web.xml中如下定义监听器:   
    Java代码

    1. <listener>      
    2.      <listener-class>XXX.MyConnectionManager</listener-class>      
    3. </listener>   

    <listener> <listener-class>XXX.MyConnectionManager</listener-class> </listener>
    server创建监听器的实例,接受事件并自动判断实现监听器接口的类型。要记住的是由于监听器是配置在部署描述符web.xml中,所以不需要改变任何代码就可以添加新的监听器。   
    Java代码

    1.      
    2. public class MyConnectionManager implements ServletContextListener{        
    3. public void contextInitialized(ServletContextEvent e) {       
    4.          Connection con = // create connection       
    5.          e.getServletContext().setAttribute("con", con);       
    6.      }        
    7.    public void contextDestroyed(ServletContextEvent e) {       
    8.          Connection con = (Connection) e.getServletContext().getAttribute("con");       
    9.         try {      
    10.            con.close();       
    11.          }       
    12.        catch (SQLException ignored) { } // close connection       
    13.      }       
    14. }   

    public class MyConnectionManager implements ServletContextListener{ public void contextInitialized(ServletContextEvent e) { Connection con = // create connection e.getServletContext().setAttribute("con", con); } public void contextDestroyed(ServletContextEvent e) { Connection con = (Connection) e.getServletContext().getAttribute("con"); try { con.close(); } catch (SQLException ignored) { } // close connection } }    
    监听器保证每新生成一个servlet context都会有一个可用的数据库连接,并且所有的连接对会在context关闭的时候随之关闭。     

    在web.xml中加入:   
    Java代码

    1. <listener><listener-class>servletlistener111111.SecondListener</listener-class> </listener>  

    <listener><listener-class>servletlistener111111.SecondListener</listener-class> </listener>

    ================================================== 

    关于用户超时的例子: 

    Java代码

    1. public class OnlineUserListener implements HttpSessionListener {   
    2.     public void sessionCreated(HttpSessionEvent event) {   
    3.      }   
    4.     public void sessionDestroyed(HttpSessionEvent event) {   
    5.          HttpSession session = event.getSession();   
    6.          ServletContext application = session.getServletContext();   
    7.         // 取得登录的用户名   
    8.          String username = (String) session.getAttribute("username");   
    9.         // 从在线列表中删除用户名   
    10.          List onlineUserList = (List) application.getAttribute("onlineUserList");   
    11.          onlineUserList.remove(username);   
    12.          System.out.println(username + "超时退出。");   
    13.      }   
    14. }  

    public class OnlineUserListener implements HttpSessionListener { public void sessionCreated(HttpSessionEvent event) { } public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession(); ServletContext application = session.getServletContext(); // 取得登录的用户名 String username = (String) session.getAttribute("username"); // 从在线列表中删除用户名 List onlineUserList = (List) application.getAttribute("onlineUserList"); onlineUserList.remove(username); System.out.println(username + "超时退出。"); }}

    以下两种情况下就会发生sessionDestoryed(会话销毁)事件: 

    1.执行session.invalidate()方法时。例如:request.getSession().invalidate(); 

    2.如果用户长时间没有访问服务器,超过了会话最大超时时间,服务器就会自动销毁超时的session。会话超时时间可以在web.xml中进行设置。 

    ======================================== 

    使用HttpSessionBindingListener 

    HttpSessionBindingListener虽然叫做监听器,但使用方法与HttpSessionListener完全不同。我们实际看一下它是如何使用的。

    我们的OnlineUserBindingListener实现了HttpSessionBindingListener接口,接口中共定义了两个方法:valueBound()和valueUnbound(),分别对应数据绑定,和取消绑定两个事件。 

    所谓对session进行数据绑定,就是调用session.setAttribute()把HttpSessionBindingListener保存进session中。我们在LoginServlet.java中进行这一步。 

    // 把用户名放入在线列表 
    session.setAttribute("onlineUserBindingListener", new OnlineUserBindingListener(username)); 
           
    这就是HttpSessionBindingListener和HttpSessionListener之间的最大区别:HttpSessionListener只需要设置到web.xml中就可以监听整个应用中的所有session。 HttpSessionBindingListener必须实例化后放入某一个session中,才可以进行监听。 

    从监听范围上比较,HttpSessionListener设置一次就可以监听所有session,HttpSessionBindingListener通常都是一对一的。 

    正是这种区别成就了HttpSessionBindingListener的优势,我们可以让每个listener对应一个username,这样就不需要每次再去session中读取username,进一步可以将所有操作在线列表的代码都移入listener,更容易维护。 

    valueBound()方法的代码如下: 

    Java代码

    1. public void valueBound(HttpSessionBindingEvent event) {   
    2.      HttpSession session = event.getSession();   
    3.      ServletContext application = session.getServletContext();   
    4.   
    5.     // 把用户名放入在线列表   
    6.      List onlineUserList = (List) application.getAttribute("onlineUserList");   
    7.     // 第一次使用前,需要初始化   
    8.     if (onlineUserList == null) {   
    9.          onlineUserList = new ArrayList();   
    10.          application.setAttribute("onlineUserList", onlineUserList);   
    11.      }   
    12.      onlineUserList.add(this.username);   
    13. }  

    public void valueBound(HttpSessionBindingEvent event) { HttpSession session = event.getSession(); ServletContext application = session.getServletContext(); // 把用户名放入在线列表 List onlineUserList = (List) application.getAttribute("onlineUserList"); // 第一次使用前,需要初始化 if (onlineUserList == null) { onlineUserList = new ArrayList(); application.setAttribute("onlineUserList", onlineUserList); } onlineUserList.add(this.username);}
           
    username已经通过构造方法传递给listener,在数据绑定时,可以直接把它放入用户列表。 

    与之对应的valueUnbound()方法,代码如下: 
    Java代码

    1. public void valueUnbound(HttpSessionBindingEvent event) {   
    2.      HttpSession session = event.getSession();   
    3.      ServletContext application = session.getServletContext();   
    4.   
    5.     // 从在线列表中删除用户名   
    6.      List onlineUserList = (List) application.getAttribute("onlineUserList");   
    7.      onlineUserList.remove(this.username);   
    8.   
    9.      System.out.println(this.username + "退出。");   
    10. }  

    public void valueUnbound(HttpSessionBindingEvent event) { HttpSession session = event.getSession(); ServletContext application = session.getServletContext(); // 从在线列表中删除用户名 List onlineUserList = (List) application.getAttribute("onlineUserList"); onlineUserList.remove(this.username); System.out.println(this.username + "退出。");}
           
    这里可以直接使用listener的username操作在线列表,不必再去担心session中是否存在username。 

    valueUnbound的触发条件是以下三种情况: 
    Java代码

    1. 1.执行session.invalidate()时。   
    2.   
    3. 2.session超时,自动销毁时。   
    4.   
    5. 3.执行session.setAttribute("onlineUserListener", "其他对象");或session.removeAttribute("onlineUserListener");将listener从session中删除时。  

    1.执行session.invalidate()时。2.session超时,自动销毁时。3.执行session.setAttribute("onlineUserListener", "其他对象");或session.removeAttribute("onlineUserListener");将listener从session中删除时。

    因此,只要不将listener从session中删除,就可以监听到session的销毁。

  • 相关阅读:
    致研究者的一封信
    机器学习简介
    The resource about the Machine Learning(Cont.)
    哈佛箴言
    Google图片搜索新算法 图片版PageRank
    top conferences and journals in Machine Learning
    做科研的几点体会
    数百本外文数学EBOOK免费下载
    Machine Learning Algorithm Tutorials
    在批处理中实现等待/延迟/暂停
  • 原文地址:https://www.cnblogs.com/yaowen/p/2933679.html
Copyright © 2011-2022 走看看