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的基本用法,可以根據具體需求進行進一步的操作和擴展。