基本搜索
原文: https://docs.oracle.com/javase/tutorial/jndi/ops/basicsearch.html
最简单的搜索形式要求您指定条目必须具有的属性集以及执行搜索的目标上下文的名称。
以下代码创建了一个属性集matchAttrs
,它有两个属性“sn”
和“mail”
。它指定合格条目必须具有姓氏(“sn”
)属性,其值为“Geisel”
和“邮件”
属性,具有任何值。然后调用 DirContext.search()
搜索上下文“ou = People”
,查找具有matchAttrs
指定属性的条目。
// Specify the attributes to match
// Ask for objects that has a surname ("sn") attribute with
// the value "Geisel" and the "mail" attribute
// ignore attribute name case
Attributes matchAttrs = new BasicAttributes(true);
matchAttrs.put(new BasicAttribute("sn", "Geisel"));
matchAttrs.put(new BasicAttribute("mail"));
// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("ou=People", matchAttrs);
然后,您可以按如下方式打印结果。
while (answer.hasMore()) {
SearchResult sr = (SearchResult)answer.next();
System.out.println(">>>" + sr.getName());
printAttrs(sr.getAttributes());
}
printAttrs()
类似于 打印属性集的示例。
运行 this example
会产生以下结果。
# java SearchRetAll
>>>cn=Ted Geisel
attribute: sn
value: Geisel
attribute: objectclass
value: top
value: person
value: organizationalPerson
value: inetOrgPerson
attribute: jpegphoto
value: [B@1dacd78b
attribute: mail
value: Ted.Geisel@JNDITutorial.example.com
attribute: facsimiletelephonenumber
value: +1 408 555 2329
attribute: cn
value: Ted Geisel
attribute: telephonenumber
value: +1 408 555 5252
上一个示例返回了与满足指定查询的条目关联的所有属性。您可以通过传递search()
要包含在结果中的属性标识符数组来选择要返回的属性。在创建matchAttrs
之后,如前所示,您还需要创建属性标识符数组,如下所示。
// Specify the ids of the attributes to return
String[] attrIDs = {"sn", "telephonenumber", "golfhandicap", "mail"};
// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("ou=People", matchAttrs, attrIDs);
This example
返回属性“sn”
,“telephonenumber”
,“golfhandicap”
和“mail”[具有属性
“mail”且具有
“sn”属性且具有值
“Geisel”的条目的 HTG9]。此示例生成以下结果。 (该条目没有
“golfhandicap”属性,因此不会返回。)
# java Search
>>>cn=Ted Geisel
attribute: sn
value: Geisel
attribute: mail
value: Ted.Geisel@JNDITutorial.example.com
attribute: telephonenumber
value: +1 408 555 5252