虽然LDAP主要是用来进行读操作的,但不可避免的,我们也要向其中添加一些新的数据。用JLDAP向LDAP服务器添加数据的操作也是非常简单的。
为什么说非常简单呢,因为大体上也就是分三步。第一步,连接LDAP服务器。第二步,建立一个要添加的新的实体LDAPEntry,并添加相应的属性。第三步,通过add方法向LDAP中添加实体。
首先说连接服务器。还是非常简单的三步:
java 代码
- LDAPConnection con = new LDAPConnection();
- con.connect("hostname",hostport);
- con.bind("version","DN","password");
连接后,可以建实体了,也就相当与为数据库添加一条新的记录。这里用到了几个类:LDAPEntry、LDAPAttribute和LDAPAttributeSet。首先建立一个LDAPAttributeSet,然后建立各种的LDAPAttribute,把他们add到LDAPAttributeSet中。然后建立一个LDAPEntry。其构造函数有两个参数,一个是这个LDAPEntry的DN,一个是他的属性集合,也就是LDAPAttributeSet。
最后,调用LDAPConnection实例化对象的add方法,把实体添加到服务器中。然后别忘了断开连接喔。整体的示例代码如下:
java 代码
- LDAPAttributeSet attributeSet = new LDAPAttributeSet();
- attributeSet.add(new LDAPAttribute("objectclass", new String(
- "inetOrgPerson")));
- attributeSet.add(new LDAPAttribute("cn", new String[] { "李",
- "Jim Smith", "Jimmy Smith" }));
- attributeSet.add(new LDAPAttribute("givenname", new String[] { "测试",
- "Jim", "Jimmy" }));
- attributeSet.add(new LDAPAttribute("sn", new String("Smith")));
- attributeSet.add(new LDAPAttribute("telephonenumber", new String(
- "1 801 555 1212")));
- attributeSet.add(new LDAPAttribute("mail",
- new String("JSmith@Acme.com")));
- attributeSet.add(new LDAPAttribute("userpassword", new String(
- "newpassword")));
- LDAPEntry entry = new LDAPEntry("cn=李,cn=Lizl,dc=excel,dc=com,dc=cn",
- attributeSet);
- LDAPConnection con = new LDAPConnection();
- con.connect("6.1.19.154", 389);
- con.bind(LDAPConnection.LDAP_V3, "cn=XXX", "XXXXXX");
- con.add(entry);
- System.out.println("成功的添加了一条记录!");
- con.disconnect();