How to Setup Global JNDI Mapping
for Oracle JDBC Connection Pooling
with Tomcat

by Gregg Lagnese, MicroDeveloper, Inc.
May 16, 2005 v1.3
 
Troubleshooting <- Previous Introduction  
 

Making a User Dependent Connection

 
10) Setup the server.xml file without the username and password
Setup the server.xml file with an entry without the username and password specified as shown in the example below:
 
 <Resource name="jdbc/db2"
           auth="Container" 
           type="oracle.jdbc.pool.OracleDataSource"
           driverClassName="oracle.jdbc.driver.OracleDriver"
           factory="oracle.jdbc.pool.OracleDataSourceFactory"
           url="jdbc:oracle:thin:@oracle.microdeveloper.com:1521:db2"
           maxActive="20"
           maxIdle="10"
           maxWait="-1" /> 
 
11) Add code to the class to set the username and password
In the class, before the connection is formed, add a call to the datasource to set the username and password. This can be done in one of two ways as shown below:
 
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
OracleDataSource ds = (OracleDataSource) envContext.lookup("jdbc/db2");
    if (envContext == null) throw new Exception("Error: No Context");
    if (ds == null) throw new Exception("Error: No DataSource");
    if (ds != null){
       ds.setUser("scott");
       ds.setPassword("tiger");
       conn = ds.getConnection();
    } catch (Exception e) {
   e.printStackTrace();
}
- or -

try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
OracleDataSource ds = (OracleDataSource) envContext.lookup("jdbc/db2");
    if (envContext == null) throw new Exception("Error: No Context");
    if (ds == null) throw new Exception("Error: No DataSource");
    if (ds != null){
       conn = ds.getConnection("scott","tiger");
    } catch (Exception e) {
   e.printStackTrace();
}
 
This method has been tested on Oracle 8.1.6 through 10.0.1 and Tomcat 5.0.28, 5.5.4, 5.5.7, and 5.5.9. It was tested using IntelliJ 4.5 and directly.
 
Troubleshooting <- Previous Introduction