JNDI

From Resin 3.0

Jump to: navigation, search


JNDI, the Java Naming and Directory service, is essential a global HashMap which stores configured services.

In general, it is best to develop applications using an Inversion of Control pattern, so all JNDI dependencies are restricted to the configuration file.

Contents

JNDI naming convensions

Each configured object has a JNDI name, for example, "java:comp/env/jdbc/test" for a database.

There are some conventions for storing JNDI names:

prefix type of objects
java:comp/env/jdbc database
java:comp/env/jms JMS queues and factories
java:comp/env/ejb remote EJBs

Storing a database in JNDI

<web-app xmlns="http://caucho.com/ns/resin">
  <database jndi-name="java:comp/env/jdbc/test">
    <driver type="org.postgresql.Driver">
      <url>jdbc:postgresql://localhost/test</url>
      <user>harry</user>
    </driver>
  </database>
  ... 
</web-app>

Looking up a database in JNDI in the resin-web.xml

<web-app xmlns="http://caucho.com/ns/resin">
  <servlet servlet-name="test"
           servlet-class="com.foo.MyTestServlet">
    <init>
      <database>${jndi("java:comp/env/jdbc/test")}</database>
    </init>
  </servlet>
</web-app>

Looking up a database with JNDI in Java code

import javax.naming.*;
import javax.sql.*;

public class TestServlet extends GenericServlet {
  private DataSource _database;

  public void init()
    throws ServletException
  {
    try {
      Context ic = new InitialContext();

      _database = (DataSource) ic.lookup("java:comp/env/jdbc/test");
    } catch (NamingException e) {
    }    
  }

  ...
}
Personal tools