监听器:
- 用于监听事件,在事件发生前后,执行一些操作
监听器操作的上下文:
- 事件源: 发生事件的位置/对象
- 监听器: 监听事件源,监听到事件发生后,调用事件处理
监听模型
- 观察者模型
- 模型图
Servlet中有6个事件和8个监听器
- 主要提供了对ServletContext, HttpSession,* ServletRequest*的监听
Listener接口 | Event类 |
---|---|
ServletContextListener | ServletContextEvent |
ServletContextAttributeListener | ServletContextAttributeEvent |
HttpSessionListener HttpSessionActivationListener | HttpSessionEvent |
HttpSessionAttributeListener HttpSessionBindingListener | HttpSessionBindingEvent |
ServletRequestListener | ServletRequestEvent |
ServletRequestAttributeListener | ServletRequestAttributeEvent |
- ServletContextListener示例
- 实现ServletContextListener接口
- 编写配置文件
@WebListener//注解配置listener
public class ContextListener implements ServletContextListener{
@Override
//应用初始化时---服务器启动时触发
public void contextInitialized(ServletContextEvent sce) {
System.out.println("initialize!");
}
@Override
//应用销毁时---服务器停止时触发
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("desotry!");
}
}
<!--配置文件-->
<listener>
<listener-class>listener.ContextListener</listener-class>
</listener>
- 监听器应用
- 统计在线人数
- 将数据存储在ServletContext中
- 上线/下线和HttpSession对象有关
- 统计在线人数
public class OnlineListener implements HttpSessionListener, ServletContextListener{
private ServletContext context = null;
private int count = 0;
@Override
public void contextInitialized(ServletContextEvent sce) {
this.context = sce.getServletContext();
count = 0;
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("session created");
context.setAttribute("count", ++count);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("session destoryed");
context.setAttribute("count", --count);
}
}
- servlet/filter/listener初始化顺序
- Listener - Filter - Servlet