java ldap查询同名用户 代码
时间: 2023-11-25 14:06:58 浏览: 106
以下是Java中使用LDAP查询同名用户的代码示例:
```java
import javax.naming.*;
import javax.naming.directory.*;
public class LDAPSearch {
public static void main(String[] args) {
String searchFilter = "(&(objectClass=user)(cn=John Smith))"; // LDAP搜索过滤器
String[] requiredAttributes = {"cn", "mail", "telephoneNumber"}; // 查询返回的属性
// LDAP连接参数
String ldapUrl = "ldap://ldap.example.com:389";
String ldapBaseDn = "dc=example,dc=com";
String ldapUsername = "cn=admin,dc=example,dc=com";
String ldapPassword = "adminpassword";
// 创建LDAP连接
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUrl);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
env.put(Context.SECURITY_CREDENTIALS, ldapPassword);
try {
// 连接LDAP服务器
DirContext ctx = new InitialDirContext(env);
// 执行搜索
NamingEnumeration<SearchResult> results = ctx.search(ldapBaseDn, searchFilter, getSimpleSearchControls(requiredAttributes));
// 处理搜索结果
while (results.hasMore()) {
SearchResult result = (SearchResult) results.next();
Attributes attrs = result.getAttributes();
Attribute attr = attrs.get("cn");
String cn = (String) attr.get();
attr = attrs.get("mail");
String mail = (String) attr.get();
attr = attrs.get("telephoneNumber");
String telephoneNumber = (String) attr.get();
System.out.println("cn: " + cn + ", mail: " + mail + ", telephoneNumber: " + telephoneNumber);
}
// 关闭LDAP连接
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
// 获取LDAP搜索控制器
private static SearchControls getSimpleSearchControls(String[] attributes) {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setTimeLimit(30000);
controls.setReturningAttributes(attributes);
return controls;
}
}
```
请注意,你需要替换代码中的LDAP连接参数和搜索过滤器,以适应你的LDAP服务器和搜索需求。
阅读全文