Servlet监听器简介与实现在线人数统计

一.Servlet监听器概述
HttpSession监听器接口
统计网站在线人数程序
ServletContext监听器接口
HttpServletRequest监听器接口

 

二.好处:
更加方便的控制application session request对象的发生的特定事件
可以集中处理特定的事件

HttpSession监听器接口
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener

HttpSessionListener
sessionCreated()
sessionDestroyed()

 

web.xml的配置
<listener>
<listener-class>projectName.CounterListener
</listener-class>
</listener>

 

HttpSession监听器接口
HttpSessionAttributeListener
attributeAdded()
attributeReplaced()
attributeRemoved()
产生事件的代码
session.setAttribute("username","SunWukong");
session.setAttribute("username","ZhangFei");
session.removeAttribute("username");

HttpSessionBindingListener 这个监听器是不用配置的
valueBound()
valueUnbound()
调用机制
如果一个类实现了HttpSessionBindingListener接口,则当这个类的对象通过session.setAttribute()被绑定到Session对象中时,则该对象的valueBound()方法被自动调用,当这个对象从Session中删除时(调用session.invalidate()和session.removeAttribute()方法,或Session对象过期)valueUnbound()方法将被自动调用.

HttpSessionActivationListener
sessionDidActivate()
sessionWillPassivate()
调用机制
活化(Activate)与(钝化)Passivate是Web容器为了更好的利用系统资源或者进行服务器负载平衡等原因而对特定对象采取的措施.
会话对象的钝化指的是暂时将会话对象通过对象序列化的方式储存到硬盘上,而会话对象活化与钝化相反,Web容器把硬盘上储存的会话对象文件重新加载到Web容器中.
sessionDidActivate()与sessionWillPassivate()方法分别于会话对象活化后和会话对象钝化前由容器进行自动调用.


ServletContext监听器接口
ServletContextListener
contextInitialized()
contextDestroyed()


调用机制
当在Web应用中部署了实现该接口的实现类后,在Web容器加载Web应用时(例如:启动服务器)就会自动调用contextInitialized()方法,而当Web容器销毁Web应用时(例如:关闭服务器),会自动调用contextDestroyed()方法

ServletContextAttributeListener
attributeAdded()
attributeReplaced()
attributeRemoved()


触发事件的代码
context.setAttribute("counter",new Integer(0));
context.setAttribute("counter",new Integer(100);
context.removeAttribute("counter");

HttpServletRequest监听器
HttpServletrequest监听器接口
ServletReuqestListener
requestInitialized()
requestDestroyed()


调用机制
与ServletContextListener接口类似,在Web应用中部署实现该接口的实现类后,
在HttpServletRequest对象(JSP中request对象)建立或者销毁时,由Web容器自动调用requestInitialized()或者requestDestroyed()方法.

ServletContext监听器接口
ServletRequestAttributeListener
attributeAdded()
attributeReplaced()
attributeRemoved()

 

触发事件的代码
request.setAttribute("username","SunWukong");
request.setAttribute("username","ZhangFei");
request.removeAttribute("username");

 

CountListener.java

 

web.xml

index.jsp

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值