简体   繁体   中英

Java LDAP returning always a single value instead of a list

I want to query my ldap to give me all users where sn contains a specific value ( maier ). However I always get a single result.

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

Did I do anything wrong?

You're not looping, so of course you're only getting one result. Change if (answer.hasMore()) to while (answer.hasMore()) .

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