8

这个问题说明了一切。当我打印一个属性时,它是:

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,即没有关键部分?问候。

4

4 回答 4

8

解决方案是:

Attribute groupCn = attributes.get("cn");
String value = groupCn.get();
于 2012-12-24T11:49:00.533 回答
5

调用getValue()方法或getValue(int)方法。

于 2012-08-28T15:51:11.210 回答
2

一般的

假设我们有:

Attributes attributes;
Attribute a = attributes.get("something");
  • if(a.size() == 1)
    • 那么您可以使用a.get()ora.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()此处使用,它将仅返回第一个值,因为它的内部实现 (in 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
}
于 2015-12-17T14:49:57.187 回答
0

这有效:(在获取属性值之前检查属性是否存在)

            Attributes attributes = searchResult.getAttributes();
            Attribute mail = attributes.get("mail");
            if (mail != null)
               {
                   System.out.println(" Mail-id value from LDAP :"+mail.get());
               }
于 2020-02-27T11:18:07.330 回答