2014-01-31 32 views
2

对不起,我在JNDI noob,我尝试连接到我的LDAPS与JNDI简单的身份验证,但我不知道我怎么可以在连接后获取数据所以我的代码是:我如何从JNDI获取数据ldap

public static void main(String[] args) { 

// Set up environment for creating initial context 
Hashtable<String, String> env = new Hashtable<String, String>(11); 
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory"); 
env.put(Context.PROVIDER_URL, "ldaps://myadress:636"); 

// Authenticate as S. User and password "mysecret" 
env.put(Context.SECURITY_AUTHENTICATION, "simple"); 
env.put(Context.SECURITY_PRINCIPAL, "my BASE DN"); 
env.put(Context.SECURITY_CREDENTIALS, "mypass"); 


try { 
    // Create initial context 
    DirContext ctx = new InitialDirContext(env); 
    // Close the context when we're done 
    ctx.close(); 
} catch (NamingException e) { 
    e.printStackTrace(); 
} 
} 

DirContext ctx = new InitialDirContext(env);` 

我希望得到我的树和一些数据,但如何..例如我的树是:

-ou=people,dc=info,dc=uni,dc=com 

---ou=students 
-----uid=5tey37 

我怎么能获取uid的数据?

对不起,我是个菜鸟,和对不起我的英语

回答

2

您调用的context具有特定参数的搜索。在你的例子中,你可以根据具体的uid做一个上下文搜索,并获得对应于一个目录对象的所有可用的不同attributes

下面一个例子,你可能要调整搜索和属性具体到目录

// Create initial context 
DirContext ctx = new InitialDirContext(env); 

String searchBase = "ou=people"; 
SearchControls searchCtls = new SearchControls(); 

// Specify the search scope 
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); 

String uid = "5tey37"; 
String searchFilter = " (uid=" + uid + ") "; 

NamingEnumeration<?> namingEnum = ctx.search(searchBase,searchFilter, searchCtls); 
while (namingEnum.hasMore()) { 
    SearchResult result = (SearchResult) namingEnum.next(); 
    // GET STUFF 
    Attributes attrs = result.getAttributes(); 
    System.out.println(attrs.get("uid")); 
... 

} 
namingEnum.close(); 
// Close the context when we're done 
ctx.close(); 
+0

伟大的!非常感谢! – FelasDroid

+0

@FelasDroid不客气 – PopoFibo