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

在 ApacheDS 中存儲 Java 對象(上):序列化、編組與屬性綁定全解析

     編輯:Java 相關知識

Apache Directory Server 存儲 Java 對象完整指南(存儲篇)

ApacheDS 是基於 LDAP 的目錄服務器,通過 JNDI 暴露操作接口。本文通過 3 個遞進示例,詳細演示 Java 對象在 ApacheDS 中的三種存儲形態:標準序列化、帶屬性綁定、編組對象。

基礎環境與 JNDI 屬性配置

ApacheDS.properties(外部化配置,支援多目錄服務切換):

java.naming.factory.initial=com.sun.jndi.ldap.LdapCtxFactory
java.naming.provider.url=ldap://localhost:389/ou=system
java.naming.security.authentication=simple
java.naming.security.principal=uid=admin,ou=system

代碼中載入屬性並設置憑證:

Properties props = new Properties();
props.load(new FileInputStream("ApacheDS.properties"));
props.setProperty("java.naming.security.credentials", "secret");
DirContext ctx = new InitialDirContext(props);

DirContext 接口:繼承 Context,增加屬性操作能力,是目錄服務核心操作句柄。

應用 1:標準序列化存儲 (StoreAlicePreferences)

領域類需實現 Serializable 並定義 serialVersionUID(使用 serialver 工具生成):

public class MessagingPreferences extends Preferences implements Serializable {
    static final long serialVersionUID = -1240113639782150930L;
    // 業務字段與方法
}

存儲代碼:

MessagingPreferences prefs = new MessagingPreferences();
// 綁定上下文:cn=preferences,uid=alice,ou=users,ou=system
// 其中 uid=alice,ou=users,ou=system 為用戶 Alice 的現有 DN
ctx.bind("cn=preferences,uid=alice,ou=users", prefs);

底層機制:兩參數 bind() 會自動生成三個屬性:

  • javaClassName:完整類名
  • javaClassNames:類名數組(含父類/接口)
  • javaSerializedData:序列化二進制數據

對象類為 javaContainer。

應用 2:帶自定義屬性存儲 (StoreBobPreferences)

使用三參數 bind(String name, Object obj, Attributes attrs),同時創建用戶條目與偏好對象:

// 構建屬性集合
Attribute objclass = new BasicAttribute("objectClass");
objclass.add("person");  // 用戶條目標記為 person
Attributes attrs = new BasicAttributes(true);
attrs.put(objclass);

// 綁定上下文為用戶 DN:uid=Bob,ou=users
ctx.bind("uid=Bob,ou=users", preferences, attrs);

一步完成:創建用戶條目 (objectClass=person) 並存儲偏好對象作為子條目。

應用 3:編組對象存儲 (StoreAlicePreferencesInMarshalledForm)

使用 java.rmi.MarshalledObject 封裝序列化數據,適用於 RMI 遠程傳輸場景:

MessagingPreferences prefs = new MessagingPreferences();
MarshalledObject mObj = new MarshalledObject(prefs); // 內部完成序列化
ctx.bind("cn=marshalledPreferences,uid=alice,ou=users", mObj);

存儲後對象類為 javaMarshalledObject,內部持有序列化字節流。

關鍵技術點總結

存儲方式API對象類適用場景
標準序列化bind(name, obj)javaContainer通用本地存儲
帶屬性綁定bind(name, obj, attrs)javaContainer + 自定義同時創建父條目與對象
編組對象bind(name, MarshalledObject)javaMarshalledObjectRMI/遠程傳輸兼容

驗證工具:JXplorer

啟動 JXplorer 連接 ApacheDS,展開 ou=users → uid=alice 可直觀查看子條目結構與屬性值。

下篇預告

下篇將講解:基礎搜索、CN 模糊匹配、反序列化獲取對象、編組對象解編、更新操作,以及統一封裝類 LDAP4JavaObjects 的完整實現。

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