【发布时间】:2017-11-18 01:22:14
【问题描述】:
我在 Netbeans 中使用 JNDI 在 Glassfish 服务器中创建了一个 JDBC 连接池 (jdbc/WILLIAMSON),我想在所有 servlet 中使用它,所以不要在每个 servlet 中编写以下代码
InitialContext context = new InitialContext();
//The JDBC Data source that we just created
DataSource datasource = (DataSource)
context.lookup("jdbc/WILLIAMSON");
Connection connection = null;
connection = ds.getConnection();
我创建了一个类 DBCONN 并尝试在每个 servlet 中调用此类的一个对象,但收到错误“变量上下文可能尚未初始化”。请看我的代码如下:
public final class DBCONN {
private static final InitialContext context;
private static final DataSource datasource;
static{
try {
context = new InitialContext();
datasource=(DataSource) context.lookup("jdbc/WILLIAMSON");
} catch (NamingException ex) {
Logger.getLogger(DBCONN.class.getName()).log(Level.SEVERE,
null, ex);
}
}
private DBCONN() {
// I am confused how to use this method, pls guide me
}// ERROR HERE VARIABLE context MIGHT NOT HAVE BEEN INITIALIZED
public static Connection getConnection() throws SQLException {
return datasource.getConnection();
}
}
我在 servlet HOME.java 中调用 datasource.getConnection()
DBCONN datasource = new DBCONN();
Connection connection = null;
connection = datasource.getConnection();// I am accessing a static
method so warning coming accessing static method getConnection(), how
to avoid it???
【问题讨论】:
-
请帮我找到上述问题的答案?
标签: java servlets jdbc connection-pooling