Home  >  JNDI

LDAP Integration with Java using JNDI

By Arvind Rai, March 27, 2014
LDAP is Lightweight Directory Access Protocol that runs over internet protocol to access and save information in distributed directory. Data can be stored in hierarchical tree structure. LDAP can be used to maintain and access telephone directory and it can also be used to maintain single sign-on. In this page we will discuss how to integrate LDAP with java using JNDI. To run example we have to configure our environment. You need local LDAP server and sample schema. You need to cover first the below two topic.

Create Local LDAP Server in Eclipse with Apache Directory Studio

How to Create LDAP Schema with Eclipse

Now we are ready with our environment. So find the example below.
LdapTest.java
package com.concretepage.ldap;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
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) throws NamingException {
		 Hashtable<String, String> conData = new Hashtable<String, String>();
		 conData.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		 conData.put(Context.PROVIDER_URL, "ldap://127.0.0.1:10389/");
		 DirContext context = new InitialDirContext(conData);
		 
		 SearchControls searchControls = new SearchControls();
		 searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		 NamingEnumeration<SearchResult> enumeration = context.search("o=cp", "(objectClass=person)", searchControls);
		 
		 while (enumeration.hasMore()) {
			 SearchResult searchResult = enumeration.next();
			 Attributes att = searchResult.getAttributes();
			 System.out.println(String.format("%s, %s, %s", att.get("cn"), att.get("uid"), att.get("sn")));
		 }
	 }
} 
 
In the example we are first creating LDAP connection. The minimum requirement is Context.INITIAL_CONTEXT_FACTORY and Context.PROVIDER_URL. Now create the directory context and search controls and set the search scope. We need to pass objectClass and base of directory to search the required tree structure of data. Find the output.
cn: Mahesh Sharma, uid: umahesh, sn: Sharma
cn: Nikhil Singh, uid: unikhil, sn: Singh
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us