You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何打印javax.naming.directory.Attributes中的所有键值对?

如何打印LDAP Attributes中的所有键值对

你可以通过Attributes.getAll()方法获取所有属性的枚举,然后遍历每个属性来打印键和对应的值。以下是修改后的代码:

import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

NamingEnumeration<SearchResult> searchResults = null;
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setTimeLimit(GloriaParams.LDAP_TIMEOUT_LIMIT);
constraints.setReturningAttributes(returningAttributes);

try {
  searchResults = HelperClass.getLdapContext().search(userId, constraints);
  if (searchResults.hasMore()) { // 先检查是否有结果,避免空指针
    Attributes attributes = searchResults.next().getAttributes();
    // 获取所有属性的枚举
    NamingEnumeration<? extends Attribute> attrEnum = attributes.getAll();
    while (attrEnum.hasMore()) {
      Attribute attr = attrEnum.next();
      String key = attr.getID();
      // 获取属性值,处理多值情况
      NamingEnumeration<?> values = attr.getAll();
      StringBuilder valueStr = new StringBuilder();
      while (values.hasMore()) {
        if (valueStr.length() > 0) {
          valueStr.append(", ");
        }
        valueStr.append(values.next().toString());
      }
      LOG.info("{}: {}", key, valueStr.toString());
    }
  }
} catch (NamingException e) { // 捕获具体异常,替代泛型Exception
  LOG.error("LDAP查询异常", e);
} finally {
  // 关闭枚举,避免资源泄漏
  if (searchResults != null) {
    try {
      searchResults.close();
    } catch (NamingException e) {
      LOG.warn("关闭搜索结果枚举失败", e);
    }
  }
}

关键点说明:

  • 使用attributes.getAll()获取所有属性的NamingEnumeration,无需预先知道键名。
  • 每个Attribute对象通过getID()获取键名,getAll()获取该键对应的所有值(兼容多值属性场景)。
  • 增加结果存在性检查,避免searchResults.next()抛出NoSuchElementException。
  • 替换泛型Exception捕获为更具体的NamingException,并使用日志记录异常而非printStackTrace()。
  • 添加finally块关闭枚举,防止资源泄漏。

内容的提问来源于stack exchange,提问作者Đỗ Văn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:05:25