Code Samples and Apps

Following are some examples to illustrate the capabilities enabled by JNDI. You can get additional examples from the following sources.

  • You can also download the source of a JNDI demo program for browsing and editing namespaces and directories. This program uses the JNDI API and can be used to browse any naming and directory service for which you have a service provider.
  • The JNDI Tutorial contains over 200 working examples of basic to advanced uses of JNDI.

Accessing the Directory

A directory is typically used to associate attributes with objects. A person object, for example, can have a number of attributes, such as the person's surname, telephone numbers, electronic mail address, postal address, computer account, and authentication information such as his password or X.509 certificate. Using JNDI, to retrieve the email address of a person object, the code looks as follows.

        Attribute attr =
        String email = (String)attr.get();

Searching the Directory

An application can also use JNDI to search the directory for objects by specifying some attributes. For example, to search for people whose surname is "Fox" in the Wiz organization, the code looks as follows.

        foxes ="o=Wiz,c=US", "sn=Fox", controls);

Looking up Objects

An intuitive model for the Java programmer is to be able to lookup objects like printers and databases from the naming/directory service. Using JNDI, to lookup a printer object, the code looks as follows.

        Printer printer = (Printer)namespace.lookup(printerName);

Browsing the Namespace

When using almost any kind of interactive application that prompts the user for input names, the user's job is simplified if a namespace browser is made available to him. This browser can either be general-purpose or be supplied by the application. Using JNDI, to list the contents of a particular level in the namespace, the code looks as follows.

        NamingEnumeration list = namespace.list("o=Widget, c=US");
        while (list.hasMore()) {
                NameClassPair entry = (NameClassPair);
                display(entry.getName(), entry.getClassName());

Left Curve
Java SDKs and Tools
Right Curve
Left Curve
Java Resources
Right Curve
JavaOne Banner
Java 8 banner (182)