近来,为了解决LDAP相关的问题,补了一补LDAP相关的知识。下面的是一个简单例子:
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LdapTest {
public static void main(String[] args) throws NamingException {
LdapTest LDAPTest1 = new LdapTest();
String root = "DC=corp,DC=dell";
Hashtable exp = new Hashtable();
exp.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
exp.put(Context.PROVIDER_URL, "ldap://10.67.10.230/" + root);
exp.put(Context.SECURITY_AUTHENTICATION, "simple");
exp.put(Context.SECURITY_PRINCIPAL, "cn//cnsystem");
exp.put(Context.SECURITY_CREDENTIALS, "dell#123");
DirContext idc = null;
try {
idc = new InitialDirContext(exp);
System.out.println("verify success");
System.out.println("---------------------------------");
Attributes attributes = idc.getAttributes("");
Attribute attr = null;
NamingEnumeration nameEnu;
for (NamingEnumeration item = attributes.getAll(); item.hasMore();) {
attr = (Attribute) item.next();
System.out.print(attr.getID() + ": ");
nameEnu = attr.getAll();
while (nameEnu.hasMore()) {
System.out.print(nameEnu.next());
System.out.print("/n");
}
}
}catch (Exception e) {
System.out.println("verify fail");
System.out.println("---------------------------------");
e.printStackTrace();
}finally{
idc.close();
}
}
}