新看到的一個對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中已解決
posted on 2007-05-24 10:40
李大嘴 閱讀(663)
評論(0) 編輯 收藏