当前页面: 开发资料首页 → J2EE 专题 → 关于EJB的基本概念和例子2
摘要: 关于EJB的基本概念和例子
package com.syscom;
import java.rmi.*;
import javax.ejb.*;
public class statefulBean implements SessionBean {
private SessionContext sessionContext;
public void ejbCreate() {
}
public void ejbRemove() {
}
public void ejbActivate() {
}
public void ejbPassivate() {
}
public void setSessionContext(SessionContext context) {
sessionContext = context;
}
}
package com.syscom.cghdemo.sejb.scrutinize;
import java.rmi.*;
import javax.ejb.*;
import java.util.*;
omport java.io.*;
import javax.naming.*;
import syscom.cghdemo.eejb.regvhist.*;
public class MyTestBean implements SessionBean {
private SessionContext sessionContext;
public String[] SerachPatient(String idno) throws RemoteException{
try{
System.out.println("\nBeginning SerachPatient ...\n");
String[] PatientData = new String[4];
javax.naming.Context ctx1 = getInitialContext();
regvhistHome home1 = (regvhistHome)javax.rmi.PortableRemoteObject.narrow(ctx1.lookup("regvhist"),regvhistHome.class);
regvhist loaddata1 = home1.findByIdCode(idno);
PatientData[0] = loaddata1.getChineseName();
PatientData[1] = loaddata1.getChartNo();
PatientData[2] = loaddata1.getSex();
PatientData[3] = loaddata1.getEnglishName();
return PatientData;
} catch (Exception ex) {
String[] PatientData = new String[1];
PatientData[0] = "Error";
System.out.println("Error:"+ex);
return PatientData;
}
}
public String Inserttristria(String[] PD) throws IOException {
System.out.println("\nBeginning Inserttristria ...\n");
}
public int GetMyID() {
return 1;
}
public void ejbCreate() throws CreateException {
//未實作
}
public void ejbRemove() throws RemoteException {
//未實作
}
public void ejbActivate() throws RemoteException {
//未實作
}
public void ejbPassivate() throws RemoteException {
//未實作
}
public void setSessionContext(SessionContext context) throws RemoteException {
sessionContext = context;
}
private static Context getInitialContext() throws NamingException {
try {
Properties h = new Properties();
h.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, "t3://localhost:7001");
return new InitialContext(h);
} catch (NamingException ne) {
System.out.println("unable to get a connection to the WebLogic server");
throw ne;
}
}
}
/**
*Remote Interface Class
*/
package com.syscom.cghdemo.sejb.scrutinize;
import java.rmi.*;
import javax.ejb.*;
public interface scrutinize extends EJBObject {
public String[] SerachPatient(String idno) throws RemoteException, RemoteException;
public String Inserttristria(String[] PD) throws IOException, RemoteException;
public int GetMyID() throws RemoteException;
}
package com.syscom.cghdemo.sejb.scrutinize;
import java.rmi.*;
import javax.ejb.*;
public interface scrutinizeHome extends EJBHome {
public scrutinize create( ) throws CreateException, RemoteException;
}
package javax.ejb;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface EJBHome extends Remote {
public abstract EJBMetaData getEJBMetaData()
throws RemoteException;
public abstract HomeHandle getHomeHandle()
throws RemoteException;
public abstract void remove(Object obj)
throws RemoteException, RemoveException;
public abstract void remove(Handle handle)
throws RemoteException, RemoveException;
}
package sample.ejb.session.stateless;
import java.rmi.*;
import javax.ejb.*;
//在撰寫EJB時,通成為了方便,我們至少都會import java.rmi.*與javax.ejb.*兩組class
public class CheckBean implements SessionBean
{
private SessionContext sessionContext;
public void ejbCreate()
{
//callback method
}
public void ejbRemove()
{
//callback method
}
public void ejbActivate()
{
//callback method
}
public void ejbPassivate()
{
//callback method
}
public void setSessionContext(SessionContext context)
{
//callback method
sessionContext = context;
//EJB Container呼叫setSessionContext時會將Bean Instance的SessionContext傳入
//我們將其reference複製到context變數中,之後便可利用context變數取得Instance的
//相關資訊,
}
/**
* 檢查身份證號是否正確的method
* @param ID 身份證號
* @return 正確嗎(true or false)?
*/
public boolean isIDCorrect(String ID){
boolean isCorrect = true;
String MapTable = new String("ABCDEFGHJKLMNPQRSTUVXY");
String C = new String("1987654321");
String PID = ID.toUpperCase();
StringBuffer str = new StringBuffer("");
int i=0,n=0;
if (PID.length()!=10)
return(false);
if (('A'>PID.charAt(0)) || (PID.charAt(0)>'Z')){
isCorrect = false;
}
else if (PID.length() != 10){
isCorrect = false;
}
for (i=1;i<=9;i++){
if (('0'>PID.charAt(i)) || (PID.charAt(i)>'9'))
isCorrect = false;
}
str.append(String.valueOf(10 + MapTable.indexOf(PID.charAt(0),0)));
str.append(PID.substring(1));
for (i=0,n=0;i<10;i++){
n += Integer.valueOf(String.valueOf(str.charAt(i))).intValue() *
Integer.valueOf(String.valueOf(C.charAt(i))).intValue();
}
n = 10 - n % 10;
if (n != Integer.valueOf(String.valueOf(PID.charAt(9))).intValue()){
isCorrect = false;
}
return(isCorrect);
}
}
package sample.ejb.session.stateless;
import java.rmi.*;
import javax.ejb.*;
public interface CheckHome extends EJBHome
{
public Check create() throws RemoteException, CreateException; //一定要有這兩個Exception
}
package sample.ejb.session.stateless;
import java.rmi.*;
import javax.ejb.*;
public interface Check extends EJBObject
{
public boolean isIDCorrect(java.lang.String ID) throws RemoteException; //一定要有這Exception
}
package sample.ejb.session.stateless;
import javax.naming.*;
import java.util.*;
public class CheckBeanTestClient
{
public static void main(String[] args)
{
Context ctx = null;
CheckHome checkHome = null;
Check check = null;
try {
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,"t3://localhost:7001");
ctx = new InitialContext(ht);
//以上四行程式用來取得與WLS的聯繫,其中localhost要改成WLS所在電腦的IP
checkHome = (CheckHome)ctx.lookup("sample.ejb.session.stateless.CheckBean");
//EJB部署到WLS需設定其JNDI name.當Client端要呼叫EJB時,便使用Context.lookup(),
//傳入JNDI name,即可找到該EJB的Home Interface.WLS會使用Home Interface建立
//EJB Home,並將其reference傳給Client端.
check = checkHome.create();
//使用Home Interface內的create()建立Remote Interface.
System.out.println("身份證號 : A200000003 " + (check.isIDCorrect("A200000003")?"正確":"錯誤"));
//利用Remote Interface呼叫EJB內的Business Logic Method
System.out.println("身份證號 : A200000001 " + (check.isIDCorrect("A200000001")?"正確":"錯誤"));
}catch (Exception ex) {
System.err.println(ex.getMessage());
//顯示錯誤訊息
}
finally{
try {
ctx.close();
//將ctx消滅
} catch (Exception ex) {}
}
}
}
package sample.ejb.session.stateful;
import java.rmi.*;
import javax.ejb.*;
import java.util.*;
public class CartBean implements SessionBean // 若需有transaction event,則implements後需再加 SessionSynchronization
{
private SessionContext sessionContext;
private Vector Items = new Vector();
private String CardHolderName;
private String CreditCardNumber;
private Date ExpirationDate;
public void ejbCreate(String cardHolderName, String creditCardNumber, Date expirationDate)
{
this.CardHolderName = cardHolderName;
this.CreditCardNumber = creditCardNumber;
this.ExpirationDate = expirationDate;
} //此時的ejbCreate便可以有參數的傳入了,這和Home的Create()參數有一致
public void ejbRemove(){}
public void ejbActivate(){}
public void ejbPassivate() {}
public void setSessionContext(SessionContext context) {
sessionContext = context;
}
/**
* 需有transaction event時,請實作下列3個method
* public void afterBegin(){}
* public void beforeCompletion(){}
* public void afterCompletion(boolean committed){}
*/
public void addItem(Item item) {
System.out.println("\t增加品名(" + item.getTitle() + "): " + this);
this.Items.addElement(item);
}
public void removeItem(Item item) throws ItemNotFoundException {
System.out.println("\t移除品名(" + item.getTitle() + "): " + this);
Enumeration elements = this.Items.elements();
while(elements.hasMoreElements()) {
Item current = (Item) elements.nextElement();
// items are equal if they have the same class and title
if(item.getClass().equals(current.getClass()) &&
item.getTitle().equals(current.getTitle())) {
this.Items.removeElement(current);
return;
}
}
throw new ItemNotFoundException("項目 " + item.getTitle() + " 不在購物車中!!");
}
public float getTotalPrice() {
System.out.println("\t總價(): " + this);
float totalPrice = 0f;
Enumeration elements = this.Items.elements();
while(elements.hasMoreElements()) {
Item current = (Item) elements.nextElement();
totalPrice += current.getPrice();
}
// round to the nearest lower penny...
return (long) (totalPrice * 100) / 100f;
}
public java.util.Enumeration getContents() {
System.out.println("\t列出購物車內品名(): " + this);
return new VectorEnumeration(this.Items);
}
public void purchase() throws PurchaseProblemException {
System.out.println("\t交易(): " + this);
// 確定信用卡尚未過期
Date today = Calendar.getInstance().getTime();
if(this.ExpirationDate.before(today)) {
throw new CardExpiredException("信用卡有效期限 : " + this.ExpirationDate);
}
// 將資料 update 進資料庫
System.out.println("==========================================");
}
public String toString() {
return "CartBean[姓名:" + this.CardHolderName + "]";
}
}
package sample.ejb.session.stateful;
import java.rmi.*;
import javax.ejb.*;
import java.util.Date;
public interface CartHome extends EJBHome {
public Cart create(String cardHolderName, String creditCardNumber, Date expirationDate)
throws RemoteException, CreateException;
}
package sample.ejb.session.stateful;
import java.rmi.*;
import javax.ejb.*;
import java.util.Enumeration;
public interface Cart extends EJBObject {
public void addItem(Item item) throws RemoteException;
public void removeItem(Item item) throws ItemNotFoundException, RemoteException;
public float getTotalPrice() throws RemoteException;
public Enumeration getContents() throws RemoteException;
public void purchase() throws PurchaseProblemException, RemoteException;
}
package sample.ejb.session.stateful;
import java.util.*;
import javax.naming.*;
class Book extends Item {
Book(String title, float price) {
super(title, price);
}
}
class CompactDisc extends Item {
CompactDisc(String title, float price) {
super(title, price);
}
}
public class CartBeanTestClient {
static void summarize(Cart cart) throws Exception {
System.out.println("======= 購物車內所含品名 ========");
Enumeration elements = cart.getContents();
while(elements.hasMoreElements()) {
Item current = (Item) elements.nextElement();
System.out.println("單價 : $" + current.getPrice() + "\t" +
current.getClass().getName() + " title: " + current.getTitle());
}
System.out.println("總價 : $" + cart.getTotalPrice());
System.out.println("=================================");
}
public static void main(String[] args) throws Exception {
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,"t3://localhost:7001");
Context ctx = new InitialContext(ht);
CartHome home = (CartHome)ctx.lookup("sample.ejb.session.stateful.CartBean");
Cart cart;
{
String cardHolderName = "Rex Cheng";
String creditCardNumber = "1234-5678-9012-3456";
Date expirationDate = new GregorianCalendar(2002, Calendar.JULY, 1).getTime();
cart = home.create(cardHolderName, creditCardNumber, expirationDate);
}
Book knuthBook = new Book("JAVA Servlet 設計", 760f);
cart.addItem(knuthBook);
CompactDisc milesAlbum = new CompactDisc("張惠妹", 340f);
cart.addItem(milesAlbum);
summarize(cart);
cart.removeItem(knuthBook);
Book weedonBook = new Book("Java 入門", 560f);
cart.addItem(weedonBook);
summarize(cart);
try {
cart.purchase();
System.out.println("交易成功");
}
catch(PurchaseProblemException e) {
System.out.println("交易失敗:\n\t" + e);
}
cart.remove();
}
}
package sample.ejb.session.stateful;
import java.io.Serializable;
public class Item implements Serializable
{
private String Title;
private float Price;
public Item(String title, float price) {
this.Title = title;
this.Price = price;
}
public String getTitle() {
return this.Title;
}
public float getPrice() {
return this.Price;
}
}
package sample.ejb.session.stateful;
import java.util.*;
/**
* 因 JDK 標準的 Enumeration 沒有實作 java.io.Serializable,
* 所以沒有辦法透過 RMI (或 RMI-over-IIOP) 的機制傳送。
* 所以我們自行實作一個簡單的 VectorEnumeration,實作 Enumeration及java.io.Serializable
*/
class VectorEnumeration implements Enumeration, java.io.Serializable {
private Vector vector;
private transient Enumeration enumeration;
public VectorEnumeration(Vector vector) {
this.vector = vector;
}
private synchronized Enumeration getEnumeration() {
if(this.enumeration == null) {
this.enumeration = this.vector.elements();
}
return this.enumeration;
}
public boolean hasMoreElements() {
return getEnumeration().hasMoreElements();
}
public Object nextElement() {
return getEnumeration().nextElement();
}
}
package sample.ejb.session.stateful;
public class CardExpiredException extends PurchaseProblemException {
public CardExpiredException(String message) {
super(message);
}
}
ItemNotFoundException.java:
package sample.ejb.session.stateful;
public class ItemNotFoundException extends Exception {
public ItemNotFoundException(String message) {
super(message);
}
}
package sample.ejb.session.stateful;
public class PurchaseProblemException extends Exception {
public PurchaseProblemException(String message) {
super(message);
}
}