1.连接LDAP:
HashEnv.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
HashEnv.put(Context.SECURITY_AUTHENTICATION, "simple");// "none","simple","strong"
HashEnv.put(Context.SECURITY_PRINCIPAL, getRootname());//管理员账号
HashEnv.put(Context.SECURITY_CREDENTIALS, getPwd());//密码
HashEnv.put(Context.PROVIDER_URL, getUrl() + getBasedn());//密码
ctx = new InitialLdapContext(HashEnv, null);
查询数据:
String userDN = "";
try {
connectToLDAP();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> en = ctx.search("", "uid=" + uid,
constraints);
if (en == null || !en.hasMoreElements()) {
System.out.println("未找到该用户");
}
// maybe more than one element
while (en != null && en.hasMoreElements()) {
Object obj = en.nextElement();
if (obj instanceof SearchResult) {
SearchResult si = (SearchResult) obj;
userDN += si.getName();
userDN += "," + getBasedn();
} else {
System.out.println(obj);
}
}
} catch (Exception e) {
System.out.println("查找用户时产生异常。");
throw new BusinessException("查找用户时产生异常。");
}
新增数据:
connectToLDAP();
BasicAttributes attrsbu = new BasicAttributes();
BasicAttribute objclassSet = new BasicAttribute("objectClass");
objclassSet.add("inetOrgPerson");//定义的对象类。类似Java的对象。要加上所有的超类和抽象类
attrsbu.put(objclassSet);
attrsbu.put("mail", usr);
attrsbu.put("cn", usr);
attrsbu.put("uid", "mousepoatoc");
attrsbu.put("userPassword", pwd);
attrsbu.put("labeledURI", usr);
attrsbu.put("sn", pwd);
// ctx.bind(arg0, arg1, arg2);(objclassSet, attrsbu);
ctx.createSubcontext("uid=mousepoatoc", attrsbu);//第一个参数为ID
return true;
删除数据:
ctx.destroySubcontext("orgId=" + orgvo.getPk_corp());//传入值
使用工具LdapAdmin可查看数据信息和超类信息