版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
一 实现监听类
package lee;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
@WebListener
public class GetConnListener implements ServletContextListener
{
// 应该启动时,该方法被调用。
public void contextInitialized(ServletContextEvent sce)
{
try
{
// 取得该应用的ServletContext实例
ServletContext application = sce.getServletContext();
// 从配置参数中获取驱动
String driver = application.getInitParameter("driver");
// 从配置参数中获取数据库url
String url = application.getInitParameter("url");
// 从配置参数中获取用户名
String user = application.getInitParameter("user");
// 从配置参数中获取密码
String pass = application.getInitParameter("pass");
// 注册驱动
Class.forName(driver);
// 获取数据库连接
Connection conn = DriverManager.getConnection(url
, user , pass);
// 将数据库连接设置成application范围内的属性
application.setAttribute("conn" , conn);
}
catch (Exception ex)
{
System.out.println("Listener中获取数据库连接出现异常"
+ ex.getMessage());
}
}
// 应该关闭时,该方法被调用。
public void contextDestroyed(ServletContextEvent sce)
{
// 取得该应用的ServletContext实例
ServletContext application = sce.getServletContext();
Connection conn = (Connection)application.getAttribute("conn");
// 关闭数据库连接
if (conn != null)
{
try
{
conn.close();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
}
}
二 测试页面
<%@ 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>
三 测试结果