er 监听 HttpSession 中的属性的操作。当在 Session 增加一个属性时,激发 attributeAdded(HttpSessionBindingEvent se) 方法;当在 Session 删除 一个属性时,激发 attributeRemoved(HttpSessionBindingEvent se)方法; 当 在 Session 属 性 被 重 新 设 置 时 , 激 发 attributeReplaced(HttpSessionBindingEvent se) 方法。 使用范例: 由监听器管理共享数据库连接 生命周期事件的一个实际应用由 context 监听器管理共享数据库连接。在 web.
xml 中如下定义监听器:
XXX.MyConnectionManager ?server 创建监听器的实例,接受事件并自动判断实现监听器接口 的类型。要记住的是由于监听器是配置在部署描述符 web.xml 中,所以不需要 改变任何代码就可以添加新的监听器。 public class MyConnectionManager ServletContextListener{ public void contextInitialized(ServletContextEvent e) { Connection con = // create connection implements
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 中加入:
servletlistener111111.SecondListener ========================================== ======== 关于用户超时的例子: 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.in