详细见代码:
/**
* 通过LDAP用户,查找LDAP的中文名称,fullname
*
*/
public String getLDAPUserName(String input){
String fullName = "";
String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";
// 服务器连接
String MY_HOST = "ldap://xx.xx.xx.xxx:389";
// 查询根目录值
String MY_SEARCHBASE = "o=sgcc";
//String MY_FILTER = "(objectclass=*)";
// 过滤条件
String MY_FILTER = "(cn="+input+")";
// 登录用户名
String MGR_DN = "cn=admin,o=services";
// 登录密码
String MGR_PW = "novell";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,INITCTX);
env.put(Context.PROVIDER_URL,MY_HOST);
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,MGR_DN);
env.put(Context.SECURITY_CREDENTIALS,MGR_PW);
DirContext ctx = null ;
try {
ctx = new InitialDirContext(env);
} catch (NamingException e) {
messageManager.reportException("连接LDAP服务器失败"+e.getMessage(),true);
e.printStackTrace();
}
if (ctx == null){
messageManager.reportException("连接LDAP服务器失败",true);
return null;
}else{
messageManager.reportSuccess("连接LDAP服务器成功");
}
try {
SearchControls constrains = new SearchControls();
constrains.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration results = ctx.search(MY_SEARCHBASE,MY_FILTER,constrains);
while(results.hasMoreElements()){
Object obj = results.next();
if(obj instanceof SearchResult){
SearchResult sr = (SearchResult) obj;
String name = sr.getName();
Attributes attrs = sr.getAttributes();
if (attrs.get("fullname") != null){
NamingEnumeration values = ((BasicAttribute)attrs.get("fullname")).getAll();
while (values.hasMore()){
//messageManager.reportSuccess("fullname:"+values.nextElement());
fullName = values.nextElement().toString();
}
}
}
}
} catch (NamingException e1) {
messageManager.reportException("查询信息失败"+e1.getMessage(),true);
e1.printStackTrace();
}
return fullName;
}