I have a web APP in tomcat 8 with servlets tecnology. For DB connection I have a servlet listener that keep a static datasource and a static method that do a getConnection. All run fine in the serlvet I can call to servletListener.getConnection();
But inside classes can't call it.
I found this class in internet:
public final class DBUtilClass {
private static DataSource datasource;
static {
Context initContext;
try {
initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
datasource = (DataSource) envContext.lookup("jdbc/testdb");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return datasource.getConnection();
}
I like it because i can call it from all classes. I am not sure if it is the best way.
others aproach? Any recomendations?