public interface Hello extends EJBObject, Remote {
//定義供遠程調用的業務邏輯方法 public String getHello() throws RemoteException; public String getStr() throws RemoteException; } ③ EJB類的實現 在EJB類中,必須給出在Remote Interface中定義的遠程方法的具體實現。EJB類中還包括一些EJB規范中定義的必須實現的方法,這些方法都有比較統一的實現模版,只需花費精力在具體業務方法的實現上。試驗的代碼如下: package ejb.hello; import javax.ejb.*; import java.util.*; import java.rmi.*; //類的實現 public class HelloBean implements sessionBean { static final boolean verbose = true; PRivate SessionContext ctx; // Implement the methods in the SessionBean // interface public void ejbActivate() { if (verbose) System.out.println("ejbActivate called"); } public void ejbRemove() { if (verbose) System.out.println("ejbRemove called"); } public void ejbPassivate() { if (verbose) System.out.println("ejbPassivate called"); } //Sets the session context. public void setSessionContext(SessionContext ctx) { if (verbose) System.out.println("setSessionContext called"); this.ctx = ctx; } /** * This method corresponds to the create method in * the home interface HelloHome.java. * The parameter sets of the two methods are * identical. When the client calls * HelloHome.create(), the container allocates an * instance of the EJBean and calls ejbCreate(). */ public void ejbCreate () { if (verbose) System.out.println("ejbCreate called"); } //以下業務邏輯的實現 public String getStr() throws RemoteException { return("...My First EJB Test??Lenper_xie...!"); } } ④會話Bean的代碼完成后,編寫客戶端,代碼如下: package ejb.hello; import javax.naming.Context; import javax.naming.InitialContext; import java.util.Hashtable; import javax.ejb.*; import java.rmi.RemoteException;
/** *用weblogic */ public class HelloClient{ public static void main(String args[]){ String url = "t3://localhost:7001"; Context initCtx = null; HelloHome hellohome = null; try{ Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); env.put(Context.PROVIDER_URL, url); initCtx = new InitialContext(env); }catch(Exception e){ System.out.println("Cannot get initial context: " + e.getMessage()); System.exit(1); } try{ hellohome = (HelloHome)initCtx.lookup("HelloHome"); Hello hello = hellohome.create(); String s = hello.getStr(); System.out.println(s); }catch(Exception e){ System.out.println(e.getMessage()); System.exit(1); } } }