1.读取配置文件
EnvironmentConfig.java
import java.io.*;
import java.util.*;
/**
* java 读取配置(属性)文件
* @author Billows.Van
* [email protected]
*/
public class EnvironmentConfig {
static EnvironmentConfig ec;// 创建对象ec
private static Hashtable<String, Properties> register = new Hashtable<String, Properties>();// 静态对象初始化[在其它对象之前]
private EnvironmentConfig() {
super();
}
/**
* 取得EnvironmentConfig的一个实例
*/
public static EnvironmentConfig getInstance() {
if (ec == null)
ec = new EnvironmentConfig();// 创建EnvironmentConfig对象
return ec;// 返回EnvironmentConfig对象
}
/**
* 读取配置文件
*/
public Properties getProperties(String fileName) {// 传递配置文件路径
InputStream is = null;// 定义输入流is
Properties p = null;
try {
p = (Properties) register.get(fileName);// 将fileName存于一个HashTable
/**
* 如果为空就尝试输入进文件
*/
if (p == null) {
try {
is = new FileInputStream(fileName);// 创建输入流
} catch (Exception e) {
if (fileName.startsWith("/"))
// 用getResourceAsStream()方法用于定位并打开外部文件。
is = EnvironmentConfig.class.getResourceAsStream(fileName);
else
is = EnvironmentConfig.class.getResourceAsStream("/"+fileName);
}
p = new Properties();
p.load(is);// 加载输入流
register.put(fileName, p);// 将其存放于HashTable缓存
is.close();// 关闭输入流
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
return p;// 返回Properties对象
}
/**
* 此处插入方法描述。
*/
public String getPropertyValue(String fileName, String strKey) {
Properties p = getProperties(fileName);
try {
return (String) p.getProperty(strKey);
} catch (Exception e) {
e.printStackTrace(System.out);
}
return null;
}
}
用法:
EnvironmentConfig ec=EnvironmentConfig.getInstance();
String driverClassName=ec.getPropertyValue("/config/jdbc.properties", "jdbc.driverClassName");
2.Jdbc工具
JdbcUtil.java
package com.billows.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author Billows.Van [email protected]
* @version 创建时间:2008-4-30 上午10:53:09 类说明
*/
public class JdbcUtil {
static {
try {
EnvironmentConfig ec=EnvironmentConfig.getInstance();
String driverClassName=ec.getPropertyValue("/config/jdbc.properties", "jdbc.driverClassName");
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
Connection conn = null;
EnvironmentConfig ec=EnvironmentConfig.getInstance();
String url=ec.getPropertyValue("/config/jdbc.properties", "jdbc.url");
String name=ec.getPropertyValue("/config/jdbc.properties", "jdbc.username");
String pwd=ec.getPropertyValue("/config/jdbc.properties", "jdbc.password");
conn = DriverManager.getConnection(url, name, pwd);
return conn;
}
public static void release(Connection conn, PreparedStatement ps,ResultSet rs) {
if (rs != null)try {rs.close();} catch (SQLException e) {e.printStackTrace();}
if (ps != null) try {ps.close();} catch (SQLException e) {e.printStackTrace();}
if (conn!= null)try {conn.close();} catch (SQLException e) {e.printStackTrace();}
}
public static void release(Object obj) {
if (obj instanceof Connection) {
Connection conn = (Connection) obj;
if (conn != null)
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (obj instanceof PreparedStatement) {
PreparedStatement ps = (PreparedStatement) obj;
if (ps != null)
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (obj instanceof ResultSet) {
ResultSet rs = (ResultSet) obj;
if (rs != null)
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
3.java数据源
DBConnectionPool.java
package com.billows.util;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBConnectionPool {
public static Connection getConnection() throws Exception{
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/hsql");
// Context initContext = new InitialContext();
// Context envContext = (Context)initContext.lookup("java:/comp/env");
// DataSource ds = (DataSource)envContext.lookup("hsql");
return ds.getConnection( );
}
}
4.hsqldb随web启动的Listener
package com.billows.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import org.hsqldb.Server;
import com.billows.util.EnvironmentConfig;
/**
* 该listener随web服务启动 并同时启动hsql-server
* @auth Billows.Van
* [email protected]
*/
public class HsqlListener implements ServletContextListener {
public static final Logger log = Logger.getLogger("HsqlListener");
private EnvironmentConfig ec=EnvironmentConfig.getInstance();
/**配置文件中的占位符,代表webapp发布后的根目录.*/
public static final String TOKEN = "${webapp.root}";
/** 等待数据库停止的最大时间.*/
public static final int WAIT_TIME = 1000;
/**jdbc的url.*/
private String url;
/**登陆用户名.*/
private String username;
/**登陆密码.*/
private String password;
/**处理context初始化事件.
* @param sce ServletContextEvent
*/
public void contextInitialized(ServletContextEvent sce) {
try {
username = ec.getPropertyValue("/config/jdbc.properties", "jdbc.username");
password = ec.getPropertyValue("/config/jdbc.properties", "jdbc.password");
String databaseName = ec.getPropertyValue("/config/jdbc.properties", "jdbc.dbname");
int port = Integer.parseInt(ec.getPropertyValue("/config/jdbc.properties", "jdbc.dbport"));
String hsqlPath = ec.getPropertyValue("/config/jdbc.properties", "jdbc.dbpath");
// FIXME: 因为要用到getRealPath方法获得路径,在使用war包发布的时候会出现问题
if (hsqlPath.startsWith(TOKEN)) {
String webappRoot = sce.getServletContext().getRealPath("/").replace("\\", "/");
hsqlPath = hsqlPath.substring(TOKEN.length());
hsqlPath = webappRoot + hsqlPath;
}
String databasePath = hsqlPath + "/" + databaseName;
url = "jdbc:hsqldb:hsql://localhost:" + port + "/" + databaseName;
Server server = new Server();
server.setDatabaseName(0, databaseName);
server.setDatabasePath(0, databasePath);
server.setPort(port);
server.setSilent(true);
server.start();
Thread.sleep(WAIT_TIME);
log.info("Hsqldb启动成功!");
} catch (Exception ex) {
log.error("Hsqldb启动失败:" + ex);
}
}
/**
* 处理context销毁事件.
* @param sce ServletContextEvent
*/
public void contextDestroyed(ServletContextEvent sce) {
try {
Class.forName("org.hsqldb.jdbcDriver");
Connection conn = null;
Statement state = null;
try {
// 向数据库发送shutdown命令,关闭数据库
conn = DriverManager.getConnection(url, username, password);
state = conn.createStatement();
state.executeUpdate("SHUTDOWN;");
try {
Thread.sleep(WAIT_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("关闭hsqldb数据库成功!");
} catch (SQLException ex1) {
log.error("关闭hsqldb数据库时出现异常:" + ex1);
} finally {
// 确保关闭Statement
if (state != null) {
try {
state.close();
state = null;
} catch (SQLException ex1) {
log.error("关闭Statement时异常:"+ex1);
}
}
// 确保关闭Connection
if (conn != null) {
try {
conn.close();
conn = null;
} catch (SQLException ex1) {
log.error("关闭Connection时异常:"+ex1);
}
}
}
} catch (ClassNotFoundException ex) {
log.error("HsqldbListener : contextDestoryed : error : " + ex);
}
}
}
其中, jdbc.properties内容为
jdbc.driverClassName=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:hsql://localhost:9990/billows
jdbc.dbname=billows
jdbc.dbport=9990
jdbc.dbpath=${webapp.root}/hsqldb
jdbc.username=sa
jdbc.password=
jdbc.max_connections=30