共計 2078 個字符,預計需要花費 6 分鐘才能閱讀完成。
Java 中使用 LDAP(輕量級目錄訪問協議)可以進行目錄服務的連接、搜索、添加、修改和刪除等操作。
- 連接 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);
- 搜索 LDAP 目錄:
使用 LDAP 搜索可以根據指定的搜索條件在 LDAP 目錄中查找符合條件的條目??梢允褂?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);
}
- 添加條目到 LDAP 目錄:
使用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);
- 修改 LDAP 目錄中的條目:
使用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);
- 刪除 LDAP 目錄中的條目:
使用context.destroySubcontext()
方法可以刪除 LDAP 目錄中的條目。
String dn = "cn=user,ou=people,dc=example,dc=com";
context.destroySubcontext(dn);
以上是 Java 中 LDAP 的基本用法,可以根據具體需求進行進一步的操作和擴展。
丸趣 TV 網 – 提供最優質的資源集合!
正文完