Use JNDI to access an LDAP.
This is the second part in my writing documentation/tutorial on how to write Java code to connect to an LDAP server. The first part focused on creating a connection with a local file system. This post assumes that you have been able to work through the first part, as you will need the skills and most of the code in that first part.
Previously we have used JNDI to access a local file system. Now we want to access an LDAP. Explaining what an LDAP is, and why we would want to access one, is beyond the scope of this post. For this example, we are going to write all of our code within the main() method of the class. (Remember, this is for instructive purposes only!)
- Here are the import statements and basic structure of the program:
* @author Kelly.Kinney
public class LDAPCtx
private static Logger log = Logger.getLogger(LDAPCtx.class);
* @param args
public static void main(String args)
- Now we add the code to create the Hashtable which will contain environment variables of the Context. This is the same as in the first part.
// Set up the environment for creating the initial context
Hashtable env = new Hashtable();
- Now the code starts to diverge from that used to access a local file system. Instead of the local filesystem, we need to include Context information for the LDAP. Note the format of the LDAP connection string. It is the connection string, followed by a colon, the LDAP host port number (usually 389), a slash, and a reference to the top level LDAP branch to be searched. With Sun One Directory Servers, this is represented by the “o=”. However, with Active Directory it is usually a string of “DC=” value pairs to indicate the top level of the directory.
- The next block of code we need to enclose in a try/catch block. Here is how to construct this block. The area indicated by the ellipses will be where the code that follows gets inserted.
catch (NamingException e)
- Inside the try/catch block, we put the rest of the code… (to be explained more tomorrow)
DirContext ctx = new InitialDirContext(env);
log.debug("Connection toString: " + ctx.toString());
Attributes matchAttrs = new BasicAttributes(true);
NamingEnumeration answer = ctx.search("ou=People", matchAttrs);
SearchResult sr = (SearchResult)answer.next();
log.debug(">>>" + sr.getName());