Table of Contents
In this example we will use an AttributesMapper
to easily build a List of all common names of all person objects.
Example 2.1. AttributesMapper that returns a single attribute
package com.example.dao;
public class PersonDaoImpl implements PersonDao {
private LdapTemplate ldapTemplate;
public void setLdapTemplate(LdapTemplate ldapTemplate) {
this.ldapTemplate = ldapTemplate;
}
public List getAllPersonNames() {
return ldapTemplate.search(
"", "(objectclass=person)",
new AttributesMapper() {
public Object mapFromAttributes(Attributes attrs)
throws NamingException {
return attrs.get("cn").get();
}
});
}
}
The inline implementation of AttributesMapper
just gets the desired attribute value from the
Attributes
and returns it. Internally,
LdapTemplate
iterates over all entries found, calling
the given AttributesMapper
for each entry, and collects
the results in a list. The list is then returned by the
search
method.
Note that the AttributesMapper
implementation
could easily be modified to return a full Person
object:
Example 2.2. AttributesMapper that returns a Person object
package com.example.dao; public class PersonDaoImpl implements PersonDao { private LdapTemplate ldapTemplate; ... private class PersonAttributesMapper implements AttributesMapper { public Object mapFromAttributes(Attributes attrs) throws NamingException { Person person = new Person(); person.setFullName((String)attrs.get("cn").get()); person.setLastName((String)attrs.get("sn").get()); person.setDescription((String)attrs.get("description").get()); return person; } } public List getAllPersons() { return ldapTemplate.search("", "(objectclass=person)", new PersonAttributesMapper()); } }
If you have the distinguished name (dn
) that
identifies an entry, you can retrieve the entry directly, without
searching for it. This is called a lookup in Java
LDAP. The following example shows how a lookup results in a Person
object:
Example 2.3. A lookup resulting in a Person object
package com.example.dao; public class PersonDaoImpl implements PersonDao { private LdapTemplate ldapTemplate; ... public Person findPerson(String dn) { return (Person) ldapTemplate.lookup(dn, new PersonAttributesMapper()); } }
This will look up the specified dn
and pass the
found attributes to the supplied AttributesMapper
, in
this case resulting in a Person
object.