The correct way to call a JNDI data source in Tomcat

I am using a Java web application on a Tomcat server and would like to know what is the "best practice" in terms of accessing a database connection from Tomcat JNDI?

Currently, this is basically what I do every time I need to access the database:

Context envContext = null;
DataSource dataSource = null;
try {
    envContext  = (Context)ctx.lookup("java:/comp/env");
    dataSource = (DataSource)envContext.lookup("jdbc/datasource");
    return dataSource.getConnection();
} catch (Exception e){
    e.printStackTrace();
    return null;
}finally {
    if(envContext != null){
        try{
           envContext.close();
        } catch (NamingException e){
            e.printStackTrace();
        }
    }
}

However, is this the right way to find a connection to JNDI every time I want to access a database? Should I refer instead to a Context or data source?

+5
source share
4 answers

jndi - , , Map, . DataSource "". , - - DataSource , J2EE .

+3

new InitialContext() , static final static {}, Singleton. , .

DataSource static. public static Connection getConnection(); Connection, DataSource . PooledDataSource.

+4

- : -

...

Context initContext = new InitialContext();
DataSource dataSource = (DataSource) initContext.lookup("java:comp/env/jdbc/datasource");

...
+2


, .

. , , spring / JdbcTemplate

+1

All Articles