Skip to main content

Accessing Derby using JNDI

Posted by bleonard on January 17, 2006 at 4:31 PM PST

After reading my Derby Tutorial, a co-worker asked me about using JNDI to access the Derby database. Here are the steps required to access Derby as a resource configured in Tomcat 5.5.

Getting Started

  1. First, follow the Derby Tutorial at least through the step Create Table Wizard. This will get Derby properly configured with NetBeans and give us at least one table to work with, Friends.
  2. Copy the derbyclient.jar to Tomcat's lib directory. You'll find derbyclient.jar in /db-derby- Copy it to /netbeans-4.1/enterprise1/jakarta-tomcat-5.5.7/common/lib. On the Macintosh, you'll copy the jar to

Fast Track

If you just want to take the project and run, extract Open the project in NetBeans and press F6 to run it.

Create the Project

  1. Create a new Web Application project named DerbyJNDI. Make sure the Server is Bundled Tomcat (5.5.9).
  2. Expand the Configuration Files node. Double-click context.xml to open it in the editor. Add the following to configure the resource:
    <Context path="DerbyJNDI">
    <Resource name="jdbc/Sample" auth="Container"
              type="javax.sql.DataSource" username="nbuser" password="nbuser"
              maxActive="8" maxIdle="4"/>   
  3. Expand the Web Pages > WEB-INF node. Double-click web.xml to open it in the graphical XML editor. Click the References button at the top. Expand the Resource References section and choose Add. Set the following values in the dialog:

  4. Add a new Servlet named DerbyJNDIServlet in package derby.
  5. Remove the comments surrounding the out.println statements.
  6. Between the tags, add the following:

    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource ds = (DataSource) envCtx.lookup("jdbc/Sample");
        Connection conn = ds.getConnection();
        Statement s = conn.createStatement();
        s.execute("Select * From \"NBUSER\".\"Friends\"");
        ResultSet rs = s.getResultSet();
        while ( {
            out.println(rs.getString("NAME") + " is my friend.");
        } catch (Exception ex) {

  7. Press Alt+Shift+F to fix the imports. Select the appropriate packages:

  8. Set the application's relative URL to the servlet. Open the project's properties, select the Run category and set the Relative URL to /DerbyJNDIServlet.
  9. Make sure the Derby Database is started (Tools > Derby Database > Start Derby Database).
  10. Press F6 to test run the application.
    Note, if you are prompted for the Tomcat Manager username and password, you'll find it in the jakarta-tomcat-5.5.9_base/conf/tomcat-users.xml file in your user directory. You can locate your User Dir by choosing Help > About and then selecting the Detail tab.
    If all goes well, you should see the output in your browser "Scott McNealy is my friend".
Related Topics >>