The Java Naming and Directory Interface (JNDI) is an API that Java developers use to access naming and directory services. These services are technologies that Java programs use to store or bind objects for later use, as well as search for or "look up" object references. The purpose of JNDI is to separate the responsibility of maintaining a repository of commonly used objects from the wide variety of Java classes that use those objects, including servlets and JSPs.
Examples of JNDI services are the Remote Method Invocation registry and the Lightweight Directory Access Protocol (LDAP). The JNDI API, represented by the javax.naming package, provides a common implementation for accessing objects that are bound to these services.
Each of these technologies has a naming scheme with which "JNDI objects" can be found. The structure of these schemes is often hierarchical; you start at the top of the JNDI tree, then work your way down to each of the branches to find what you are looking for. Using JNDI, Java programs begin with an "initial context," similar to the forward slash (/) from which Unix begins to describe the location of a file. The / represents the root of a storage medium or hard disk; you can find the Users folder at the top level of the disk by entering /Users .
In Tomcat, the initial context of its built-in JNDI implementation is the address java:comp/env ”all lookups start from there. Chapter 21 describes how to access a javax.sql.Datasource from a JNDI implementation by starting at the initial context java:comp/env , and then looking up the DataSource at the address jdbc/MyDataSource . All DataSources are stored under jdbc , so this is how Java code accesses a DataSource named "MyDataSource." Using a filesystem analogy, the "root" folder in Tomcat's JNDI structure is "java:comp/env" and specific DataSource s are stored under the jdbc subdirectory.
You can use JNDI to get access to any Java object, not just DataSources . This chapter describes how to store a JavaBean using Tomcat's JNDI implementation, and then look up the bean using a servlet or JSP. The chapter also describes how to configure a mail session (with a javax.mail.Session object) using BEA WebLogic's JNDI implementation, and then to gain access to that mail session by enabling a servlet or JSP to send email.
A servlet can also access Enterprise JavaBeans (EJBs) using JNDI.
The servlets or JSPs may represent the presentation logic of a system that uses EJBs to access databases and implement tasks that are specific to a business or organization. The last recipe shows how to access an EJB from a servlet using BEA WebLogic as the application server.