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); } } }