Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to call JNDI datasource within Tomcat

Tags:

People also ask

Does Tomcat supports JNDI?

Tomcat provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java Enterprise Edition application server. The Java EE standard provides a standard set of elements in the /WEB-INF/web.

How do I use DataSource with Tomcat?

Tomcat DataSource JNDI Configuration Example - server.Add below code in the tomcat server. xml file. The code should be added in the GlobalNamingResources element. Also make sure that database driver is present in the tomcat lib directory, so in this case mysql jdbc jar have to be present in the tomcat lib.

How can I get JNDI name for DataSource?

To obtain a reference to a data source bound to the JNDI context, look up the data source's JNDI name from the initial context object. The object retrieved in this way is cast as a DataSource type object: ds = (DataSource)ctx. lookup(JndiDataSourceName);


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 within Tomcat's JNDI?

Currently this is basically what I am doing each 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 proper way to look up a connection from JNDI each time I want to access the database? Should I hold a reference to the Context or the Datasource instead?