Scope
默认值SearchControls指定要在命名上下文(SearchControls.ONELEVEL_SCOPE)中执行搜索。 搜索过滤器部分中的示例中使用了默认值。
除了此默认值之外,您还可以指定在* entire 子树*中或仅在命名对象中执行搜索。
搜索子树
整个子树的搜索将搜索命名对象及其所有后代。要使搜索以这种方式进行,请按以下方式将SearchControls.SUBTREE_SCOPE传递给SearchControls.setSearchScope()。
// Specify the ids of the attributes to return
String[] attrIDs = {"sn", "telephonenumber", "golfhandicap", "mail"};
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Specify the search filter to match
// Ask for objects that have the attribute "sn" == "Geisel"
// and the "mail" attribute
String filter = "(&(sn=Geisel)(mail=*))";
// Search the subtree for objects by using the filter
NamingEnumeration answer = ctx.search("", filter, ctls);
This example在上下文ctx
的子树中搜索满足指定过滤器的条目。它在此子树中找到满足过滤条件的条目"cn= Ted Geisel, ou=People"
。
# java SearchSubtree
>>>cn=Ted Geisel, ou=People
attribute: sn
value: Geisel
attribute: mail
value: [email protected]
attribute: telephonenumber
value: +1 408 555 5252
搜索命名对象
您也可以搜索命名对象。例如,这对于测试命名对象是否满足搜索过滤器很有用。要搜索命名的对象,请将SearchControls.OBJECT_SCOPE传递给setSearchScope\(\)
。
// Specify the ids of the attributes to return
String[] attrIDs = {"sn", "telephonenumber", "golfhandicap", "mail"};
SearchControls ctls = new SearchControls();
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.OBJECT_SCOPE);
// Specify the search filter to match
// Ask for objects that have the attribute "sn" == "Geisel"
// and the "mail" attribute
String filter = "(&(sn=Geisel)(mail=*))";
// Search the subtree for objects by using the filter
NamingEnumeration answer =
ctx.search("cn=Ted Geisel, ou=People", filter, ctls);
This example测试对象"cn=Ted Geisel, ou=People"
是否满足指定的过滤条件。
# java SearchObject
>>>
attribute: sn
value: Geisel
attribute: mail
value: [email protected]
attribute: telephonenumber
value: +1 408 555 5252
该示例找到了一个答案并将其打印出来。请注意,结果的名称是空字符串。这是因为对象名称总是相对于搜索上下文命名(在这种情况下为"cn=Ted Geisel, ou=People"
)。