首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

封裝 JNDI 操作 LDAP 服務的工具類(一):Env 連線屬性類設計

     編輯:Java 相關知識

設計目標

使用者只需熟悉 List、Map 等標準集合結構,即可完成 LDAP 增刪改查,屏蔽 JNDI 底層 API 複雜度。

三層架構職責劃分

  1. Env:封裝 LDAP 連線參數(URL、認證、SSL、逾時等)。
  2. LdapConnectionFactory:單例工廠,管理連線池與 DirContext 建立/關閉。
  3. LdapOperUtils:靜態工具類,提供高層業務操作(增刪改查 Context/屬性、搜尋、認證)。

Env 類別完整實作

package com.common.ldapconnection;

import org.apache.log4j.Logger;

public class Env {
    private static final Logger log = Logger.getLogger(Env.class.getName());

    // 固定參數
    public String factory;           // JNDI 提供者工廠類,如 com.sun.jndi.ldap.LdapCtxFactory
    public String url;               // LDAP 伺服器 URL,如 ldap://10.110.179.175:389
    public String adminUID;          // 綁定 DN,如 cn=admin,dc=example,dc=com
    public String adminPWD;          // 密碼
    public String sslTrustStore;     // SSL 信任憑證庫路徑
    public String securityProtocol;  // "ssl" 或 null
    public String timeOut;           // 連線逾時毫秒數(字串形式)

    // 多重建構子支援不同場景
    public Env() {}

    public Env(String factory, String url, String adminUID, String adminPWD) {
        this.factory = factory;
        this.url = url;
        this.adminUID = adminUID;
        this.adminPWD = adminPWD;
    }

    public Env(String factory, String url, String adminUID, String adminPWD,
               String sslTrustStore, String securityProtocol) {
        this(factory, url, adminUID, adminPWD);
        this.sslTrustStore = sslTrustStore;
        this.securityProtocol = securityProtocol;
    }

    public Env(String factory, String url, String adminUID, String adminPWD,
               String timeOut, String sslTrustStore, String securityProtocol) {
        this(factory, url, adminUID, adminPWD, sslTrustStore, securityProtocol);
        this.timeOut = timeOut;
    }
}

關鍵設計細節

  • 欄位公開:為簡化使用,採用公有欄位而非 Getter/Setter,配合多建構子滿足不同初始化需求。
  • SSL 參數分離:sslTrustStore 與 securityProtocol 獨立,支援單向/雙向 SSL 彈性配置。
  • 逾時字串化:timeOut 以字串儲存,避免基本型別無法表達「未設定」狀態,工廠層轉換為長整數。
  • Log4j 整合:靜態 Logger 記錄初始化與錯誤資訊,便於生產環境追蹤。

使用範例

Env env = new Env();
env.factory = "com.sun.jndi.ldap.LdapCtxFactory";
env.url = "ldap://ldap.example.com:389";
env.adminUID = "cn=admin,dc=example,dc=com";
env.adminPWD = "secret";
// 啟用 SSL
env.securityProtocol = "ssl";
env.sslTrustStore = "/path/to/truststore.jks";

下一篇將詳細介紹 LdapConnectionFactory 連線池管理與 DirContext 生命週期控制。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved