问题说明了一切。当我打印属性时,它是:
cn: WF-008-DAM-PS
代码段是:
private void searchGroup() throws NamingException {
NamingEnumeration<SearchResult> searchResults = getLdapDirContext().search(groupDN, "(objectclass=groupOfUniqueNames)", getSearchControls());
String searchGroupCn = getCNForBrand(m_binder.getLocal("brandId"), m_binder.getLocal("brandName"));
Log.info(searchGroupCn);
while (searchResults.hasMore()) {
SearchResult searchResult = searchResults.next();
Attributes attributes = searchResult.getAttributes();
Attribute groupCn = attributes.get("cn");
if(groupCn != null) {
Log.info(groupCn.toString());
}
}
}
我怎样才能获得WF-008-DAM-PS
的值,即没有关键部分?
问候。
答案 0 :(得分:6)
解决方案是:
Attribute groupCn = attributes.get("cn");
String value = groupCn.get();
答案 1 :(得分:5)
调用getValue()
方法或getValue(int)
方法。
答案 2 :(得分:2)
常规强>
让我们说我们有:
Attributes attributes;
Attribute a = attributes.get("something");
if(a.size() == 1)
a.get()
或a.get(0)
来获取唯一值 if(a.size() > 1)
遍历所有值:
for ( int i = 0 ; i < a.size() ; i++ ) {
Object currentVal = a.get(i);
// do something with currentVal
}
如果你在这里使用a.get()
,它将只返回第一个值,因为它的内部实现(在BasicAttribute
中)如下所示:
public Object get() throws NamingException {
if (values.size() == 0) {
throw new NoSuchElementException("Attribute " + getID() + " has no value");
} else {
return values.elementAt(0);
}
}
两种方法(get(int)
和get()
)都会抛出NamingException
。
实际示例
(当Attribute
实例有多个值时)
LdapContext ctx = new InitialLdapContext(env, null);
Attributes attributes = ctx.getAttributes("", new String[] { "supportedSASLMechanisms" });
System.out.println(attributes); // {supportedsaslmechanisms=supportedSASLMechanisms: GSSAPI, EXTERNAL, DIGEST-MD5}
Attribute a = atts.get("supportedsaslmechanisms");
System.out.println(a); // supportedSASLMechanisms: GSSAPI, EXTERNAL, DIGEST-MD5
System.out.println(a.get()); // GSSAPI
for (int i = 0; i < a.size(); i++) {
System.out.print(a.get(i) + " "); // GSSAPI EXTERNAL DIGEST-MD5
}
答案 3 :(得分:0)
这有效:(在获取属性值之前检查属性是否存在)
Attributes attributes = searchResult.getAttributes();
Attribute mail = attributes.get("mail");
if (mail != null)
{
System.out.println(" Mail-id value from LDAP :"+mail.get());
}