# 范围

> 原文： [https://docs.oracle.com/javase/tutorial/jndi/ops/scope.html](https://docs.oracle.com/javase/tutorial/jndi/ops/scope.html)

默认 [`SearchControls`](https://docs.oracle.com/javase/8/docs/api/javax/naming/directory/SearchControls.html)指定在指定的上下文中执行搜索（ [`SearchControls.ONELEVEL_SCOPE`](https://docs.oracle.com/javase/8/docs/api/javax/naming/directory/SearchControls.html#ONELEVEL_SCOPE)）。此默认值用于[搜索过滤器部分](filter.html)的示例中。

除此默认值外，您还可以指定在 _ 整个子树 _ 中执行搜索，或仅在命名对象中执行搜索。

搜索整个子树搜索命名对象及其所有后代。要使搜索以这种方式运行，请将 [`SearchControls.SUBTREE_SCOPE`](https://docs.oracle.com/javase/8/docs/api/javax/naming/directory/SearchControls.html#SUBTREE_SCOPE)传递给 [`SearchControls.setSearchScope（）`](https://docs.oracle.com/javase/8/docs/api/javax/naming/directory/SearchControls.html#setSearchScope-int-) ，如下所示。

```
// 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`](examples/SearchSubtree.java) 在上下文 `ctx` 的子树中搜索满足指定过滤器的条目。它在该子树中找到满足过滤器的条目`“cn = Ted Geisel，ou = People”`。

```
# java SearchSubtree
>>>cn=Ted Geisel, ou=People
attribute: sn
value: Geisel
attribute: mail
value: Ted.Geisel@JNDITutorial.example.com
attribute: telephonenumber
value: +1 408 555 5252

```

## 搜索命名对象

您还可以搜索命名对象。例如，这可用于测试命名对象是否满足搜索过滤器。要搜索命名对象，请将 [`SearchControls.OBJECT_SCOPE`](https://docs.oracle.com/javase/8/docs/api/javax/naming/directory/SearchControls.html#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`](examples/SearchObject.java) 测试对象`“cn = Ted Geisel，ou = People”`是否满足给定的过滤器。

```
# java SearchObject
>>>
attribute: sn
value: Geisel
attribute: mail
value: Ted.Geisel@JNDITutorial.example.com
attribute: telephonenumber
value: +1 408 555 5252

```

该示例找到了一个答案并打印出来。请注意，结果的名称是空字符串。这是因为对象的名称总是相对于搜索的上下文命名（在这种情况下，`“cn = Ted Geisel，ou = People”`）。