Create an Initial Context to the Naming service
With this tutorial we shall show you how to create an Initial Context to the Naming service to get you going. This example uses the default naming service provider setup on the JVM.
For connecting to alternate naming service providers you should construct a Hashtable containing appropriate environment directives and initialize the InitialContext Object using the InitialContext(Hashtable env) constructor injecting the environment table.
For example, connecting to an RMI Registry naming service running on local host and on port 1099 the environment that should be created is like the one shown below :
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
env.put(Context.PROVIDER_URL, "rmi://localhost:1099");
Let’s see the code:
package com.javacodegeeks.snippets.enterprise; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; public class CreateInitialContext { public static void main(String[] args) { try { /* * Another example; connecting to JBoss naming service running on local host and on default port * 1099 the environment that should be created is like the one shown below : * * Hashtable env = new Hashtable(); * env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory"); * env.put(Context.PROVIDER_URL, "jnp://localhost:1099"); * env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces"); * */ Context ctx = new InitialContext(); System.out.println("Initial Context created successfully"); } catch (NamingException e) { System.out.println("Exception occurred while creating InitialContext : " + e.getMessage()); } } }
Output:
Initial Context created successfully
This was an example on how to create an Initial Context to the Naming service.