在employeeID属性中查找具有特定值的用户

时间:2012-04-03 13:15:27

标签: java active-directory ldap

我正在尝试通过搜索employeeID属性(每个员工都是唯一的)来查找用户名的CN。我已经让它返回一个包含所有属性的字符串,但我希望它只返回用户的CN(例如:'John Doe'或'cn = John Doe';两者都很好)

public void getEmployeeId(String id) {
        // TODO stuff
        String groupName = "ou=Accounts,DC=PORTAL,DC=COMPANY,DC=BE";

        try {
            System.out.println("Creating initial directory context...");
            LdapContext ctx = new InitialLdapContext(env, null);

            // Create default search controls
            SearchControls ctls = new SearchControls();


            // Search for user with 'id' as value for employeeID attribute
            String filter = "(&(employeeID=" +id + "))";

            // Search for objects using filter
            NamingEnumeration answer = ctx.search(groupName, filter, ctls);

            // Print the answer
            // Search.printSearchEnumeration(answer);

            System.out.println("-----------------");
            System.out.println(answer.next());
            System.out.println("-----------------");

            // Close the context when we're done
            ctx.close();
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

注意:我知道您可以从字符串中剪切部分,但我希望它只返回我需要的值。

2 个答案:

答案 0 :(得分:1)

搜索请求应包含属性列表。某些API将返回匹配条目的所有属性。在要返回的属性列表中指定cn,并准备好处理多值cn属性。

另见

答案 1 :(得分:0)

例如:

DirContext ctx = new InitialDirContext(env);
            /***/
            NamingEnumeration<?> namingEnum = ctx.search(
                    "dc=stackoverflow,dc=com, "employeeID=" +id,
                    ctls);
            while (namingEnum.hasMoreElements()) {
                SearchResult result = (SearchResult) namingEnum.next();
                Attributes attrs = result.getAttributes();
                System.out.println(attrs.get("cn"));
                System.out.println(attrs.get("name"));
                System.out.println(attrs.get("userPrincipalName"));
            }
            /***/

结果:

CN:Andres Montejo

NAME:Andres Montejo

userPrincipalName:andresmontejo@stackoverflow.com