1. 创建一个名为exp10的Web项目,编写、部署、测试一个ServletContext事件监听器。
【步骤1】编写监听器类MyServletContextListener.java,Web应用程序启动时创建一个数据源对象,并将其保存在ServletContext作用域中,Web应用销毁时将其清除;在ServletContext对象上添加属性、删除属性和替换属性时,在Tomcat日志中记录有关信息,包括提示信息、属性名和属性值等。
package edu.exp.no_1;
import java.util.Date;
import javax.servlet.*;
public final class MyServletContextListener implements ServletContextListener, ServletContextAttributeListener {
private ServletContext context = null;
public void contextInitialized(ServletContextEvent sce){
context = sce.getServletContext();
context.log("应用程序已启动:"+new Date());
}
public void contextDestroyed(ServletContextEvent sce){
context = sce.getServletContext();
context.log("应用程序已关闭:"+new Date());
}
public void attributeAdded(ServletContextAttributeEvent sce){
context = sce.getServletContext();
context.log("添加一个属性:"+sce.getName()+":"+sce.getValue());
}
public void attributeRemoved(ServletContextAttributeEvent sce){
context = sce.getServletContext();
context.log("删除一个属性:"+sce.getName()+":"+sce.getValue());
}
public void attributeReplaced(ServletContextAttributeEvent sce){
context = sce.getServletContext();
context.log("替换一个属性:"+sce.getName()+":"+sce.getValue());
}
}
【步骤2】在web.xml文件中注册监听器类。
<listener>
<listener-class>edu.exp.no_1.MyServletContextListener</listener-class>
</listener>
【步骤3】编写监听器测试页面:contextListenerTest.jsp:使用监听器创建的数据源对象连接是一次实验创建的MySQL数据库test,以表格的形式显示其中books数据表的所有内容。
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.PrintWriter" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title