---
title: "用JAVA实现LDAP的访问（三）"
author: "superallen"
date: "2007-02-04T10:27:52Z"
tags: []
slug: "java-ldap"
draft: false
lastmod: "2007-02-04T10:27:52Z"
id: 52088
url: "https://junewolf.iteye.com/blog/52088"
---

虽然LDAP主要是用来进行读操作的，但不可避免的，我们也要向其中添加一些新的数据。用JLDAP向LDAP服务器添加数据的操作也是非常简单的。

   为什么说非常简单呢，因为大体上也就是分三步。第一步，连接LDAP服务器。第二步，建立一个要添加的新的实体LDAPEntry，并添加相应的属性。第三步，通过add方法向LDAP中添加实体。

   首先说连接服务器。还是非常简单的三步:

java 代码

1. LDAPConnection con = new LDAPConnection();
2. con.connect("hostname",hostport);
3. con.bind("version","DN","password");

连接后，可以建实体了，也就相当与为数据库添加一条新的记录。这里用到了几个类：LDAPEntry、LDAPAttribute和LDAPAttributeSet。首先建立一个LDAPAttributeSet,然后建立各种的LDAPAttribute，把他们add到LDAPAttributeSet中。然后建立一个LDAPEntry。其构造函数有两个参数，一个是这个LDAPEntry的DN，一个是他的属性集合，也就是LDAPAttributeSet。

   最后，调用LDAPConnection实例化对象的add方法，把实体添加到服务器中。然后别忘了断开连接喔。整体的示例代码如下：

java 代码

01. LDAPAttributeSet attributeSet = new LDAPAttributeSet();
02. attributeSet.add(new LDAPAttribute("objectclass", new String(
03. "inetOrgPerson")));
04. attributeSet.add(new LDAPAttribute("cn", new String\[] { "李",
05. "Jim Smith", "Jimmy Smith" }));
06. attributeSet.add(new LDAPAttribute("givenname", new String\[] { "测试",
07. "Jim", "Jimmy" }));
08. attributeSet.add(new LDAPAttribute("sn", new String("Smith")));
09. attributeSet.add(new LDAPAttribute("telephonenumber", new String(
10. "1 801 555 1212")));
11. attributeSet.add(new LDAPAttribute("mail",
12. new String("JSmith@Acme.com")));
13. attributeSet.add(new LDAPAttribute("userpassword", new String(
14. "newpassword")));
15. LDAPEntry entry = new LDAPEntry("cn=李,cn=Lizl,dc=excel,dc=com,dc=cn",
16. attributeSet);
17. LDAPConnection con = new LDAPConnection();
18. con.connect("6.1.19.154", 389);
19. con.bind(LDAPConnection.LDAP\_V3, "cn=XXX", "XXXXXX");
20. con.add(entry);
21. System.out.println("成功的添加了一条记录！");
22. con.disconnect();