naming

Create an Initial Context to a Directory

In this example we are going to see how to create an Initial Context to a Directory. This example uses the JNDI/LDAP service provider to connect to an LDAP server on the local machine.

In order to do that you should :

  • Create a new Hashtable.
  • Use put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory")
  • Use put(Context.PROVIDER_URL, "ldap://localhost/o=JNDIExample").
  • For simple authentication we can use :
    • env.put(Context.SECURITY_AUTHENTICATION, "simple")
    • env.put(Context.SECURITY_PRINCIPAL, "userDN")
    • env.put(Context.SECURITY_CREDENTIALS, "secret")
  • Create a new DirContext using InitialDirContext method .

Let’s see the code:

package com.javacodegeeks.snippets.enterprise;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class CreateInitialDirContext {

  public static void main(String[] args) {

// This example uses the JNDI/LDAP service provider to connect to an LDAP server on the local machine

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

env.put(Context.PROVIDER_URL, "ldap://localhost/o=JNDIExample");

/*

 * For simple authentication we can use :

 *

 * env.put(Context.SECURITY_AUTHENTICATION, "simple");

 * env.put(Context.SECURITY_PRINCIPAL, "userDN");

 * env.put(Context.SECURITY_CREDENTIALS, "secret");

 */

try {

    DirContext ctx = new InitialDirContext(env);

    System.out.println("Initial Directory Context created successfully");

} catch (NamingException e) {

    System.out.println("Could not create directory context : " + e.getMessage());

}

  }
}

Example Output:

Initial Directory Context created successfully

 
This was an example on how to create an Initial Context to a Directory.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button