Listener是监听器,监听Servlet某一个事件的发生或者状态的改变,它的内部其实就是接口回调。
ServletContextListener监听对象:
ServletContextListener用于监听ServletContext对象作用域创建和销毁,利用它可以完成自己想要的初始化工作。
-
servletcontext创建contextInitialized:
1、启动服务器的时候 -
servletContext销毁contextDestroyed:
1、关闭服务器
2、从服务器移除项目
创建:
public class MyContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("contextInitialized ...");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("contextDestroyed ...");
}
}
配置:
ServletRequestListenercom.xxx(包名).MyContextListener
监听对象:
ServletRequestListener用于监听ServletRequest对象作用域创建和销毁,利用它可以判断当前是否存在请求。
-
request创建requestInitialized:
访问服务器上的任意资源都会有请求出现。
访问 html :会
访问 jsp :会
访问 servlet :会 -
request销毁requestDestroyed:
服务器已经对这次请求作出了响应。
创建:
public class MyRequestListener implements ServletRequestListener {
@Override
public void requestInitialized(ServletRequestEvent servletRequestEvent) {
System.out.println("requestInitialized ...");
}
@Override
public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
System.out.println("requestDestroyed ...");
}
}
配置:
HttpSessionListenercom.xxx(包名).MyRequestListener
监听对象:
HttpSessionListener用于监听HttpSession对象作用域创建和销毁,利用它可以统计在线人数。
-
session的创建sessionCreated:
只要调用getSession()方法。
html :不会
jsp :会
servlet :会 -
session的销毁sessionDestroyed:
1、会话超时30分钟。
2、非正常关闭服务器。
3、正常关闭服务器(序列化)
创建:
public class MySessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
System.out.println("sessionCreated ...");
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
System.out.println("sessionDestroyed ...");
}
}
配置:
监听三个作用域属性状态变更com.xxx(包名).MySessionListener
ServletContextAttributeListener 监听ServletContext存值状态变更。
ServletRequestAttributeListener 监听ServletRequest存值状态变更。
HttpSessionAttributeListener 监听HttpSession存值状态变更。
主要方法:
attributeAdded()
attributeRemoved()
attributeReplaced()
HttpSessionBindingListener :监听对象与session绑定和解除绑定的动作。(这一类监听器不用注册。)
valueBound(HttpSessionBindingEvent httpSessionBindingEvent){
}
valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent){
}
HttpSessionActivationListener:用于监听现在session的值是钝化(序列化)还是活化(反序列化)的动作。
- 钝化(序列化) :把内存中的数据存储到硬盘上。
- 活化(反序列化):把硬盘中的数据读取到内存中。
如何钝化:
-
在tomcat的 conf/context.xml 里面配置
对所有的运行在这个服务器的项目生效。 -
在tomcat的 conf/Catalina/localhost/context.xml 里面配置
对localhost生效。 -
在自己的web工程项目中的 meta-INF/context.xml 里面配置
只对当前的工程生效。
具体配置信息如下:
maxIdleSwap : 1分钟不用就钝化。
directory : 钝化后的那个文件存放的目录位置。
创建:
public class MySessionActivationListener implements HttpSessionActivationListener {
@Override
public void sessionWillPassivate(HttpSessionEvent httpSessionEvent) {
System.out.println("sessionWillPassivate ...");
}
@Override
public void sessionDidActivate(HttpSessionEvent httpSessionEvent) {
System.out.println("sessionDidActivate ...");
}
}



