I created a JDBC connection pool (jdbc/WILLIAMSON
) in Glassfish server using JNDI in Netbeans, I want to use this in all servlets so instead of writing the following code in every 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();
I created a class DBCONN and tried to call an object of this class in every servlet but getting error "variable context might not have been initialized". See my code is below:
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();
}
}
I'm calling the datasource.getConnection()
in 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???