O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required