Java 跨平台特性使其成為伺服器端首選。Sun 推出 J2EE 平台,核心為 EJB:定義伺服器端組件標準、組件與應用伺服器間契約,支援可擴展企業級應用快速開發。
同為組件模型但關注點不同:JavaBeans 面向視覺化工具組裝;EJB 面向可攜式部署服務框架。無事件/屬性機制,屬性由部署描述符描述。JavaBeans 非專屬客戶端,EJB 非專屬伺服器端。用 JavaBeans 做伺服器應用需自建框架,EJB 提供現成框架。
EJBHome:定位/建立/刪除實例,Home Object 實作EJBObject:實作遠端介面,客戶端代理,提供包裝功能| Session Bean | Entity Bean | |
|---|---|---|
| 代表 | 商業流程對象 | 持久資料實體 |
| 生命週期 | 與客戶端同在 | 與資料同在 |
| 類型 | Stateful / Stateless | 單一/多表映射 |
| 共享性 | 專屬客戶端 | 多客戶端共享 |
| 狀態 | 保存客戶端狀態 | 保存資料記錄狀態 |
最佳組合:客戶端 → Session Bean (流程/交易) → Entity Bean (資料)。
SessionBean 或 EntityBean 介面EJBObject 定義遠端介面(方法同名、拋 RemoteException)EJBHome 定義 create() 對應 ejbCreate()public class HelloBean implements SessionBean {
public void ejbCreate() { System.out.println("ejbCreate()"); }
public void ejbActivate() { System.out.println("ejbActivate()"); }
public void ejbPassivate() { System.out.println("ejbPassivate()"); }
public void ejbRemove() { System.out.println("ejbRemove()"); }
public void setSessionContext(SessionContext ctx) { System.out.println("setSessionContext()"); }
public String hello() { return "Hello, World!"; }
}
public interface Hello extends EJBObject {
String hello() throws RemoteException;
}
public interface HelloHome extends EJBHome {
Hello create() throws CreateException, RemoteException;
}
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>helloworld</ejb-name>
<home>com.JSPer.ejbexample.session.helloworld.HelloHome</home>
<remote>com.JSPer.ejbexample.session.helloworld.Hello</remote>
<ejb-class>com.JSPer.ejbexample.session.helloworld.HelloBean</ejb-class>
<session-type>Stateless</session-type>
<container-transaction>
<method><ejb-name>helloworld</ejb-name><method-name>*</method-name></method>
Required
</container-transaction>
</session>
</enterprise-beans>
</ejb-jar>
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>helloworld</ejb-name>
<jndi-name>hello.HelloHome</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
jar cv0f std_hello.jar META-INF com imagesweblogic.ejbc 產生可部署 JARweblogic.properties 加入 JAR 路徑Context ctx = getInitialContext("t3://localhost:7001", null, null);
HelloHome home = (HelloHome) ctx.lookup("hello.HelloHome");
Hello hello = home.create();
System.out.println(hello.hello());
hello.remove();