Listener监听器

Servlet规范中定义的一种特殊的组件,用来监听Servlet容器产生的事件并进行相应的处理
容器产生的事件分类
    -   生命周期相关的事件
    -   设置和删除Attribute数据相关的事件
ServletContextListener监听器
    在ServletContext创建时和关闭时都会通知ServletContextListener
方法:
    servletContextInitialized(ServletContextEvent sce)
    当ServletContext创建的时候,将会调用这个方法
    servletContextDestroyed(ServletContextEvent sce)
    当ServletContext销毁的时候(例如关闭应用服务器或者重新加载应用),将会调用这个方法。
ServletContextAttributeListener监听器
当往Servlet Context添加、删除或者替换一个属性的时候,将会通知ServletContextAttributesListener 
方法:
    void attributeAdded(ServletContextAttributeEvent scab)
    往ServletContext中加入一个属性的时候触发;
    void attributeRemoved(ServletContextAttributeEvent scab)
    从ServletContext中删除一个属性的时候触发;
    void attributeReplaced(ServletContextAttributeEvent scab)
    改变ServletContext中属性的时候触发。
HttpSessionListener监听器
当一个HttpSession刚被创建或者失效(invalidate)的时候,将会通知HttpSessionListener 
    方法:
    void sessionCreated(HttpSessionEvent hse)
    当一个HttpSession对象被创建时,将会调用这个方法;
    void sessionDestroyed(HttpSessionEvent hse)
    当一个HttpSession超时或者调用HttpSession的invalidate()方法让它销毁时,将会调用这个方法 
HttpSessionAttributesListener监听器
HttpSession中添加、删除或者替换一个属性的时候,将会通知HttpSessionAttributesListener 
    方法:
    void attributeAdded(HttpSessionBindingEvent e)
    当往会话中加入一个属性的时候,将会调用这个方法;
    void attributeRemoved(HttpSessionBindingEvent e)
    当从会话中删除一个属性的时候,将会调用这个方法;
    void attributeReplaced(HttpSessionBindingEvent e)
    当改变会话中的属性的时候,将会调用这个方法

上面只是列举了一些常用的Listener,关于Listener中的方法,有一个规律,就是如果是Attribute的Listener那么就有三个抽象方法,如果是非Attribute的Listener就只有两个抽象方法。其实官方提供了8大Listener,其中有2个ServletContextEvents,4个HttpSessionEvents,2个ServeltRequestEvents

ServletContextEvents:
  ServletContextListener Servlet上下文更改监听
  ServletContextAttributeListener  Servlet上下文属性更改监听

HttpSessionEvents:
  HttpSessionListener  会话更改监听
  HttpSessionAttributeListener  会话属性更改监听
  HttpSessionActivationListener  会话钝化或激活监听
  HttpSessionBindingListener  会话绑定或取消监听

ServetRequestEvents:
  ServletRequestAttributeListener  请求属性更改监听
  ServletRequestListener 请求更改监听
在web.xml中配置listener组件
<listener>
    <listener-class>
        cn.xdl.listener.ListenerName
    </listener-class>
 </listener>




看一个计算当前网站的在线人数案例:

jsp文件:
<%@page import="cn.xdl.listener.MySessionListener"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
demo.jsp

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
  • 2021-04-16
  • 2021-10-10
猜你喜欢
  • 2021-06-14
  • 2022-02-28
  • 2021-12-01
  • 2021-08-24
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案