4 發布EJB程序
我們來編寫一段最簡單的“Hello World”無狀態會話Bean,我們創建的無狀態會話Bean運行在分布式對象架構里,執行著重要的任務:向客戶端返回一字符串——“Hello,World!”
4.1 創建Remote接口
我們以編寫Remote接口開始,Remote接口復制了Bean“暴露”的每一個商務方法,由EJB容器實現Remote接口,實現的結果就是EJB對象。EJB對象將所有的客戶端請求委托給實際的Bean。源代碼如下:
Hello.java
package hello.ejb; /** * Remote interface for Enterprise Bean: Hello */ public interface Hello extends javax.ejb.EJBObject { /** * 唯一的方法hello,向客戶端返回問候。 */ public String hello() throws java.rmi.RemoteException; } |
4.2 實現“Hello,world!”的Bean
接下來,創建Bean本身。我們將實現一個商務方法——hello()方法,我們還增加了所需的EJB容器回調方法。程序源代碼如下“:
HelloBean.java
package hello.ejb; /** * Bean implementation class for Enterprise Bean: Hello */ public class HelloBean implements javax.ejb.SessionBean { private javax.ejb.SessionContext mySessionCtx; /** * getSessionContext */ public javax.ejb.SessionContext getSessionContext() { return mySessionCtx; } /** * setSessionContext */ public void setSessionContext(javax.ejb.SessionContext ctx) { mySessionCtx = ctx; } /** * ejbActivate */ public void ejbActivate() { } /** * ejbCreate */ public void ejbCreate() throws javax.ejb.CreateException { } /** * ejbPassivate */ public void ejbPassivate() { } /** * ejbRemove */ public void ejbRemove() { } // // 商務方法 // public String hello() { return "Hello,World!"; }
} |
4.3 創建“Hello,World!”Home接口
這里編寫的Home接口詳細說明了生成和清除EJB對象方法。程序源代碼如下:
HelloHome.java
package hello.ejb; /** * Home interface for Enterprise Bean: Hello */ public interface HelloHome extends javax.ejb.EJBHome { /** * Creates a default instance of Session Bean: Hello */ public Hello create() throws javax.ejb.CreateException, java.rmi.RemoteException; } |
4.4 EJB部署描述
ejb-jar.xml
|
下面icech來簡單介紹一下XML部署描述的內容。
|
4.5 客戶端代碼
客戶端代碼執行以下幾個任務:
· 查找Home對象;
· 使用Home對象生成EJB對象;
· 對EJB對象調用hello()方法;
· 從內存中清除EJB對象。
HelloClient.java
package hello.ejb; import java.util.*; import java.io.*; import javax.naming.InitialContext; import javax.rmi.PortableRemoteObject; public class HelloClient { public static void main(String[] args) { try { //jndi配置,硬編碼到java中,應實現為外部屬性文件 Properties p=new Properties(); p.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory"); p.setProperty("java.naming.provider.url", "localhost:1099");
//out print jndi配置 p.list(System.out);
// Get a naming context InitialContext jndiContext = new InitialContext(p); System.out.println("Got context");
// Get a reference to the Interest Bean //jboss默認jndi名為ejb-jar.xml中的:ejb-name Object ref = jndiContext.lookup("Hello"); System.out.println("Got reference");
// Get a reference from this to the Bean"s Home interface HelloHome home = (HelloHome) PortableRemoteObject.narrow(ref, HelloHome.class);
// Create an Hello object from the Home interface Hello hello = home.create();
// call the hello() method System.out.println(hello.hello()); } catch(Exception e) { System.out.println(e.toString()); } } } |