📄 hsqldblistener.java
字号:
package com.uiwz.db;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hsqldb.Server;
/**
* 控制数据库的周期.
* context启动的时候,启动hsqldb数据库服务器,context关闭时shutdown数据库服务器
*
* @author Lingo
* @version 1.0
* @since 2007-03-13
* @see javax.servlet.ServletContextListener
* @web.listener
*/
public class HsqldbListener implements ServletContextListener {
private static final Log log = LogFactory.getLog(HsqldbListener.class);
/**
* 等待数据库停止的最大时间.
*/
public static final int WAIT_TIME = 1000;
/**
* 处理context初始化事件.
* @param sce ServletContextEvent
*/
public void contextInitialized(ServletContextEvent sce) {
try {
Properties prop = new Properties();
prop.load(getClass().getResourceAsStream("/hsqldb.properties"));
String username = prop.getProperty("hsql.username");
String password = prop.getProperty("hsql.password");
String databaseName = prop.getProperty("hsql.dbname");
int port = Integer.parseInt(prop.getProperty("hsql.port"));
String hsqlPath = prop.getProperty("hsql.path");
String databasePath = sce.getServletContext().getRealPath(hsqlPath) + "/" + databaseName;
//System.out.println(sce.getServletContext().getRealPath(hsqlPath));
Server server = new Server();
server.setDatabaseName(0, databaseName);
server.setDatabasePath(0, databasePath);
server.setPort(port);
server.setSilent(true);
server.start();
log.info("Started HSQLDB server on port:" + port);
} catch (Exception e) {
log.error(e);
e.printStackTrace();
}
}
/**
* 处理context销毁事件.
* @param sce ServletContextEvent
*/
public void contextDestroyed(ServletContextEvent sce) {
Connection conn = null;
Statement state = null;
try {
// 向数据库发送shutdown命令,关闭数据库
log.info("Stoping HSQLDB server...");
conn = Database.getConnection();
state = conn.createStatement();
state.executeUpdate("SHUTDOWN;");
Thread.sleep(WAIT_TIME);
log.info("Stoped HSQLDB server");
} catch (Exception e) {
log.error(e);
} finally {
// 确保关闭Statement
if (state != null) {
try {
state.close();
state = null;
} catch (SQLException e) {
log.error(e);
}
}
// 确保关闭Connection
if (conn != null) {
try {
conn.close();
conn = null;
} catch (SQLException e) {
log.error(e);
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -