无法使用Spring Ldap获取DirContext ctx

时间:2011-02-18 05:12:00

标签: spring-ldap

嗨我正在使用Spring ldap,在程序下面执行之后显示我只在这里,之后没有发生任何事情,程序处于继续执行模式。

public class SimpleLDAPClient {
        public static void main(String[] args) {
            Hashtable env = new Hashtable();
            System.out.println("I am here");
            String principal = "uid="+"a502455"+", ou=People, o=ao, dc=com";
            env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, "MYURL");
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, principal);
            env.put(Context.SECURITY_CREDENTIALS,"PASSWORD");

            DirContext ctx = null;
            NamingEnumeration results = null;
            try {
                ctx = new InitialDirContext(env);

                System.out.println(" Context" + ctx);



                SearchControls controls = new SearchControls();
                controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                results = ctx.search("", "(objectclass=aoPerson)", controls);
                while (results.hasMore()) {
                    SearchResult searchResult = (SearchResult) results.next();
                    Attributes attributes = searchResult.getAttributes();
                    Attribute attr = attributes.get("cn");
                    String cn = (String) attr.get();
                    System.out.println(" Person Common Name = " + cn);
                }
            } catch (NamingException e) {
                throw new RuntimeException(e);
            } finally {
                if (results != null) {
                    try {
                        results.close();
                    } catch (Exception e) {
                    }
                }
                if (ctx != null) {
                    try {
                        ctx.close();
                    } catch (Exception e) {
                    }
                }
            }
        }


    }

1 个答案:

答案 0 :(得分:0)

尝试修复以下行,我删除了" ao"它工作正常。

results = ctx.search("", "(objectclass=Person)", controls);

您还需要提供搜索基础

env.put(Context.PROVIDER_URL, "ldap://xx:389/DC=test,DC=enterprise,DC=xx,DC=com");

也请参阅此链接{{3}}