我想向 LDAP 服务器添加任何数据(条目)。我尝试了以下代码。一种连接有效的方法,另一种添加不起作用的条目的方法。
有什么建议或解决方案吗?
我附上了我的 LDAP 服务器的屏幕截图:
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);
最佳答案
我尝试了其他 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");
关于java - 使用 JNDI 将任何数据(条目)添加到 LDAP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53366694/