A Simple Example
Before going any further, let’s take a look at a simple JNDI example. To access an object in a naming system, we need to create an initial context for the naming system, to give us an entry point into it. Once we have an initial context, we can look up an object by name.
Example 7-1 demonstrates the basic JNDI tasks of getting
an initial context to a naming system and looking up an object in
that naming system. With slight modification, this code can be used
to look up objects with any JNDI provider. So, for example, you could
use this Lookup
class to look up Enterprise
JavaBeans or remote objects in an RMI registry and handle them
however you like. All you have to change is the properties that
control the naming system being accessed.
Example 7-1. Looking Up an Object in a Naming System
import java.util.Properties; import javax.naming.*; public class Lookup { public static void main(String[] args) { String name = ""; if (args.length > 0) name = args[0]; try { // Create a Properties object and set default properties Properties props = new Properties( ); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); props.put(Context.PROVIDER_URL, "file:///"); // Optional command-line args to specify alternate factory and URL if (args.length > 1) { props.put(Context.INITIAL_CONTEXT_FACTORY, args[1]); } if (args.length > 2) { props.put(Context.PROVIDER_URL, args[2]); } // Create the initial context from the properties we just created ...
Get Java Enterprise in a Nutshell, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.