(1)、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应用结束销毁前调用,用来做资源的释放,比如释放数据库的连接
}
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) {
}
}
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中
HttpSessionListener是"会话生命周期监听器",如果想要在HttpSession对象创建或结束时,做些相对应动作,则可以实现HttpSessionListener。
HttpSessionAttributeListener是"会话属性改变监听器",当在会话对象中加入属性、移除属性或替换属性时,相对应的attributeAdded()、attributeRemoved()与attributeReplaced()方法就会被调用,并分别传入HttpSessionBindingEvent。
HttpSessionBindingListener是"会话对象绑定监听器",如果有个即将加入HttpSession的属性对象,希望在设置给HttpSession成为属性或从HttpSession中移除时,可以收到HttpSession的通知,则可以让该对象实现HttpSessionBindingListener接口。
ServletRequestListener是"请求生命周期监听器",如果想要在HttpServletRequest对象生成或结束时做些相对应的操作,则可以实现ServletRequestListener。如果做为servletRequest对象的修改。
ServletRequestAttributeListener是"属性改变监听器",在请求对象中加入属性、移除属性或替换属性时,相对应的attributeAdded()、attributeRemoved()与attributeReplaced()方法就会被调用,并分别传入ServletRequestAttributeEvent。
ServletRequestAttributeEvent有个getName()方法,可以取得属性设置或移除时指定的名称,而getValue()则可以取得属性设置或移除时的对象。