Read Attributes
要从目录中读取对象的属性,请使用DirContext.getAttributes()并将其想要获得其属性的对象的名称传递给它。假设命名服务中的对象名称为"cn=Ted Geisel, ou=People"
。要检索该对象的属性,您将需要code如下所示:
Attributes answer = ctx.getAttributes("cn=Ted Geisel, ou=People");
然后,您可以按以下方式打印此答案的内容。
for (NamingEnumeration ae = answer.getAll(); ae.hasMore();) {
Attribute attr = (Attribute)ae.next();
System.out.println("attribute: " + attr.getID());
/* Print each value */
for (NamingEnumeration e = attr.getAll(); e.hasMore();
System.out.println("value: " + e.next()))
;
}
这将产生以下输出。
# java GetattrsAll
attribute: sn
value: Geisel
attribute: objectclass
value: top
value: person
value: organizationalPerson
value: inetOrgPerson
attribute: jpegphoto
value: [B@1dacd78b
attribute: mail
value: [email protected]
attribute: facsimiletelephonenumber
value: +1 408 555 2329
attribute: telephonenumber
value: +1 408 555 5252
attribute: cn
value: Ted Geisel
返回所选属性
要读取选择性的属性子集,请提供字符串 数组,这些字符串 是要检索的属性的属性标识符。
// Specify the ids of the attributes to return
String[] attrIDs = {"sn", "telephonenumber", "golfhandicap", "mail"};
// Get the attributes requested
Attributes answer = ctx.getAttributes("cn=Ted Geisel, ou=People", attrIDs);
This example要求对象"cn=Ted Geisel, ou=People"
的"sn"
,"telephonenumber"
,"golfhandicap"
和"mail"
属性。该对象具有"golfhandicap"
以外的所有属性,因此答案中将返回三个属性。以下是示例的输出。
# java Getattrs
attribute: sn
value: Geisel
attribute: mail
value: [email protected]
attribute: telephonenumber
value: +1 408 555 5252