一段操作LDAP的java代碼

java 代碼
  1. public class LdapService {   
  2.     private Logger logger = Logger.getLogger(LdapService.class);   
  3.   
  4.     private Properties env;   
  5.   
  6.     private DirContext ctx;   
  7.   
  8.     public void setEnv(Properties env) {   
  9.         this.env = env;   
  10.     }   
  11.   
  12.     public NamingEnumeration search(String dn, String filter,   
  13.             String[] returningAttr) throws NamingException {   
  14.         try {   
  15.             ctx = new InitialDirContext(env);   
  16.             SearchControls constraints = new SearchControls();   
  17.             constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);   
  18.             constraints.setReturningAttributes(returningAttr);   
  19.             return ctx.search(dn, filter, constraints);   
  20.         } finally {   
  21.             if (ctx != null) {   
  22.                 try {   
  23.                     ctx.close();   
  24.                 } catch (Exception ex) {   
  25.                     logger.error(ex);   
  26.                 }   
  27.             }   
  28.         }   
  29.     }   
  30. }  

下面是測試代碼:

java 代碼
  1. public class LdapTest extends BaseUnitTest {   
  2.   
  3.     public void testSerach() {   
  4.         LdapService ldap = (LdapService) this.applicationContext   
  5.                 .getBean("ldapService");   
  6.         String dn = "ou=people,dc=ibm,dc=com";   
  7.         String[] returningAttr = null;   
  8.         String filter = "uid=c0001";   
  9.         try {   
  10.             NamingEnumeration n = ldap.search(dn, filter, returningAttr);   
  11.             if (n.hasMoreElements()) {   
  12.                 SearchResult sr = (SearchResult) n.next();   
  13.                 printAttributes(sr.getAttributes());   
  14.             }   
  15.         } catch (Exception e) {   
  16.             e.printStackTrace();   
  17.         }   
  18.     }   
  19.        
  20.     private void printAttributes(Attributes attributes) throws NamingException {   
  21.         String attrType;   
  22.         Attribute attr;   
  23.         NamingEnumeration ne;   
  24.   
  25.         // Iterate through the attributes..   
  26.         for (NamingEnumeration a = attributes.getAll(); a.hasMore();) {   
  27.             attr = (Attribute) a.next();   
  28.   
  29.             System.out.print(attr.getID() + ": ");   
  30.   
  31.             ne = attr.getAll();   
  32.             while (ne.hasMore()) {   
  33.                 System.out.print(ne.next());   
  34.             }   
  35.   
  36.             System.out.print("\n");   
  37.         }   
  38.     }   
  39. }  
發佈了19 篇原創文章 · 獲贊 0 · 訪問量 3102
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章