我关注了this在 Activity 目录中搜索的教程。
示例代码:
class SearchSubtree {
public static void main(String[] args) {
Hashtable<String, Object> env = new Hashtable<String, Object>(11);
env
.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");
try {
DirContext ctx = new InitialDirContext(env);
String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" };
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(sn=Geisel)(mail=*))";
NamingEnumeration answer = ctx.search("", filter, ctls);
// Print the answer
ctx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
但是NameNotFoundException
被抛出
NamingEnumerationanswer = ctx.search("",filter,ctls);
但是当我通过 "DC=extldap,DC=com"
作为第一个参数时,代码工作正常。
教程有问题吗?第一个参数不能为空字符串吗?或者这是 Active Directory 的限制?
最佳答案
一般来说,对于 LDAP 服务器,您始终需要一个根上下文来开始搜索。基本上,您所做的相当于尝试在不指定数据库或表名称的情况下搜索 SQL 数据库。
某些服务器实现可能允许空上下文(我知道 iPlanet 在某些情况下曾经允许它),但这些是规则的异常(exception)。
DirContext.search()
的 javadoc说:
Searches in the named context or object for entries that satisfy the given search filter. Performs the search as specified by the search controls.
See
search(Name, String, SearchControls)
for details.Parameters:
- name the name of the context or object to search
...
通常,在 Active Directory 中,可以从域根开始搜索,该根始终为 DC=<your>,DC=<domain>
。
这就是您的第二次搜索有效的原因。
关于java - Active Directory - 通过指定搜索过滤器和搜索控件进行搜索,无需上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34139297/