62,614
社区成员
发帖
与我相关
我的任务
分享
//指定Ldap服务器的主机,端口和要访问的根目录
Properties env = new Properties();
String MY_HOST = "localhost";
int MY_PORT = 389;
String MY_SEARCHBASE = "o=Airius.com";
env.put("jndi.service.host", MY_HOST);
env.put("jndi.service.port", MY_PORT);
try {
//首先建立上下文
DSContext ctx = new InitialDSContext(env);
//指定查询的条件
SearchConstraints constraints = new SearchConstraints();
constraints.setSearchScope(SearchConstraints.SUBTREE_SCOPE);
//找到拥有名字Jensen的Entity
String MY_FILTER = "sn=Jensen";
SearchEnumeration results = ctx.search(MY_SEARCHBASE, MY_FILTER, constraints);
//对每个找到的Entity,打印出它的名字以及所有的属性
while (results != null && results.hasMoreElements()) {
SearchResult si = results.next();
//打印名字
System.out.println("name: " + si.getName());
AttributeSet attrs = si.getAttributes();
if (attrs == null) {
System.out.println("No attributes");
} else {
//打印出所有的属性值
for (AttributeEnumeration ae = attrs.getAttributes(); ae.hasMoreElements();) {
Attribute attr = ae.next();
String attrId = attr.getAttributeId();
/* print each value */
for (Enumeration vals = attr.getValues(); vals.hasMoreElements();) {
System.out.println(attrId + ": " + vals.nextElement());
}
}
}
}
} catch (NamingException e) {
System.err.println("Search example failed");
e.printStackTrace();
}