一.监听器简介
Listener,中文名为监听器。通过Listener可以监听容器中某一执行动作,并根据其要求作出响应。
目前为止,Listener接口分为3类:
1.与ServletContext有关的Listener接口,即Servlet上下文监听器
2.与HttpSession有关的Listener接口,即Http会话监听器
3.与ServletRequest有关的Listener接口,即客户请求监听器
二.Servlet上下文监听器
Servlet上下文监听器用于ServletContext的创建和删除以及属性的添加、删除和修改等操作。Servlet上下文监听器包含ServletContextListener和ServletContextAttributeListener两个接口。
接口名 | 描述 |
---|---|
ServletContextListener接口 | 用于ServletContext的创建和销毁 |
ServletContextAttributeListener接口 | 用于实现ServletContext对象中属性的操作,如添加,删除,修改操作 |
ServletContextListener接口有两个方法:
方法名 | 描述 |
---|---|
contextInitialized(ServletContextEvent sce) | 当ServletContext对象创建时调用该方法 |
contextDestroyed(ServletContextEvent sce) | 当ServletContext对象销毁时调用该方法 |
ServletContextAttributeListener接口有三个方法:
方法名 | 描述 |
---|---|
attributeAdded(ServletContextAttributeEvent scab) | 当往ServletContext对象中添加属性时将调用该方法 |
attributeRemoved(ServletContextAttributeEvent scab) | 当从ServletContext对象中移除属性时将调用该方法 |
attributeReplaced(ServletContextAttributeEvent scab) | 当ServletContext对象中属性发生改变时调用该方法 |
范例: 定义一个Servlet上下文监听器,并监听Servlet上下文的创建和销毁。
TestServletContext.java
package com.javaweb.Listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class TestServletContext implements ServletContextListener{
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
System.out.println("ServletContext创建");
}
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("ServletContext销毁");
}
}
在web.xml中配置Listener,Listener只需配置类名即可,代码如下:
<listener>
<listener-class>com.javaweb.Listener.TestServletContext</listener-class>
</listener>
启动服务器,在后台console可以看到下图:
关闭服务器、移除项目,重新部署项目,都可以看到下图:
三.Http会话监听器
Http会话监听器用于HttpSession对象的创建和删除以及属性的添加,删除,修改操作,还可以用来监听HttpSession对象的有效状态。
Http会话监听器有四个接口:
接口名 | 描述 |
---|---|
HttpSessionListener接口 | 用来实现监听HttpSession对象的创建和销毁 |
HttpSessionAttributeListener接口 | 用来实现监听HttpSession对象中属性的操作,如增加,删除,修改操作 |
HttpSessionBindingListener接口 | 用来给那些需要传入HttpSession中的对象提供接口 |
HttpSessionActivationListener接口 | 用来对sessio对象的序列化与反序列化 |
HttpSessionListener接口有两个方法:
方法名 | 描述 |
---|---|
sessionCreated(HttpSessionEvent se) | 当HttpSession对象创建时调用该方法 |
sessionDestroyed(HttpSessionEvent se) | 当HttpSession对象销毁时调用该方法 |
HttpSessionAttributeListener接口有三个方法:
方法名 | 描述 |
---|---|
attributeAdded(HttpSessionAttributeEvent se) | 当往HttpSession对象添加属性时调用该方法 |
attributeRemoved(HttpSessionAttributeEvent se) | 当从HttpSession对象移除属性时调用该方法 |
attributeReplaced(HttpSessionAttributeEvent se) | 当HttpSession对象属性发生改变时调用该方法 |
HttpSessionBindingListener接口有两个方法:
1.如果调用HttpSession对象的setAttribute方法,那么将自动调用HttpSession中的对象的valueBound方法
2.如果调用HttpSession对象的removeAttribute方法或者session超时,那么将自动调用HttpSession中的对象的valueUnbound方法
摘自《Java Web 程序设计与项目实践》,电子工业出版社