我正在尝试返回搜索过滤器中每个人的员工编号
(&(employeeType= Workforce)(objectClass=person))
这是我的代码:
import java.util.Enumeration;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.Attribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import java.util.Hashtable;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class testing2 {
public testing2() {
}
public void doLookup() {
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.put(Context.PROVIDER_URL, "removed for reasons");
properties.put(Context.SECURITY_AUTHENTICATION,"simple");
properties.put(Context.SECURITY_PRINCIPAL,"removed");
properties.put(Context.SECURITY_CREDENTIALS,"secret");
try {
DirContext context = new InitialDirContext(properties);
SearchControls searchCtrls = new SearchControls();
searchCtrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "(&(employeeType= Workforce)(objectClass=person))";
NamingEnumeration values = context.search("o = xyz",filter,searchCtrls);
while (values.hasMoreElements())
{
SearchResult result = (SearchResult) values.next();
Attributes attribs = result.getAttributes();
if (null != attribs)
{
for (NamingEnumeration ae = attribs.getAll(); ae.hasMoreElements();)
{
Attribute atr = (Attribute) ae.next();
String attributeID = atr.getID();
for (Enumeration vals = atr.getAll();
vals.hasMoreElements();
System.out.println(attributeID +": "+ vals.nextElement()));
//System.out.println(attributeID.getAttributes().get("uid"))
}
}
}
context.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
testing2 sample = new testing2();
sample.doLookup();
}
}
问题在于,当我运行这个时,我会获得有关所有用户的所有信息 - 包括名字,姓氏,职位,给定名称,邮政编码,员工编号等属性。我如何仅提取/返回员工编号(对于过滤器中的所有用户)
由于
答案 0 :(得分:0)
@Sampisa的解决方案是正确的:
if (null != attribs) {
Attribute myattrib = attribs.get("employeeNumber");
System.out.println(myattrib); // or myattrib.get(0)
}
而不是
if (null != attribs)
{
for (NamingEnumeration ae = attribs.getAll(); ae.hasMoreElements();)
{
Attribute atr = (Attribute) ae.next();
String attributeID = atr.getID();
for (Enumeration vals = atr.getAll();
vals.hasMoreElements();
System.out.println(attributeID +": "+ vals.nextElement()));
//System.out.println(attributeID.getAttributes().get("uid"))
}
}