二、监听的分类(按监听的事件划分)
1、监听域对象自身的创建和销毁的事件监听器
如下:
1.1、ServletContext——>ServletContextListener接口介绍如下:
ServletContextListener接口,主要实现监听ServletContext的创建和删除。同时它提供了两个方法,它们被称为“Web应用程序的生命周期方法”。
- public void contextDestroyed(ServletContextEvent sce) {………………….}:通知正在收听的对象,应用程序已经被加载及初始化
- public void contextInitialized(ServletContextEvent sce) {……………………}:通知正在收听的对象,应用程序已经被关闭。
例子:测试ServletContextListener
创建FistListener.java
package com;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class FirstListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("destroy");
}
public void contextInitialized(ServletContextEvent sce) {
//通过上下文getServletContext(),和getInitParameter()获取web.xml值
String init=sce.getServletContext().getInitParameter("init");
System.out.println("init的值为:"+init);
}
}
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>FirstListener</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.FirstListener<