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