1.初始化上下文
public InitialDirContext createLDAPContext(String ldapHost, String ldapPort, String bindDN, String bindPwd)
throws NamingException
{
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.factory.url.pkgs", "com.ibm.jndi");
env.put("java.naming.provider.url", "ldap://" + ldapHost + ":" + ldapPort);
env.put("java.naming.security.principal", bindDN);
env.put("java.naming.security.credentials", bindPwd);
InitialDirContext dirCtx = new InitialDirContext(env);
return dirCtx;
}
2.获取uid为20170808用户的姓名
姓名属性为displayName,参数:
dn=”uid=20170808,dc=test,dc=com”,attrName=”displayName”
public synchronized String getLDAPAttribute(String dn, String attrName, DirContext dirCtx) {
String result = null;
boolean rebuilt = false;
try { Attributes attrs;
Attribute attr;
do { attrs = dirCtx.getAttributes(dn);
attr = attrs.get(attrName); }
while (attrs == null);
result = (String)attr.get();
} catch (CommunicationException ce)
{
while (true) {
if (!rebuilt) {
try
{
createLDAPContext(SystemProperties.getLDAP_HOST(), SystemProperties.getLDAP_PORT(), SystemProperties.getLDAP_BINDDN(), SystemProperties.getLDAP_BINDPASSWORD());
rebuilt = true;
}
catch (NamingException ne) {
log.error(ne.toString());
}
}
}
}
catch (Exception ex)
{
log.error("*********LDAP attribute not found: " + ex.toString() + "**********");
}
log.info("********getLDAPAttribute(): exit (" + result + ").*********");
return result;
}