Java 如何使用spring在ldap中执行搜索操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6434999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:53:27  来源:igfitidea点击:

How to perform search operation in ldap using spring

javaldapspring-ldap

提问by Raje

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 i m using ldap template. How can i modify this code so that it return person object?

我想从 ldap 中搜索特定的用户详细信息。所以我写下了以下检索用户详细信息的代码,但它返回用户对象列表。基本上我只想要人对象而不是人对象列表。用于使用 ldap 模板检索即时消息。如何修改此代码以使其返回 person 对象?

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();
                }
            });


}

采纳答案by Matt Ryall

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 loginIdexists, you are using the correct method already. Just check the length of the list and retrieve the first item from the returned list.

您正在调用的方法ldapTemplate.search()始终返回匹配对象的列表。这是因为它正在 LDAP 服务器上查找与您的条件匹配的所有对象。如果您不确定是否loginId存在与您匹配的用户,那么您已经在使用正确的方法。只需检查列表的长度并从返回的列表中检索第一项。

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.

要仅从 LDAP 获取单个项目,您需要知道LDAP 服务器中用户的专有名称(DN)。DN 是 LDAP 中对象的唯一标识符,如果要专门查找单个对象,则需要知道这一点。根据您的 LDAP 配置,这可能类似于cn=<loginId>,ou=users,dc=yourorg,dc=com.

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

如果您可以从现有的 DN 中构造 DN,则loginId可以使用ldapTemplate.lookup(String, AttributesMapper)方法来查找单个对象。