簡體   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