[ Team LiB ] Previous Section Next Section

Recipe 21.5 Using a JNDI Lookup to get a DataSource from WebLogic

Problem

You want to use a JNDI lookup to access a WebLogic DataSource.

Solution

Use the JNDI API and the classes in the javax.naming package to get the JNDI object that you have bound on WebLogic.

Discussion

Accessing a Connection from a WebLogic DataSource and connection pool uses similar Java code compared with Tomcat.

  1. Set up the connection pool and DataSource by following Recipe 21.4s instructions.

  2. In the servlet code, get the DataSource by using a JNDI lookup. This involves creating an instance of a javax.naming.InitialContext and then calling its lookup( ) method with the name that you gave your DataSource (Recipe 21.4).

  3. Get a Connection from the DataSource by calling the DataSource's getConnection( ) method.

Example 21-5 creates an instance of an InitialContext by passing in a Hashtable that contains some property values.

Example 21-5. A servlet that uses a WebLogic connection pool
package com.jspservletcookbook;       

import java.util.Hashtable;    

import java.sql.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class WeblogicDbServlet extends HttpServlet {

 DataSource pool;
   
 
  public void init( ) throws ServletException {
        
       Context env = null;
         
       Hashtable ht = new Hashtable( );
       
       //Create property names/values that will be passed to
       //the InitialContext constructor

       ht.put(Context.INITIAL_CONTEXT_FACTORY,
         "weblogic.jndi.WLInitialContextFactory");

       // t3://localhost:7001 is the default value
       //Add your own value if necessary:
       // ht.put(Context.PROVIDER_URL,"t3://localhost:7001");
    
      try {
    
         env = new InitialContext(ht);

         pool = (javax.sql.DataSource) env.lookup (
           "oracle-8i-athletes");
            
        if (pool == null)
            throw new ServletException(
              "'oracle-8i-athletes' is an unknown DataSource");
             
        } catch (NamingException ne) { 
        
           throw new ServletException(ne);

        }
      
   }

  public void doGet(HttpServletRequest request, 
    HttpServletResponse response)
      throws ServletException, java.io.IOException {
    
        String sql = "select * from athlete";

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        ResultSetMetaData rsm = null;
        
        response.setContentType("text/html");

        java.io.PrintWriter out = response.getWriter( );

        out.println(
        "<html><head><title>Weblogic Database Access</title></head><body>");

        out.println("<h2>Database info</h2>");
        out.println("<table border='1'><tr>");
        
        try{ 
        
           conn = pool.getConnection( );

           stmt = conn.createStatement( );
      
           rs = stmt.executeQuery(sql);

           rsm = rs.getMetaData( );

           int colCount =  rsm.getColumnCount( );
            
           //print column names
           for (int i = 1; i <=colCount; ++i){
                
               out.println("<th>" + rsm.getColumnName(i) + "</th>");
           }
            
            out.println("</tr>");
          
            while( rs.next( )){
                
                out.println("<tr>");
                
                for (int i = 1;  i <=colCount; ++i)
                    out.println("<td>" + rs.getString(i) + "</td>");
                
                  out.println("</tr>");
                }
                
        } catch (Exception e){
            
           throw new ServletException(e.getMessage( ));
            
        } finally {
            
            try{
                
                if (stmt != null)
                    stmt.close( );
                
                //RETURN THE CONNECTION TO THE POOL!
                if (conn != null)
                    conn.close( );
                
            } catch (SQLException sqle){ }
            
        }
      out.println("</table></body></html>");
      
     } //doGet

}

Once you have accessed a Connection from the WebLogic connection pool, the code can execute various SQL statements in order to interact with the associated database. Always call the Connection's close( ) method when you are finished with the Connection, because this method call returns the shared Connection to the pool.

Example 21-5 cannot work without a properly configured connection pool and DataSource, which is very easy to do with the WebLogic console (as explained in Recipe 21.4).


The servlet output looks just like Figure 21-1, except for the different URL in the web browser's address field (http://localhost:7001/dbServlet).

See Also

The JDBC specification: http://java.sun.com/products/jdbc/download.html; Recipe 21.1 on accessing a database from a servlet without a connection pool; Recipe 21.2 and Recipe 21.3 on using a DataSource on Tomcat; Recipe 21.6 on using a DataSource with a JSP on WebLogic; Recipe 21.7 and Recipe 21.8 on calling stored procedures from servlets and JSPs; Recipe 21.9 on converting a java.sql.ResultSet object to a javax.servlet.jsp.jstl.sql Result; Recipe 21.10 and Recipe 21.11 on using transactions in servlets and JSPs; Recipe 21.12 on finding out information about a ResultSet.

    [ Team LiB ] Previous Section Next Section