In this post under Java LDAP, I will show with example how to retrieve specific attributes when doing basic search.
For our example we will use the below ldap hierarchy.

Now lets see the main code which actually does the search.
Main class
1 package package11;
2
3 import javax.naming.Context;
4 import javax.naming.NamingEnumeration;
5 import javax.naming.NamingException;
6 import javax.naming.directory.*;
7 import java.util.Hashtable;
8
9 public class LDAPDemo11 {
10 public static void main(String[] args) {
11 Hashtable<String, Object> env = new Hashtable<String, Object>();
12 env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
13 env.put(Context.PROVIDER_URL, "ldap://localhost:1389");
14 env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=example,dc=org");
15 env.put(Context.SECURITY_CREDENTIALS, "adminpassword");
16
17 DirContext dirContext = null;
18 try {
19 dirContext = new InitialDirContext(env);
20
21 Attributes attributes = new BasicAttributes();
22 attributes.put("description", "Software engineer 1");
23
24 String[] attrIds = new String[] {"cn", "description"};
25
26 NamingEnumeration<SearchResult> searchResultNamingEnumeration = dirContext.search("ou=dev,dc=example,dc=org", attributes, attrIds);
27
28 while(searchResultNamingEnumeration.hasMore()) {
29 SearchResult searchResult = searchResultNamingEnumeration.next();
30 System.out.println(searchResult);
31 }
32 } catch(Exception excep) {
33 excep.printStackTrace();
34 } finally {
35 if(dirContext != null) {
36 try {
37 dirContext.close();
38 } catch(NamingException excep) {
39 excep.printStackTrace();
40 }
41 }
42 }
43 }
44 }
In the above code, at line 19, I get a connection to LDAP.
At line 22, I create the where condition of the search. So I am basically telling get all the ldap records where “description” attributes value is “Software engineer 1”.
At line 24, I create a string array and list the attributes which has to be retrieved from the matching records. Please note I used the attribute id in the String array.
At line 26, I perform the actual search. I have provided the below information
1) the context within which the search has to be performed.
2) the where condition
3) the attributes to be retrieved
Then in the while loop, I print the results.
Below is the output for your reference. As you can see from the output only “cn”, and “description” attribute is returned and printed.
Output
cn=user2: null:null:{description=description: Software engineer 1, cn=cn: user2}
cn=user3: null:null:{description=description: Software engineer 1, cn=cn: user3}
In this way we can retrieve specific attributes from a search.