Java操作LDAP有几种方法,这里主要介绍的是JNDI包,就是它:
com.sun.jndi.ldap.LdapCtxFactory
LDAP默认情况下使用的是BDB数据库,所以呢,操作LDAP就和操作数据库一样,要分几步走:
1、先导入所需的包,如下:
import java.util.ArrayList;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.DirContext;
import javax.naming.directory.Attributes;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchResult;
import javax.naming.NamingException;
import com.sun.NET.ssl.internal.ssl.Debug;
2、连接LDAP,得到连接对象,如下:
DirContext ctx = null; //这个就是LDAP的连接对象
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldap://192.168.0.1:389);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "");
env.put(Context.SECURITY_CREDENTIALS, "123456");
try
{
}
catch(NamingException e)
{
}
这里建议大家把以上的代码写成一个函数,返回DirContext 这个对象,方便使用。
3、连接LDAP后同步某一个组下面的用户,如下:
Map<String,String> map = new HashMap<String, String>();
try {
if(ctx != null){
NamingEnumeration<NameClassPair> list = ctx.list("ou=Group,dc=cs,dc=hunan,dc=com“);
while(list.hasMore()){
NameClassPair ncp = list.next();
String cn = ncp.getName();
if(StringUtil.isNotBlank(cn) && cn.indexOf("=") != -1){
int index = cn.indexOf("=");
cn = cn.substring(index + 1,cn.length());
map.put(cn, ncp.getNameInNamespace());
}
}
}
} catch (NamingException e) {
e.printStackTrace();
return;
}
try {
if(ctx != null)
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
//遍历用户
Iterator<Entry<String,String>> it = map.entrySet().iterator();
while(it.hasNext()){
Entry<String,String> entry = it.next();
System.out.println(entry.getKey())
System.out.println(entry.getValue())