您的位置:首页 > 其它

jndi快速上手

2007-04-20 15:20 141 查看
新看到的一个对jndi初学比较好的例子

package jndi;

import javax.naming.*;
import java.util.Hashtable;
class JNDI {
static Context ctx = null;
public JNDI()
{ }
//将对象object绑定到WebLogic Server的名字服务中
public static void bind(String name, String object) {
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
try {
ctx = new InitialContext(ht);

ctx.rebind(name, object);
}
catch (NamingException e) {
System.out.println(e);
}
finally {
try {
ctx.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
//通过JNDI查询指定的对象
public static Object lookUp(String name) {
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
try {
ctx = new InitialContext(ht);
Object object = ctx.lookup(name);
return object;
}
catch (NamingException e) {
System.out.println(e);
}
finally {
try {
ctx.close();
}
catch (Exception e) {
System.out.println(e);
}
}
return null;
}
public static void main(String args[]) {
String arg = args[0];
if(arg.equals("bind")) {
System.out.println("bind begin...");
String bookName = "WebLogic introduction";
bind("bookname", bookName);
System.out.println("bind end");
}
if(arg.equals("lookup")) {
System.out.println("lookup begin...");
String bookName;
bookName = (String)lookUp("bookname");
System.out.println("bookname is: "+bookName);
System.out.println("lookup end");
}
}
}

要注意的是,如果在运行时出现如下错误(BEA weblogic 8)
javax.naming.NoInitialContextException: Cannot instantiate class: weblogic.jndi.WLInitialContextFactory [Root exception is java.lang.ClassNotFoundException: weblogic.jndi.WLInitialContextFactory]” 为什么编译没问题了,却还是出错呢,这是网络上问得最多的问题。这是缺少"\bea\weblogic81\server\lib\wlclient.jar"文件所致。 在buildpath里加入这个包后再运行。

如果还是出错,显示“Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/corba/se/connection/ORBSocketFactory” 还是缺少包,这时如果你只安装有jre1.5.*,那是没有ORBSocketFactory这个类文件的。还是找个jre1.4.*吧,这个类在“jre/lib/rt.jar”包中。据说这个问题在weblogic9中已解决
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: