我使用NetBeans JNDI創造了GlassFish服務器的JDBC連接池(jdbc/WILLIAMSON
)沒有初始化,我想在所有servlet使用該如此,而不是在每一個servlet的寫下面的代碼JDBC連接池變量上下文可能
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();
}
}
我打電話datasource.getConnection()
在servlet的HOME.java
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???
使用全部大寫被認爲是喊,不這樣做。 –
plz幫助我找到上述問題的答案? – Williamson