【IT168技术文档】
搜索LDAP服务器
搜索有几个要素:
ldap对象
搜索的开始点
搜索的范围
搜索查询语句(和SQL类似)
ldap对象我们已经取得了。(程序中的ctx) 搜索开始点指的是ldap目录树中某一个结点。比如:
SearchBase=”dc=jssvc,dc=com”或者 SearchBase=”ou=groups,dc=jssvc,dc=com”等。
搜索范围指的是搜索结点的所有子树或者是其它范围,具体有子树,本级,下一级, 查询语句象 sql 语句一样,比如 sn=Zeng 或者 cn=lee 等。

这里我们显示多有得记录,其中包括连接代码:
该运行程序后是搜索出所有用户的所有属性的所有值来,搜索出多少用户取决于你指定的条件 SearchContents,而显示多少属性也是可以指定的。比如你只想显示名字,地址,其它不想显示。//连接代码
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389");
![]()
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=Manager,o=JNDITutorial");
env.put(Context.SECURITY_CREDENTIALS, "secret");
![]()
String searchBase= "o=JNDITutorial";//从默认的点开始寻找,这里的根是 dc-dc
String searchContents="(ou=*)";
![]()
try ...{
/**//* get a handle to an Initial DirContext */
DirContext ctx = new InitialDirContext(env);
![]()
/**//* specify search constraints to search subtree */
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
![]()
/**//* search for all entries with surname of Jensen */
NamingEnumeration results
= ctx.search(searchBase, searchContents, constraints);
![]()
![]()
/**//* for each entry print out name + all attrs and values */
while (results != null && results.hasMore()) ...{
![]()
SearchResult si = (SearchResult)results.next();
![]()
/**//* print its name */
System.out.println("name: " + si.getName());
![]()
Attributes attrs = si.getAttributes();
if (attrs == null) ...{
System.out.println("No attributes");
} else ...{
/**//* print each attribute */
for (NamingEnumeration ae = attrs.getAll();
ae.hasMoreElements();) ...{
Attribute attr = (Attribute)ae.next();
String attrId = attr.getID();
![]()
/**//* print each value */
for (Enumeration vals = attr.getAll();
vals.hasMoreElements();
System.out.println(attrId + ": " + vals.nextElement()))
;
}
}
System.out.println();
}
} catch (NamingException e) ...{
System.err.println("Search example failed.");
e.printStackTrace();
}