一段操作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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值