使用ServletContextListener创建和关闭一个数据库连接

本文介绍了如何在Servlet应用中利用ServletContextListener监听器在Web应用启动时创建数据库连接,并在应用结束时关闭连接。详细步骤包括从web.xml读取配置信息,创建DBConnConfig对象,通过DBManagerUtil管理连接,并在MyServletContextListener中处理上下文初始化和销毁事件。此外,还提供了一个DBConnServletTest测试类来验证连接的可用性。
摘要由CSDN通过智能技术生成

1、流程简述

 

    1)上下文初始化时得到通知(Web应用部署时)。

        a)从ServletContext中得到上下文初始化参数(配置在web.xml中)。

        b)使用初始化参数创建一个新的数据库连接。

        c)把数据库连接作为属性保持到ServletContext上下文中,使得整个Web应用的各个部分都能访问。

 

     2)上下文撤消时得到通知(Web应用取消部署或结束时)

        a)关闭数据库连接

 

2、需要用到web.xml文件及四个类

 

    1)web.xml:部署描述符,配置Web应用上下文初始化参数(数据库连接信息)以及监听器。

    2)MyServletContextListener类:监听器类,用于监听上下文初始化及销毁事件。

    3)DBConnConfig:数据库配置对象,用于封装数据库连接所需的数据。

    4)DBMangerUtil:数据库连接工具类,用于获取和关闭数据库连接。

    5)DBConnServletTest:测试类,在Servlet中测试能否获取保存在ServletContext中的数据库连接对象。

   

3、实例代码

   

    1)web.xml配置如下:

<!-- 数据库连接初始化参数 -->
  <context-param>
      <param-name>driver</param-name>
      <param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>
  <context-param>
      <param-name>url</param-name>
      <param-value>jdbc:mysql://localhost:3306/student</param-value>
  </context-param>
  <context-param>
      <param-name>username</param-name>
      <param-value>admin</param-value>
  </context-param>
  <context-param>
      <param-name>password</param-name>
      <param-value>mysqladmin</param-value>
  </context-param>
  
  <!-- ServletContext监听器 -->
  <listener>
      <listener-class>com.linwei.listener.MyServletContextListener</listener-class>  
  </listener>

 

    2)MyServletContextListener类:监听器类

package com.linwei.listener;

import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.linwei.model.DBConnConfig;
import com.linwei.util.DBMangerUtil;

/**
 * @author Linwei
 * 监听器保证每新生成一个servletContext都会有一个可用的数据库连接,
 * 并且所有的连接会在context销毁的时候随之关闭。
 */
public class MyServletContextListener implements ServletContextListener {
	Connection conn=null;
	
	//上下文初始化
	public void contextInitialized(ServletContextEvent event) {
		try {
			//使用数据库配置对象初始化数据库连接工具类
			DBConnConfig dbConfig = getDBConnConfig(event);
			if(dbConfig!= null){
				DBMangerUtil.initDBMangerUtil(dbConfig);
			}
			
			// 创建数据库连接
			conn = DBMangerUtil.getConncection();
			
			//将连接保存到ServletContext上下文中
			event.getServletContext().setAttribute("dbconn", conn);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//上下文销毁
	public void contextDestroyed(ServletContextEvent event) {
		try {
			// 关闭数据库连接
			DBMangerUtil.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//读取Web.xml中数据库初始化参数,然后实例化并返回数据库配置对象
	private DBConnConfig getDBConnConfig(ServletContextEvent event){
		
		//使用获取Web应用上下文初始化参数
		ServletContext ctx = event.getServletContext();
		String driver = ctx.getInitParameter("driver");
		String url = ctx.getInitParameter("url");
		String username = ctx.getInitParameter("username");
		String password = ctx.getInitParameter("password");
		
		DBConnConfig dbConfig=null;
		dbConfig = new DBConnConfig(driver, url, username, password);
		return dbConfig;
	}
}

 

    3)DBConnConfig类:数据库配置对象

package com.linwei.model;

public class DBConnConfig {
	public String driver;
	public String url;
	public String username;
	public String password;
	
	public DBConnConfig(String driver, String url, String username,
			String password) {
		super();
		this.driver = driver;
		this.url = url;
		this.username = username;
		this.password = password;
	}
	//getter()和setter()
}

    

    4)DBMangerUtil类:数据库连接工具类

package com.linwei.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.linwei.model.DBConnConfig;

public class DBMangerUtil {
	public static String driver = "";
	public static String url = "";
	public static String username = "";
	public static String password = "";

	public static Connection conn = null;

	// 初始化DBMangerUtil的实例变量
	public static void initDBMangerUtil(DBConnConfig dbConfig) {
		DBMangerUtil.driver = dbConfig.getDriver();
		DBMangerUtil.url = dbConfig.getUrl();
		DBMangerUtil.username = dbConfig.getUsername();
		DBMangerUtil.password = dbConfig.getPassword();
	}

	// 获取连接
	public static Connection getConncection() throws SQLException {
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		conn = DriverManager.getConnection(url, username, password);
		return conn;
	}

	// 关闭连接
	public static void close() throws SQLException {
		if (conn != null) {
			conn.close();
		}
	}
}

    

    5)DBConnServletTest类:测试类

package com.linwei.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DBConnServletTest extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		
		//获取ServletContext上下文中保存连接对象
		Connection dBconn=(Connection) getServletContext().getAttribute("dbconn");
		PrintWriter out=response.getWriter();
		out.println(dBconn.toString());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值