java web 监听器学习

本文详细介绍了网站监听器的用途,包括统计在线人数、系统启动时加载初始化信息、统计网站访问量以及与Spring框架的结合,并提供了创建监听器的步骤,涉及Servlet上下文、HTTP会话及客户端请求级别的监听器接口使用与配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

监听器的用途

1,统计网站的在线人数和在线人数

2,系统启动时加载初始化信息

3,统计网站的访问量

4,和spring结合

创建监听器步骤

1,创建一个实现监听器接口的类

2,在web.xml文件中进行配置

监听器接口

1. Servlet上下文进行监听(Application级): 
用于监听 ServletContext 对象的创建和删除以及属性的添加、删除和修改等操作,该监听器需要用到如下两个接口类: 
(1) ServletContextAttributeListener:监听对 ServletContext 属性的操作,比如增加、删除、修改 
      attributeAdded(ServletContextAttributeEvent e)             添加属性时调用    
      attributeReplaced(ServletContextAttributeEvent e)        修改属性时调用    
      attributeRemoved(ServletContextAttributeEvent e)        删除属性时调用 

(2) ServletContextListener:监听对 ServletContext  对象的创建和删除 
      contextInitialized(ServletContextEvent sce)          初始化时调用    
      contextDestroyed(ServletContextEvent sce)        销毁时调用,即当服务器重新加载时调用 

2. 监听HTTP会话(Session级): 
用于监听 HTTP 会话活动情况和 HTTP 会话中的属性设置情况,也可以监听 HTTP 会话的 active 和 passivate 情况等,该监听器需要用到如下多个接口类: 
(1) HttpSessionListener:监听 HttpSession 的操作 
      sessionCreate(HttpSessionEvent se)         初始化时调用; 
      sessionDestroyed(httpSessionEvent se)    销毁时调用,即当用户注销时调用

(2) HttpSessionActivationListener:用于监听 HTTP 会话的 active 和 passivate 情况 

(3) HttpSessionAttributeListener:监听 HttpSession 中的属性操作 
      attributeAdded(HttpSessionBindingEvent se)         添加属性时调用 
      attributeRemoved(HttpSessionBindingEvent se)    删除属性时调用 
      attributeReplaced(HttpSessionBindingEvent se)    修改属性时调用 

3. 对客户端请求进行监听(Requst级): 
用于对客户端的请求进行监听是在 Servlet2.4 规范中新添加的一项新技术,使用的接口如下: 
(1) ServletRequestListener 接口类 
       requestDestroyed(ServletRequestEvent e)       对销毁客户端进行监听,即当执行 request.removeAttribute("xxx") 时调用 
              requestInitialized(ServletRequestEvent e)         对实现客户端的请求进行监听 

(2) ServletRequestAttributeListener 接口类 
       attributeAdded(ServletRequestAttributeEvent e)         对属性添加进行监听 
       attributeRemoved(ServletRequestAttributeEvent e)    对属性删除进行监听 
       attributeReplaced(ServletRequestAttributeEvent e)    对属性替换进行监听

在web.xml中进行配置

  1.  <listener>  
  2.     <listener-class>包名.类名</listener-class>  
  3. </listener> 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值