当前位置:首页 > java 过滤器、监听器 拦截器 原理个人总结
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中如下定义监听器:
?server创建监听器的实例,接受事件并自动判断实现监听器接口的类型。要记住的是由于监听器是配置在部署描述符web.xml中,所以不需要改变任何代码就可以添加新的监听器。
public class MyConnectionManager implements ServletContextListener{ public void contextInitialized(ServletContextEvent e) { Connection con = // create connection e.getServletContext().setAttribute(\
}
public void contextDestroyed(ServletContextEvent e) {
Connection con = (Connection) e.getServletContext().getAttribute(\ try {
con.close(); }
catch (SQLException ignored) { } // close connection } }
监听器保证每新生成一个servlet context都会有一个可用的数据库连接,并且所有的连接对会在context关闭的时候随之关闭。
计算在线用户数量的Linstener (1)
Package xxx;
public class OnlineCounter { private static long online = 0; public static long getOnline(){ return online;
}
public static void raise(){ online++; }
public static void reduce(){ online--; } }
import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener;
public class OnlineCounterListener implements HttpSessionListener{ public void sessionCreated(HttpSessionEvent hse) { OnlineCounter.raise(); }
public void sessionDestroyed(HttpSessionEvent hse){ OnlineCounter.reduce(); } }
在需要显示在线人数的JSP中可是使用 目前在线人数:
<%@ page import=“xxx.OnlineCounter\ %> <%=OnlineCounter.getOnline()%>
退出会话(可以给用户提供一个注销按钮):
共分享92篇相关文档