Working With JNDI In A J2SE Application

0

Java Naming and Directory Interface (JNDI) allows Java objects to be published to a directory service which can be accessed by other Java applications later. For this to work you need a JNDI service provider. All the J2EE servers come with a built-in implementation of the JNDI service. This makes most people assume that you can work with JNDI only in J2EE environment. It is possible for you to set up your own lightweight JNDI server, host your J2SE objects on this and make these objects available for other's use. There are varieties of JNDI service providers available. In this article, I am going to refer to the one provided by JBOSS.

The following .jar files must be added to your classpath in order to setup the server, host an object, and to access the same.

1) log4j.jar

2) jnpserver.jar

3) jboss-common.jar

4) concurrent.jar

In addition, you must also have the log4j.properties file in your classpath. These files are available with the Jboss binary distribution.

To setup the environment you can also type the following in a text file (setJNPEnv.cmd)

set JNP_HOME = C: jnp

set JNP_LIB =% JNP_HOME% lib

set JNP_PATH =% JNP_LIB%;% JNP_LIB% log4j.jar

set JNP_PATH =% JNP_PATH%;% JNP_LIB% jnpserver.jar

set JNP_PATH =% JNP_PATH%;% JNP_LIB% jboss-common.jar

set JNP_PATH =% JNP_PATH%;% JNP_LIB% concurrent.jar

set CLASSPATH =.;% JNP_PATH%;% CLASSPATH%

Make sure to change the JNP_HOME environment variable's value to the folder, where you have extracted the jnp.zip.

To start the JNDI service, open a command prompt and type the following command:

c: work> setJNPEnv.cmd

c: work> start java org.jnp.server.Main

This opens a new window which represents the JNP (Jboss Naming Provider) server listening at port 1099.

Now you can store any object you want in the JNDI using the code below:

Context ctx = new InitialContext ();

ctx.rebind ("name1", "Vinod");

ctx.rebind ("person1", new Person ("Vinod", "Bangalore");

Also, you can lookup and obtain an object using the code below:

Context ctx = new InitialContext ();

String name = (String) ctx.lookup ("name1");

Person p1 = (Person) ctx.lookup ("person1");

One last thing. You must provide the information about JNDI provider when you call new InitialContext (). This is usually done by placing a jndi.properties file in you working directory or supplying a java.util.Map object. Here is the content of jndi.properties file:

java.naming.provider.url = localhost: 1099

java.naming.factory.initial = org.jnp.interfaces.NamingContextFactory

java.naming.factory.url.pkgs = org.jboss.naming



Source

You might also like

Leave A Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More