一 代码
package lee;
import javax.servlet.*;
import javax.servlet.annotation.*;
@WebListener
public class MyServletContextAttributeListener
implements ServletContextAttributeListener
{
// 当程序向application范围添加属性时触发该方法
public void attributeAdded(ServletContextAttributeEvent event)
{
ServletContext application = event.getServletContext();
// 获取添加的属性名和属性值
String name = event.getName();
Object value = event.getValue();
System.out.println(application + "范围内添加了名为"
+ name + ",值为" + value + "的属性!");
}
// 当程序从application范围删除属性时触发该方法
public void attributeRemoved(ServletContextAttributeEvent event)
{
ServletContext application = event.getServletContext();
// 获取被删除的属性名和属性值
String name = event.getName();
Object value = event.getValue();
System.out.println(application + "范围内名为"
+ name + ",值为" + value + "的属性被删除了!");
}
// 当application范围的属性被替换时触发该方法
public void attributeReplaced(ServletContextAttributeEvent event)
{
ServletContext application = event.getServletContext();
// 获取被替换的属性名和属性值
String name = event.getName();
Object value = event.getValue();
System.out.println(application + "范围内名为"
+ name + ",值为" + value + "的属性被替换了!");
}
}
二 测试JSP
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> 测试ServletContextListener </title>
<meta name="website" content="http://www.crazyit.org" />
</head>
<body>
下面是直接从application中取出数据库连接,<br/>
并执行查询后的结果<br/>
<%
Connection conn = (Connection)application.getAttribute("conn");
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行查询
ResultSet rs = stmt.executeQuery("select * from news_inf");
%>
<table bgcolor="#9999dd" border="1" width="300">
<%
// 遍历结果集
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
</tr>
<%
}
%>
<table>
</body>
</html>
三 测试
日志文件输出
org.apache.catalina.connector.RequestFacade@2b5e78d5范围内名为org.apache.catalina.ASYNC_SUPPORTED,值为true的属性被替换了!