我有一个简单的 LDAP 客户端,它使用过时的 Hashtable
集合。
class SAuth {
public static void main(String[] args) {
Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");
// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");
try {
DirContext ctx = new InitialDirContext(env);
System.out.println(" i guess the connection is sucessfull :)");
// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
是否有任何现代集合可以代替 Hashtable 而无需破坏代码?
更新:
class tSAuth {
public static void main(String[] args) {
Map<String, String> env = new HashMap<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://xx.xx.xx.xx:yyyy/");
// Authenticate as S. User and password "mysecret"
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=orcladmin");
env.put(Context.SECURITY_CREDENTIALS, "password");
try {
DirContext ctx = new InitialDirContext((Hashtable<?, ?>) env);
System.out.println(" i guess the connection is sucessfull :)");
// Do something useful with ctx
// Close the context when we're done
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
最佳答案
使用HashMap
而不是HashTable
像这样:
Map env = new HashMap();
我不确定 Context.*
的确切类型,但是,如果是 String
,那么你可以这样编写代码:
Map<String, String> env = new HashMap<String, String>();
编辑:
InitialDirContext
构造函数的参数类型为Hashtable<?,?>
。所以你应该Hashtable
在这种情况下。也许你可以这样编码:
Hashtable<String, String> env = new Hashtable<String, String>();
关于java - 替换过时的 `Hashtable` 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21008492/