[英]Java how to get an Attribute from ldap using the DN?
我有一个用于搜索组的Java应用程序。 它基于组名(cn)进行搜索时效果很好,但是有时我会得到一个以上的结果,因为在其他分支中使用了相同的cn。 我有该组的DN,我想知道如何根据DN进行搜索,或者因为我有完整的路径,是否可以直接访问该属性。 这是我使用的代码:
public Group getGroup( String groupName) throws Exception {
List<User> memberList = new ArrayList<User>();
// Create the search controls
SearchControls searchCtls = new SearchControls();
// Specify the search scope
searchCtls.setSearchScope( SearchControls.SUBTREE_SCOPE );
// Specify the attributes to return
String returnedAtts[] = { MEMBER_FIELD };
searchCtls.setReturningAttributes( returnedAtts );
// Specify the LDAP search filter
String searchFilter = "(&(objectClass=group)(CN=" + groupName + "))";
// Search for objects using the filter
NamingEnumeration<SearchResult> answer = ctxMap.get( configMap.get( GROUP ) ).search( configMap.get( SEARCHBASE ), searchFilter,
searchCtls );
SearchResult sr = null;
// Loop through the search results
while ( answer.hasMoreElements() ) {
sr = (SearchResult) answer.next();
}
if ( sr == null ) {
return group;
}
// Create an attribute for memberOf
javax.naming.directory.Attribute member = sr.getAttributes().get( MEMBER_FIELD );
// Enumeration of all elements in memberOf
NamingEnumeration<?> ne = member.getAll();
// Loop though the enumeration, cut unwanted characters and add all
// elements to User List
while ( ne.hasMoreElements() ) {
...
}
}
因此,我想将组的专有名称作为参数而不是组的名称传递给函数,并对此进行搜索或直接获取属性。 这可能吗?
PS:此代码用于获取特定组的成员。
谢谢
如果您有DN,则无需搜索。 只需使用lookup()进行查找。
在EJP的帮助下,我找到了一种无需执行搜索即可从DistinguishedName获取属性的方法:
Attributes attrs;
attrs = ctx.getAttributes( dn );
Attribute attr= attrs.get( "the attribute you need" );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.