JNDI

From CauchoWiki

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

[edit] 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:

prefixtype of objects
java:comp/env/jdbcdatabase
java:comp/env/jmsJMS queues and factories
java:comp/env/ejbremote EJBs

[edit] 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>

[edit] 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>

[edit] 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) {
    }    
  }

  ...
}
Retrieved from "http://wiki.caucho.com/JNDI"
Personal tools