LDAP Connection Sample Java

LDAP Connection Sample Java

LDAP Connection Sample Java demo program show 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.

LDAP Connection Sample Java sample code:

package com.ldap;

import java.util.Hashtable;

import javax.naming.*;
import javax.naming.directory.*;

public class LDAPConnectionSample {
	public static String ldapUri = "ldap://domainName";
	public static String usersContainer = "cn=users,DC=pte-am,DC=companyName,DC=com";

	public static void main(String args[]) {

		String username = "domainName\\userid";
		String password = "password";

		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.PROVIDER_URL, ldapUri);
		env.put(Context.SECURITY_PRINCIPAL, username);
		env.put(Context.SECURITY_CREDENTIALS, password);

		try {
			DirContext ctx = new InitialDirContext(env);
			SearchControls ctls = new SearchControls();
			String[] attrIDs = { "cn" };

			NamingEnumeration answer = ctx.search(usersContainer,
					"(objectclass=group)", ctls);
			while (answer.hasMore()) {
				SearchResult rslt = (SearchResult) answer.next();
				Attributes attrs = rslt.getAttributes();

		} catch (NamingException e) {




Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *