简体   繁体   中英

How to perform search operation in ldap using spring

I want to search specific user details from ldap. so i have wrote down following code retrieving user details but it returns list of user object. Basically i want only person obejct not list of person objects. for retreiving im using ldap template. How can i modify this code so that it return person object?

public void searchByFirstName(String loginId) {

        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectclass", "Person"));
        filter.and(new EqualsFilter("cn", loginId));
        List list = ldapTemplate.search("", 
            filter.encode(),
            new AttributesMapper() {
                public Object mapFromAttributes(Attributes attrs) throws NamingException        {
                    return attrs.get("sn").get();
                }
            });


}

The method you're calling, ldapTemplate.search() always returns a list of matching objects. This is because it is finding all the objects that match your criteria on the LDAP server. If you're not certain that a user matching your loginId exists, you are using the correct method already. Just check the length of the list and retrieve the first item from the returned list.

To get just a single item from LDAP, you need to know the distinguished name (DN) of a user in the LDAP server. A DN is a unique identifier of an object in LDAP, and you need to know this if you're going to look up a single object specifically. Depending on your LDAP configuration, this might be something like cn=<loginId>,ou=users,dc=yourorg,dc=com .

If you can construct the DN from the loginId you have, you can use the ldapTemplate.lookup(String, AttributesMapper) method to find just a single object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM