Use JNDI to access an LDAP (part 2).
In the previous part, we began working with the code to create a connection to an LDAP. The code is listed completely in parts with the core of it below. See the box.net widget in the blog here to obtain the LDAPCtx.java code.
- The DirectoryContext is going to be defined from the env variable, which is the Hashtable containing our environment variables.
DirContext ctx = new InitialDirContext(env);
- Next we define the Attributes we are going to be looking for. Attributes is an interface which represents a collection of values (attributes) associated with an object.
Attributes matchAttrs = new BasicAttributes(true);
- The next line includes BasicAttribute which implements the Attributes interface with an unordered attribute and its value. In this instance, the attribute is “uid” and its value is”Vice.Pres.”
- Now we implement the interface NamingEnumeration to contain the results of searching our connection for our given attributes value pair.
NamingEnumeration answer = ctx.search("ou=People", matchAttrs);
- Finally, while there are results in our enumeration, we print them out to the console.
SearchResult sr = (SearchResult)answer.next();
log.debug(">>>" + sr.getName());