javax.naming.NoInitialContextException:需要在environment或sys中指定类名

时间:2012-12-01 19:30:58

标签: java ldap

运行Java程序时出现此错误。我想要做的是能够使用Java代码创建LDAP用户。我的目标是能够添加,删除,设置密码并在现有组中添加用户。

更好的是还有一个输入框

由于

import javax.naming.directory.DirContext;

import javax.naming.directory.InitialDirContext;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.NamingException;
import java.util.Hashtable;
import java.util.Properties;



public class LdapExampleAdd {


private static LdapContext ctx;

public static void main(String[] args) 
{

//Identify service provider to use

Hashtable env = new Hashtable();
Properties prop = new Properties();  
prop.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");  
prop.put("java.naming.provider.url", "ldap://ldapserverip:389");  
prop.put("java.naming.security.principal", "cn=Administrator,cn=Users,dc=domain,dc=local");  
prop.put("java.naming.security.credentials", "password"); 

try {  
    setCtx(new InitialLdapContext(prop, null));  
    System.out.println("Connected"); 

  }  
  catch (NamingException ex) { 
    System.err.println("Not connected");     
    System.exit(0);
  }  

try 
{ 
// Create the initial directory context
InitialDirContext initialContext = new InitialDirContext(env);



DirContext dCtx = (DirContext)initialContext;

Attributes matchAttrs = new BasicAttributes(true);
matchAttrs.put(new BasicAttribute("uid", "defaultuser"));
matchAttrs.put(new BasicAttribute("cn", "defaultuser")); 
matchAttrs.put(new BasicAttribute("givenname", "defaultuser")); 
matchAttrs.put(new BasicAttribute("sn", "defaultuser")); 
matchAttrs.put(new BasicAttribute("userpassword", "password")); 
matchAttrs.put(new BasicAttribute("objectclass", "top")); 
matchAttrs.put(new BasicAttribute("objectclass", "person")); 
matchAttrs.put(new BasicAttribute("objectclass", "organizationalPerson")); 
matchAttrs.put(new BasicAttribute("objectclass","inetorgperson")); 
String name="uid=defaultuser";

InitialDirContext iniDirContext = (InitialDirContext)dCtx;
iniDirContext.bind(name,dCtx,matchAttrs);

iniDirContext.close();
dCtx.close(); 
} 
catch (NamingException ne) 
{
System.err.println(ne);
}
catch(Exception e)
{
System.err.println(e);
}
}

public static LdapContext getCtx() {
    return ctx;
}

public static void setCtx(LdapContext ctx) {
    LdapExampleAdd.ctx = ctx;
}
}

谁将成为真正的专家

1 个答案:

答案 0 :(得分:0)

您创建了InitialLdapContext,但从不使用它。您创建了HashTable,但从未填充它。