使用JNDI将任何数据(条目)添加到LDAP服务器

时间:2018-11-18 23:59:31

标签: java ldap jndi

我想将任何数据(条目)添加到LDAP服务器。我尝试了以下代码。一种方法有效,而另一种方法无效。

有什么建议或解决方案吗?
我将附加LDAP服务器的屏幕截图:

enter image description here

public static  DirContext connectJndi() throws NamingException {
    //method to connect to LDAP server using JNDI 
    Hashtable<String, String> env = new Hashtable<String, String>(); 
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://192.168.0.60:389");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "******");
    env.put(Context.SECURITY_CREDENTIALS, "*******");
    //DirContext ctx = new InitialDirContext(env); 
    LdapContext ctx = new InitialLdapContext(env,null);
    return ctx;     // connection method works. 
} 

//this method doesn't work. 
public static void insertJndi( ) throws NamingException  {
    LdapContext ctx = (LdapContext) connectJndi();    //connecting to the server

    LDAPAttributeSet attrs = new LDAPAttributeSet();
    String objectclass_values[] = { "top", "person", "op","11" };
    LDAPAttribute attr = new LDAPAttribute("objectclass",objectclass_values);
    //Attribute objectClass = new BasicAttribute("objectClass");
    attrs.add(attr);
    LDAPEntry myEntry = new LDAPEntry("cn=jin,c=kr", attrs);
     ctx.add(myEntry);

1 个答案:

答案 0 :(得分:2)

我改用了其他API,它起作用了。我本来要消除这个问题,但这可能对某些人有帮助,所以我在这里复制代码。如果没有,我将其删除。

public static void insertJndi( ) throws NamingException  {

    DirContext ctx = connectJndi();
    Attributes attributes = new BasicAttributes(); 
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("anything");
    attributes.put(objectClass);
    Attribute a = new BasicAttribute("a");
    Attribute b = new BasicAttribute("b");
    a.add("jin");
    b.add("lee");
    attributes.put(a);
    attributes.put(b);
    ctx.createSubcontext("cn=a002,ou=b,ou=c,ou=d,o=government of Mars,c=Earth", attributes);
    System.out.println("it worked");