`

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

阅读更多

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);
	}
}

 

分享到:
评论

相关推荐

    ServletContextListener使用详解

    ServletContextListener使用详解

    ServletContextListener socket实现数据接收

    这是一个maven项目,直接导入eclipse即可运行,此处监听的是9092端口,将项目运行起后,可以对其端口使用情况进行查看,在window下,可以使用命令 netstat -aon|findstr "9092",在linux下可以使用命令netstat -...

    ServletContextListener的应用

    ServletContextListener的应用案例 项目启动:创建新的空表, 项目关闭:删除表 百度六祎,期...

    Java基于ServletContextListener实现UDP监听

    主要介绍了Java基于ServletContextListener实现UDP监听,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    ServletContextListener完成在线人数统计和显示人员列表

    ServletContextListener完成在线人数统计和显示人员列表

    ServletContextListener,Timer,TimerTask学习笔记

    NULL 博文链接:https://chenhua-1984.iteye.com/blog/374683

    SpringMVC中ervletContextListener的使用

    在SpringMVC中利用ServletContextListener初始化数据到内存

    springboot参考指南

    创建和删除JPA数据库 viii. 29. 使用NoSQL技术 i. 29.1. Redis i. 29.1.1. 连接Redis ii. 29.2. MongoDB i. 29.2.1. 连接MongoDB数据库 ii. 29.2.2. MongoDBTemplate iii. 29.2.3. Spring Data MongoDB仓库 iii. ...

    WebSocketClient

    Web Socket 客户端 WAR 脚手架 用于将 Web 应用程序用作 Web 套接...随着 WAR 的部署,一个 ServletContextListener 将被创建和调用 上下文侦听器查找系统 'env' 变量并从类路径中读取相应的属性文件('prod' 是默认的

    监听器:监听三个对象的创建和销毁方法

    本次工程的目标是学习监听器,掌握监听三个对象的创建和销毁方法。 三个对象:rquest,session,ServletContext 实现的接口:ServletRequestListener,HttpSessionListener,ServletContextListener 工程的大致步骤...

    23-Listener-源代码.rar

    案例-使用监听器完成定时生日祝福、,一、监听器Listener 二、邮箱服务器。 1.什么是监听器? 2.监听器有哪些? 3.监听三大域对象的创建与销毁的监听器 4.监听三大域对象的属性变化的 5.与session中的绑定的...

    JavaWeb开发技术-Listener监听器.pptx

    Listener监听器 ...用于监听域对象创建和销毁的事件监听器 用于监听域对象属性增加和删除的事件监听器 用于监听绑定到HttpSession域中某个对象 状态的事件监听器 ServletContextListener接口 HttpS

    java 监听使用

    有时候在开发Web应用的时候,需要tomcat启动后自动加载一个用户的类,执行一些初始化方法,如从数据库中加载业务字典到内存中,因此需要在tomcat启动时就自动加载一个类,或运行一个类的方法。 可以采用在WEB-INF/...

    编写程序,提供用户登录界面。登录成功后,提示用户上次登录时间,登录IP地址信息

    编写程序,提供用户登录界面。 登录成功后,提示用户上次登录时间,登录IP地址信息。 保存用户的登录信息可以使用XML,也可以使用纯文本文件。... 要求使用ServletContextListener,要求理解Listener.

    Listener:ServletContextListener,sesson,请求侦听器

    听众 ServletContextListener,sesson,请求侦听器

    SI_LabWeek7:是的实验周7

    SI_LabWeek7 SI实验第7周使用以下方法完成: ...servlet作为控制器 jsp作为输出页面 一个实现ServletContextListener进行... P / S:忘记关闭应该正确在ServletContextListener.contextDestroyed()中的数据库连接。

    JavaWeb新版教程. jsp--ServletContextListener监听器演示.avi

    JavaWeb新版教程. jsp--ServletContextListener监听器演示.avi

    用Timer开发的一个定时任务

    最近公司项目要用到定时任务,因为是通过接口传送数据,所以我就新建了一个web项目,在web.xml配置文件里配置一个监听器,然后该监听器再继承HttpServlet,同时实现ServletContextListener接口,很简单的一个定时...

    tomcat启动|退出执行事件

    tomcat启动|退出执行事件类: import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.servlet.ServletContextEvent; import javax.servlet....// 添加一个新的文本文件 }

Global site tag (gtag.js) - Google Analytics