Building Dynamic Filters

We can build dynamic filters to use in searches, using the classes from the org.springframework.ldap.filter package. Let's say that we want the following filter: (&(objectclass=person)(sn=?)), where we want the ? to be replaced with the value of the parameter lastName. This is how we do it using the filter support classes:

Example 2.4. Building a search filter dynamically

package com.example.dao;

public class PersonDaoImpl implements PersonDao {
   private LdapTemplate ldapTemplate;
   ...
   public List getPersonNamesByLastName(String lastName) {
      AndFilter filter = new AndFilter();
      filter.and(new EqualsFilter("objectclass", "person"));
      filter.and(new EqualsFilter("sn", lastName));
      return ldapTemplate.search(
         "", filter.encode(),
         new AttributesMapper() {
            public Object mapFromAttributes(Attributes attrs)
               throws NamingException {
               return attrs.get("cn").get();
            }
         });
   }
}

To perform a wildcard search, it's possible to use the WhitespaceWildcardsFilter:

Example 2.5. Building a wildcard search filter

AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "person"));
filter.and(new WhitespaceWildcardsFilter("cn", cn));

Note

In addition to simplifying building of complex search filters, the Filter classes also provide proper escaping of any unsafe characters. This prevents "ldap injection", where a user might use such characters to inject unwanted operations into your LDAP operations.