- public class LdapService {
- private Logger logger = Logger.getLogger(LdapService.class);
- private Properties env;
- private DirContext ctx;
- public void setEnv(Properties env) {
- this.env = env;
- }
- public NamingEnumeration search(String dn, String filter,
- String[] returningAttr) throws NamingException {
- try {
- ctx = new InitialDirContext(env);
- SearchControls constraints = new SearchControls();
- constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
- constraints.setReturningAttributes(returningAttr);
- return ctx.search(dn, filter, constraints);
- } finally {
- if (ctx != null) {
- try {
- ctx.close();
- } catch (Exception ex) {
- logger.error(ex);
- }
- }
- }
- }
- }
下面是測試代碼:
- public class LdapTest extends BaseUnitTest {
- public void testSerach() {
- LdapService ldap = (LdapService) this.applicationContext
- .getBean("ldapService");
- String dn = "ou=people,dc=ibm,dc=com";
- String[] returningAttr = null;
- String filter = "uid=c0001";
- try {
- NamingEnumeration n = ldap.search(dn, filter, returningAttr);
- if (n.hasMoreElements()) {
- SearchResult sr = (SearchResult) n.next();
- printAttributes(sr.getAttributes());
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private void printAttributes(Attributes attributes) throws NamingException {
- String attrType;
- Attribute attr;
- NamingEnumeration ne;
- // Iterate through the attributes..
- for (NamingEnumeration a = attributes.getAll(); a.hasMore();) {
- attr = (Attribute) a.next();
- System.out.print(attr.getID() + ": ");
- ne = attr.getAll();
- while (ne.hasMore()) {
- System.out.print(ne.next());
- }
- System.out.print("\n");
- }
- }
- }