---
title: "一段操作LDAP的java代码"
author: "absolute"
date: "2007-08-13T15:51:19Z"
tags: []
slug: "ldap-java"
draft: false
lastmod: "2007-08-13T15:51:19Z"
id: 111749
url: "https://absolute.iteye.com/blog/111749"
---

java 代码

01. public class LdapService {
02. private Logger logger = Logger.getLogger(LdapService.class);
03. private Properties env;
04. private DirContext ctx;
05. public void setEnv(Properties env) {
06. this.env = env;
07. }
08. public NamingEnumeration search(String dn, String filter,
09. String\[] returningAttr) throws NamingException {
10. try {
11. ctx = new InitialDirContext(env);
12. SearchControls constraints = new SearchControls();
13. constraints.setSearchScope(SearchControls.SUBTREE\_SCOPE);
14. constraints.setReturningAttributes(returningAttr);
15. return ctx.search(dn, filter, constraints);
16. } finally {
17. if (ctx != null) {
18. try {
19. ctx.close();
20. } catch (Exception ex) {
21. logger.error(ex);
22. }
23. }
24. }
25. }
26. }

下面是测试代码：

java 代码

01. public class LdapTest extends BaseUnitTest {
02. public void testSerach() {
03. LdapService ldap = (LdapService) this.applicationContext
04. .getBean("ldapService");
05. String dn = "ou=people,dc=ibm,dc=com";
06. String\[] returningAttr = null;
07. String filter = "uid=c0001";
08. try {
09. NamingEnumeration n = ldap.search(dn, filter, returningAttr);
10. if (n.hasMoreElements()) {
11. SearchResult sr = (SearchResult) n.next();
12. printAttributes(sr.getAttributes());
13. }
14. } catch (Exception e) {
15. e.printStackTrace();
16. }
17. }
18. private void printAttributes(Attributes attributes) throws NamingException {
19. String attrType;
20. Attribute attr;
21. NamingEnumeration ne;
22. // Iterate through the attributes..
23. for (NamingEnumeration a = attributes.getAll(); a.hasMore();) {
24. attr = (Attribute) a.next();
25. System.out.print(attr.getID() + ": ");
26. ne = attr.getAll();
27. while (ne.hasMore()) {
28. System.out.print(ne.next());
29. }
30. System.out.print("\\n");
31. }
32. }
33. }