在Servlet规范中定义了多种类型的监听器,它们用于监听的事件源分别为 ServletContext , HttpSession 和 ServletRequest 这三个域对象。
一、监听ServletContext的事件
(1)、ServletContextListener
监听的事件源是ServletContextEvent,ServletContextListener是"生命周期监听器",如果想要知道何时Web应用程序已经初始化或即将结束销毁,可以实现ServletContextListener:
package javax.servlet;
import java.util.EventListener;
public interface ServletContextListener extends EventListener {
public void contextInitialized(ServletContextEvent sce); //web应用启动初始化时调用,比如数据库的连接等,
public void contextDestroyed(ServletContextEvent sce); //web应用结束销毁前调用,用来做资源的释放,比如释放数据库的连接
}
而传入的事件中包含ServletContext,通过ServletContextEvent event.getServletContext()获取
例如:
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener()
public class MyContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
//对servletContext做初始化处理
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
(2)、ServletContextAttributeListener
监听的事件源是ServletContextEvent
ServletContextAttributeListener是"监听属性改变的监听器",如果想要对象被设置、移除或替换ServletContext属性,可以收到通知以进行一些操作,则可以实现ServletContextAttributeListener。
package javax.servlet;
import java.util.EventListener;
public interface ServletContextAttributeListener extends EventListener{
public void attributeAdded(ServletContextAttributeEvent scab);
public void attributeRemoved(ServletContextAttributeEvent scab);
public void attributeReplaced(ServletContextAttributeEvent scab);
}
当在ServletContext中添加属性、移除属性或替换属性时,相对应的attributeAdded()、attributeRemoved()与attributeReplaced()方法就会被调用。
如果希望容器在部署应用程序时,实例化实现ServletContextAttributeListener的类并注册给应用程序,同样也是在实现类上标注@WebListener(其他事件也是加上此注解,并实现相应的接口即可),并实现ServletContextAttributeListener接口,也可以配置在web.xml中
二、监听HttpSession的事件
(1)、HttpSessionListener
HttpSessionListener是"会话生命周期监听器",如果想要在HttpSession对象创建或结束时,做些相对应动作,则可以实现HttpSessionListener。
(2)、HttpSessionAttributeListener
HttpSessionAttributeListener是"会话属性改变监听器",当在会话对象中加入属性、移除属性或替换属性时,相对应的attributeAdded()、attributeRemoved()与attributeReplaced()方法就会被调用,并分别传入HttpSessionBindingEvent。
(3)、HttpSessionBindingListener
HttpSessionBindingListener是"会话对象绑定监听器",如果有个即将加入HttpSession的属性对象,希望在设置给HttpSession成为属性或从HttpSession中移除时,可以收到HttpSession的通知,则可以让该对象实现HttpSessionBindingListener接口。
(4)、HttpSessionActivationListener
八辈子用不到。。。
三、监听ServletRequest 的事件
(1)、ServletRequestListener
ServletRequestListener是"请求生命周期监听器",如果想要在HttpServletRequest对象生成或结束时做些相对应的操作,则可以实现ServletRequestListener。如果做为servletRequest对象的修改。
(2)、ServletRequestAttributeListener
ServletRequestAttributeListener是"属性改变监听器",在请求对象中加入属性、移除属性或替换属性时,相对应的attributeAdded()、attributeRemoved()与attributeReplaced()方法就会被调用,并分别传入ServletRequestAttributeEvent。
ServletRequestAttributeEvent有个getName()方法,可以取得属性设置或移除时指定的名称,而getValue()则可以取得属性设置或移除时的对象。
(3)、AsyncListener
这个略叼。下个篇幅在完善吧。