ITeye博客

一段操作LDAP的java代码

absolute · 2007-08-13 15:51 · Java记事本 · Markdown

java 代码

  1. public class LdapService {
  2. private Logger logger = Logger.getLogger(LdapService.class);
  3. private Properties env;
  4. private DirContext ctx;
  5. public void setEnv(Properties env) {
  6. this.env = env;
  7. }
  8. public NamingEnumeration search(String dn, String filter,
  9. 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 代码

  1. public class LdapTest extends BaseUnitTest {
  2. public void testSerach() {
  3. LdapService ldap = (LdapService) this.applicationContext
  4. .getBean("ldapService");
  5. String dn = "ou=people,dc=ibm,dc=com";
  6. String[] returningAttr = null;
  7. String filter = "uid=c0001";
  8. try {
  9. 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. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。