package test;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
public class LdapImpl {
private DirContext ds;
public void search() throws NamingException {
System.out.println(“Searching…”);
SearchControls searchCtls = new SearchControls();
// Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// specify the LDAP search filter
String searchFilter = “(sAMAccountName=adamli)”;
// Specify the Base for the search
String searchBase = “dc=XX,dc=XX”;
// Specify the attributes to return
String returnedAtts[] = {“mail”, “displayName”};
searchCtls.setReturningAttributes(returnedAtts);
// Search for objects using the filter
NamingEnumeration entries = ds.search(searchBase,
searchFilter, searchCtls);
// Loop through the search results
while (entries.hasMoreElements()) {
SearchResult entry = entries.next();
System.out.println(“>>>” + entry.getName());
// Print out the groups
Attributes attrs = entry.getAttributes();
if (attrs != null) {
for (NamingEnumeration extends Attribute> names = attrs
.getAll(); names.hasMore();) {
Attribute attr = names.next();
System.out.println(“AttributeID: ” + attr.getID());
for (NamingEnumeration> e = attr.getAll(); e.hasMore();) {
System.out.println(“Attributes:” + e.next());
}
}
}
}
System.out.println(“Search complete.”);
}
public synchronized void connect() throws NamingException {
System.out.println(“connecting…”);
if (ds == null) {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, “com.sun.jndi.ldap.LdapCtxFactory”);
env.put(Context.PROVIDER_URL, “ldap://ip:port”);
env.put(Context.SECURITY_AUTHENTICATION, “simple”);
env.put(Context.SECURITY_PRINCIPAL, “username”);
env.put(Context.SECURITY_CREDENTIALS, “password”);
ds = new InitialDirContext(env);
}
System.out.println(“connected.”);
}
public void close() throws NamingException {
System.out.println(“closing…”);
ds.close();
System.out.println(“closed.”);
}
}
package test;
import javax.naming.NamingException;
public class LdapDemo {
public static void main(String[] args) {
LdapImpl ldap = new LdapImpl();
try {
ldap.connect();
ldap.search();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/35433.html