使用servlet方法配合hibernate启动会有异常,尤其用pool
hsqldb随tomcat启动改进方法:使用listener
- package cn.qbq.database;
-
-
import java.io.IOException;
-
import java.net.ServerSocket;
-
import java.util.logging.Logger;
-
-
import javax.servlet.ServletContextEvent;
-
import javax.servlet.ServletContextListener;
-
-
import org.hsqldb.Server;
-
-
public class StartHSQLDBListener implements ServletContextListener {
-
-
private Logger logger = Logger.getLogger(StartHSQLDBListener.class.getName());
-
-
private Server server;
-
-
private final static String HSQLDB_PATH_PARAM_NAME = "HSQLDBPath";
-
private final static String HSQLDB_NAME_PARAM_NAME = "HSQLDBName";
-
private final static String HSQLDB_PORT_PARAM_NAME = "HSQLDBPort";
-
-
private final static String DEFAULT_HSQLDB_PATH = "/WEB-INF/lib/hsqldb/";
-
private final static String DEFAULT_HSQLDB_NAME = "labdb";
-
private final static int DEFAULT_HSQLDB_PORT = 9001;
-
-
@Override
-
public void contextDestroyed(ServletContextEvent event) {
-
if (server != null) {
-
server.shutdown();
-
}
-
}
-
-
@Override
-
public void contextInitialized(ServletContextEvent event) {
-
String HSQLDBPath = event.getServletContext().getInitParameter(HSQLDB_PATH_PARAM_NAME);
-
String HSQLDBName = event.getServletContext().getInitParameter(HSQLDB_NAME_PARAM_NAME);
-
String paramPort = event.getServletContext().getInitParameter(HSQLDB_PORT_PARAM_NAME);
-
if (HSQLDBPath == null || HSQLDBPath.length() == 0) {
-
HSQLDBPath = DEFAULT_HSQLDB_PATH;
-
}
-
if (HSQLDBName == null || HSQLDBName.length() == 0) {
-
HSQLDBName = DEFAULT_HSQLDB_NAME;
-
}
-
int HSQLDBPort = DEFAULT_HSQLDB_PORT;
-
if (paramPort != null && paramPort.length() > 0) {
-
HSQLDBPort = Integer.valueOf(paramPort);
-
}
-
String path = event.getServletContext().getRealPath(HSQLDBPath) + "/" + HSQLDBName;
-
-
ServerSocket s = null;//因为有可能端口被占用,Server类内部会出异常,先在外部看下端口
-
try {
-
s = new ServerSocket(HSQLDBPort);
-
} catch (IOException e) {
-
logger.info("HSQLDB was not started caused by " + e.getMessage());
-
return;
-
} finally {
-
if (s != null) {
-
try {
-
s.close();
-
} catch (IOException e) {
-
logger.warning(e.getMessage());
-
return;
-
}
-
}
-
}
-
-
server = new Server();
-
server.setDatabaseName(0, HSQLDBName);
-
server.setDatabasePath(0, path);
-
server.setPort(HSQLDBPort);
-
server.setSilent(true);
-
-
if (server == null) {
-
}
-
-
Thread thread = new Thread(new Runnable() {
-
public void run() {
-
server.start();
-
}
-
});
-
thread.start();
-
}
-
-
}
web.xml加入如下:
- <!-- Start HSQLDB server -->
-
<context-param>
-
<param-name>HSQLDBPath</param-name>
-
<param-value>/WEB-INF/lib/hsqldb/</param-value>
-
</context-param>
-
-
<context-param>
-
<param-name>HSQLDBName</param-name>
-
<param-value>labdb</param-value>
-
</context-param>
-
-
<context-param>
-
<param-name>HSQLDBPort</param-name>
-
<param-value>9001</param-value>
-
</context-param>
-
-
<listener>
-
<listener-class>cn.qbq.database.StartHSQLDBListener</listener-class>
-
</listener>
阅读(2211) | 评论(0) | 转发(0) |