LDAP Connection Sample Code
Below is LDAP Connection Sample Code to show to you how to connect LDAP server. Please use this
program and replace your LDAP domain name and port number and it also need valid user id and password to access the record from LDAP server.
Sample code to connect to LDAP server using java.
LDAP Connection Sample Code:
package com.ldap; import java.util.Hashtable; import javax.naming.*; import javax.naming.directory.*; public class LDAPConnectionSampleCode { public static String usersContainer = "cn=users,DC=domainName,DC=companyName,DC=com"; public static void main(String args[]){ Hashtable<String,String> env = new Hashtable<String,String>(); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://domainName"); env.put( Context.SECURITY_PRINCIPAL, "domainName\\userId" ); env.put( Context.SECURITY_CREDENTIALS, "password" ); try { DirContext ctx = new InitialDirContext(env); SearchControls ctls = new SearchControls(); /*String[] attrIDs = {"cn"}; ctls.setReturningAttributes(attrIDs);*/ ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE); /*ctls.setCountLimit(0); ctls.setTimeLimit(0);*/ SearchControls sc = new SearchControls(); String[] attributeFilter = { "cn", "mail" }; sc.setReturningAttributes(attributeFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String base = "ou=People"; String filter = "(&(sn=W*)(l=Criteria*))"; NamingEnumeration answer = ctx.search( usersContainer, "(objectclass=group)",ctls ); while(answer.hasMore()) { SearchResult rslt = (SearchResult)answer.next(); Attributes attrs = rslt.getAttributes(); System.out.println(attrs.get("cn")); } while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute attr = attrs.get("cn"); System.out.print(attr.get() + ": "); attr = attrs.get("mail"); System.out.println(attr.get()); } ctx.close(); } catch (NamingException e) { e.printStackTrace(); } } }