我在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???
答案 0 :(得分:0)
将行更改为private static InitialContext context = null;
。编译器警告您,在某些情况下,可能不会创建context
。
答案 1 :(得分:-2)
static{
context = new InitialContext();
try {
datasource=(DataSource) context.lookup("jdbc/WILLIAMSON");
} catch (NamingException ex) {
Logger.getLogger(DBCONN.class.getName()).log(Level.SEVERE, null, ex); }