问题的产生:
在 Servlet 技 术 中 我 们 学 习 了 request 、 session 、 application 作用域对象,其主要作用是实现数据的在不同 场景中的灵活流转。但是数据的具体流转过程我们是看不 到的,比如作用域对象是什么时候创建和销毁的,数据是 什么时候存取,改变和删除的。因为具体的流转过程看不 到,所以也就无法再指定的时机对数据和对象进行操作,
比如 session 销毁的时候,在线人数-1。
监听器:监听器也叫Listener,是Servlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。
Servlet 监听器是 Servlet 规范中定义的一种特殊类,用于监听 ServletContext、HttpSession 和 ServletRequest 等域对象的创建与销毁事件,以及监听这些域对象中属性发生修改的事件。
监听作用:在事件发生之前,之后进行一些处理,比如统计在线人数
ServletContextListener监听ServletContext对象
ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改
HttpSession监听器
2.1> HttpSessionListener监听Session对象
2.2> HttpSessionAttributeListener监听Session中的属性操作
ServletRequest监听器
3.1> ServletRequestListener监听Request对象
3.2> ServletRequestAttributeListener监听Requset中的属性操作
Web.xml的配置:
<listener>
<listener-class>com.zyb.Listener.MyListener</listener-class>
</listener>
使用方法:
和过滤器差不多都是
1.先声明普通java类实现相应Listener的接口
2.配置web.xml
web.xm的配置:
<listener> <listener-class>com.zyb.Listener.MyListener</listener-class> </listener>
例如监听器统计在线人数的实现:https://www.cnblogs.com/cstdio1/p/11735070.html
更多内容请参考(有一些我还没有涉及到,例如: HttpSessionActivationListener就不需要配置web.xml等等):https://blog.csdn.net/menghuanzhiming/article/details/79042182
原文:https://www.cnblogs.com/cstdio1/p/11737125.html