大家好,欢迎来到IT知识分享网。
1、创建新项目TestOpenLdap;
2、新建测试类TestOpenLdap.java;
3、编写测试程序。代码见附件。package com.suresec.openldap;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class TestOpenLDAP {
final private static String account = “Manager”;
final private static String password = “python”;
final private static String root = “dc=python,dc=com”;
public TestOpenLDAP()
{
//init();
}
public DirContext getCtx()
{
DirContext ctx = null;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, “com.sun.jndi.ldap.LdapCtxFactory”);
env.put(Context.PROVIDER_URL, “ldap://192.168.1.45:389/”);
env.put(Context.SECURITY_AUTHENTICATION, “simple”);
env.put(Context.SECURITY_PRINCIPAL, “cn=”+account+”,”+root);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
ctx = new InitialDirContext(env);
System.out.println(“认证成功”);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(“认证失败:”+e.toString());
return null;
}
return ctx;
}
public void add(DirContext ctx)
{
try {
String newUserName = “hi”;
BasicAttributes attrs = new BasicAttributes();
BasicAttribute objclassSet = new BasicAttribute(“objectClass”);
objclassSet.add(“top”);
objclassSet.add(“organizationalUnit”);
attrs.put(objclassSet);
attrs.put(“ou”,newUserName);
ctx.createSubcontext(“ou=” + newUserName+”,”+root, attrs);
} catch (NamingException e) {
// TODO Auto-generated catch block
System.out.println(“Exception in add():”+e);
}
}
public void delete(DirContext ctx)
{
try {
ctx.destroySubcontext(“ou=hi,dc=python,dc=com”);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void close(DirContext ctx)
{
try {
if(ctx != null)
{
ctx.close();
}
} catch (NamingException e) {
// TODO Auto-generated catch block
System.out.println(“NamingException in close():”+e);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TestOpenLDAP testOpenLdap = new TestOpenLDAP();
DirContext ctx = testOpenLdap.getCtx();
testOpenLdap.add(ctx);
testOpenLdap.close(ctx);
}
}
4、运行测试程序,结果如下所示:
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/22058.html