Listing 1: Login.java — Logs in to an LDAP store

package jndisamples;

import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.*;

public class Login {
  public static void main(String[] args){

    // Set-up Environment
    Hashtable environment = new Hashtable();
    environment.put(Context.INITIAL_CONTEXT_FACTORY,
                    "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL, "ldap://127.0.0.1:389");
    environment.put(Context.SECURITY_PRINCIPAL, 
                    "cn=mseaver,ou=HR,o=SLC");
    environment.put(Context.SECURITY_CREDENTIALS, "password");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");

    try{
      InitialDirContext root = new InitialDirContext(environment);
      System.out.println("Successfully logged in");
      root.close();
      System.out.println("Successfully logged out");
    }catch(NamingException ex){
      System.out.println("Error: " + ex);
    }
  }
}

/* Output:
Successfully logged in
Successfully logged out
*/
— End of Listing —