servlet的listener

ServletContextListener

  1. 建立一個類 implements ServletContextListener
package JDBC;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

public class JdbcUtil implements ServletContextListener {
	private ServletContext context;
	private Connection connection = null;

	public void contextInitialized(ServletContextEvent sce) {
		/*Context initCtx;
		try {
			initCtx = new InitialContext();
			DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/mysql");
			sce.getServletContext().setAttribute("dataSource", ds);
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		System.out.println("項目已啓動");
		context=sce.getServletContext();
		Properties properties = loadJdbcProperties();
		String url = properties.getProperty("url");
		String user = properties.getProperty("username");
		String password = properties.getProperty("password");
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(url, user, password);
			System.out.println("數據庫鏈接成功!");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void contextDestroyed(ServletContextEvent sce) {
		try {
			connection.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: loadJdbcProperties   
	 * @Description: TODO(這裏用一句話描述這個方法的做用)   
	 * @param:      
	 * @return: Properties      
	 */
	public Properties loadJdbcProperties() {
		InputStream inStream=context.getResourceAsStream("/WEB-INF/classes/mysql.properties");
		/*File mySql = new File("mysql.properties");*/
		/*InputStream inStream;*/
		try {
			/*inStream = new FileInputStream(mySql);*/
			Properties properties = new Properties();
			properties.load(inStream);
			return properties;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	public ServletContext getContext() {
		return context;
	}

	public void setContext(ServletContext context) {
		this.context = context;
	}
	
	

}

這是我寫的一個demo在項目啓動的時候進行數據庫的鏈接java

2.在_web.xml_裏做以下配置:mysql

<listener>
		<listener-class>JDBC.JdbcUtil</listener-class>
	</listener>
相關文章
相關標籤/搜索