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

时间:2015-11-16 06:54:56

标签: java ldap jndi

我想查询我的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;
}

我做错了吗?

1 个答案:

答案 0 :(得分:1)

你没有循环,所以你当然只得到一个结果。将if (answer.hasMore())更改为while (answer.hasMore())