你可以找到一个很好的代码示例
here
:
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/dc=fraglab,dc=net");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=fraglab,dc=net");
env.put(Context.SECURITY_CREDENTIALS, "yannis");
DirContext ctx = new InitialDirContext(env);
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setCountLimit(10);
NamingEnumeration<SearchResult> namingEnumeration =
ctx.search("", "(uid=*)", new Object[]{}, searchControls);
while (namingEnumeration.hasMore()) {
SearchResult sr = namingEnumeration.next();
System.out.println("DN: " + sr.getName());
System.out.println(sr.getAttributes().get("uid"));
System.out.println("Password:" + new String((byte[]) sr.getAttributes().get("userPassword").get()));
}
ctx.close();
它使用LDAP命名服务提供程序
Java命名与目录接口
JNDI
,并且应该使用小的调整来执行您想要的操作(例如,至少输入服务器的名称)。这个
documentation for the ldap provider
非常好,可以帮助你满足你的需要。