繁体   English   中英

Java LDAP始终返回单个值而不是列表

[英]Java LDAP returning always a single value instead of a list

我想查询我的ldap,以便给我所有用户,其中sn包含特定值( maier )。 但是我总是得到一个结果。

public LdapContext getLdapContext(){
    LdapContext ctx = null;
    try{
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://ldap.url:389");
        ctx = new InitialLdapContext(env, null);
        System.out.println("Connection Successful.");
    }catch(NamingException nex){
        System.out.println("LDAP Connection: FAILED");
        nex.printStackTrace();
    }
    return ctx;
}

private User getUserBasicAttributes(String username, LdapContext ctx) {
    User user=null;
    try {

        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { "distinguishedName",
                "sn",
                "givenname",
                "mail",
                "telephonenumber"};
        constraints.setReturningAttributes(attrIDs);
        constraints.setCountLimit(200);
        NamingEnumeration answer = ctx.search("DC=myDc,DC=com", "sn=*maier*", constraints);
        if (answer.hasMore()) {
            Attributes attrs = ((SearchResult) answer.next()).getAttributes();
            System.out.println("distinguishedName "+ attrs.get("distinguishedName"));
            System.out.println("givenname "+ attrs.get("givenname"));
            System.out.println("sn "+ attrs.get("sn"));
            System.out.println("mail "+ attrs.get("mail"));
            System.out.println("telephonenumber "+ attrs.get("telephonenumber"));
        }else{
            throw new Exception("Invalid User");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return user;
}

我做错了吗?

您不会循环播放,因此当然只能得到一个结果。 if (answer.hasMore())更改为while (answer.hasMore())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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