Here is code snippet which will connect to the LDAP and retireve specific user information such as user name and e-mail id from the LDAP. It uses the user id to query the ldap and find user information. This code can be customized to retrieve any of the user information available in ldap.
import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; public class LdapTest { public static void main(String[] args) { final String PROVIDER_URL = "http://ldaphost:389/o=xyz.com"; //Enter LDAP URL here final Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, PROVIDER_URL); try { DirContext ctx = new InitialDirContext(env); String filter = "(uid=1234)"; // Enter User ID here. String[] attrIDs = {"uid","cn","mail"}; // Enter list of attributes to retrieve from LDAP here SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(attrIDs); NamingEnumeration answer = ctx.search("ou=People", filter, ctls); SearchResult searchResult = null; String cn=null; String uid=null; String mail=null; while (answer.hasMore()) { searchResult = (SearchResult) answer.next(); Attributes attr = searchResult.getAttributes(); cn=attr.get("cn").get(0).toString(); uid=attr.get("uid").get(0).toString(); mail=attr.get("mail").get(0).toString(); System.out.println("Name: "+cn); System.out.println("User ID: "+uid); System.out.println("E-mail Address: "+mail); } } catch (Exception e) { e.printStackTrace(); } } }