Java中使用LDAP(轻量级目录访问协议)可以进行目录服务的连接、搜索、添加、修改和删除等操作。
InitialLdapContext
类创建一个LDAP上下文连接对象,需要指定LDAP服务器的地址、端口和认证信息。String url = "ldap://localhost:389";
String user = "cn=admin,dc=example,dc=com";
String password = "password";
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, user);
env.put(Context.SECURITY_CREDENTIALS, password);
InitialLdapContext context = new InitialLdapContext(env, null);
SearchControls
类设置搜索的范围、返回的属性等。String baseDN = "dc=example,dc=com";
String filter = "(objectClass=person)";
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setReturningAttributes(new String[] { "cn", "email" });
NamingEnumeration<SearchResult> results = context.search(baseDN, filter, controls);
while (results.hasMore()) {
SearchResult result = results.next();
Attributes attrs = result.getAttributes();
String cn = attrs.get("cn").get().toString();
String email = attrs.get("email").get().toString();
System.out.println("CN: " + cn + ", Email: " + email);
}
BasicAttributes
类创建要添加的条目的属性集合,并使用context.createSubcontext()
方法添加到LDAP目录中。String dn = "cn=user,ou=people,dc=example,dc=com";
BasicAttributes attrs = new BasicAttributes();
attrs.put(new BasicAttribute("objectClass", "person"));
attrs.put(new BasicAttribute("cn", "user"));
attrs.put(new BasicAttribute("sn", "User"));
attrs.put(new BasicAttribute("email", "user@example.com"));
context.createSubcontext(dn, attrs);
context.modifyAttributes()
方法可以修改LDAP目录中的条目的属性值。String dn = "cn=user,ou=people,dc=example,dc=com";
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("email", "newemail@example.com"));
context.modifyAttributes(dn, mods);
context.destroySubcontext()
方法可以删除LDAP目录中的条目。String dn = "cn=user,ou=people,dc=example,dc=com";
context.destroySubcontext(dn);
以上是Java中LDAP的基本用法,可以根据具体需求进行进一步的操作和扩展。