使用使用者名和密碼來進行ldap驗證,需要使用cn(使用者名)、ou(組織)和dc(多個dc可以表示域名)等關鍵字。
import java.util.hashtable;
import javax.naming.context;
import javax.naming.namingenumeration;
import javax.naming.namingexception;
import javax.naming.directory.attribute;
import javax.naming.directory.attributes;
import javax.naming.ldap.initialldapcontext;
import javax.naming.ldap.ldapcontext;
/**
* this is a tool class for connecting to ldap.
* @author jason
*/
public class copyofconnldap {
//store the connected information
private hashtable env = null;
//ldap context
private ldapcontext ctx = null;
//set some connected information
private string initial_context_factory = "com.sun.jndi.ldap.ldapctxfactory";
private string provider_url = "ldap://10.27.132.17:389";
private string security_authentication = "simple";
private string security_principal = "cn=視訊會議組,ou=機關服務部,ou=資訊技術服務中心,ou=集團公司機關,dc=cnpc,dc=com,dc=cn";
private string security_credentials = "sphy321";
public static void main(string[] args) {
copyofconnldap con=new copyofconnldap();
try {
ldapcontext ctxs = con.connectldap();
attributes attrs = ctxs.getattributes("cn=itest,ou=資訊技術服務中心,ou=集團公司機關,dc=cnpc,dc=com,dc=cn");
for (namingenumeration ae = attrs.getall(); ae.hasmore();) {
attribute attr = (attribute) ae.next();
system.out.println("attribute: " + attr.getid());
for (namingenumeration e = attr.getall(); e.hasmore(); system.out.println("value: " + e.next()));
}
} catch (namingexception e) {
// todo auto-generated catch block
e.printstacktrace();
/** creates a new instance of connldap */
public copyofconnldap() {
env = new hashtable();
}
/**
* connect to ldap and initialize the ldap context.
* @throws javax.naming.namingexception if connect fail,throw this exception.
*/
public ldapcontext connectldap()throws namingexception{
//set the initializing information of the context
env.put(context.initial_context_factory, initial_context_factory);
//set the url of ldap server
env.put(context.provider_url, provider_url);
//set the authentication mode
env.put(context.security_authentication, security_authentication);
//set user of ad
env.put(context.security_principal, security_principal);
//set password of user
env.put(context.security_credentials, security_credentials);
//initialize the ldap context
ctx = new initialldapcontext(env,null);
return ctx;
public void closecontext() throws namingexception{
ctx.close();
* return the ldap context.
* @return return the ldap context.
public ldapcontext getcontext(){
return this.ctx;
}