`

EJB 2.0之Session Bean 示例教程

    博客分类:
  • EJB
阅读更多

本示例是在Weblogic的示范example中进行修改的,模拟Trade的buy和sell的过程.

定义了四个Business方法,具体看Remote接口Trader.

另外定义了一个testLocal的方法用来测试Local接口(为什么要这么做,不明白的同学先看看Local的基本知识)

自定义买卖过程中出现的Exceptioin:ProcessingErrorException

封装买卖的结果PO:TradeResult

模拟客户端的买卖行为:Client

配置ejb-jar.xml和weblogic-ejb-jar.xml

 1.Remote 接口 Trader.java

import java.rmi.RemoteException;
import javax.ejb.EJBObject;

public interface Trader extends EJBObject {
	public abstract TradeResult buy(String customerName, String stockSymbol,
			int shares) throws ProcessingErrorException, RemoteException;

	public abstract TradeResult sell(String customerName, String stockSymbol,
			int shares) throws ProcessingErrorException, RemoteException;

	public abstract double getBalance() throws RemoteException;

	public abstract double getStockPrice(String stockSymbol)
			throws ProcessingErrorException, RemoteException;
	
	public abstract double testLocal() throws RemoteException;
}

 2.Home 接口 TraderHome.java

import java.rmi.RemoteException;

import javax.ejb.CreateException;
import javax.ejb.EJBHome;
import javax.ejb.EJBObject;

public interface TraderHome extends EJBHome {

	public Trader create() throws RemoteException,CreateException;
}

 

3.Local 接口 TraderLocal.java

import javax.ejb.EJBLocalObject;

public interface TraderLocal extends EJBLocalObject{

	public abstract TradeResult buy(String customerName, String stockSymbol,
			int shares) throws ProcessingErrorException;
	
	public abstract TradeResult sell(String customerName, String stockSymbol,
			int shares) throws ProcessingErrorException;
	
	public abstract double getBalance() ;
	
	public abstract double getStockPrice(String stockSymbol)
	throws ProcessingErrorException;
	
	public abstract double testLocal();
}

 

4.LocalHome 接口 TraderLocalHome.java

import javax.ejb.CreateException;
import javax.ejb.EJBLocalHome;

public interface TraderLocalHome extends EJBLocalHome {
	public TraderLocal create() throws CreateException;
}

 

5.Stateful Session Bean TraderBean.java

import javax.ejb.CreateException;
import javax.ejb.RemoveException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class TraderBean implements SessionBean {

	static final boolean VERBOSE = true;

	private SessionContext ctx;
	private Context environment;
	private double tradingBalance;

	public void setSessionContext(SessionContext ctx) {
		log("setSessionContext called");
		this.ctx = ctx;
	}

	public void ejbActivate() {
		log("ejbActivate called");
	}

	public void ejbPassivate() {
		log("ejbPassivate called");
	}

	public void ejbRemove() {
		log("ejbRemove called");
	}

	public void ejbCreate() throws CreateException {
		log("ejbCreate called");
		try {
			InitialContext ic = new InitialContext();
			environment = (Context) ic.lookup("java:comp/env");
			
			
		} catch (NamingException ne) {
			throw new CreateException("Could not look up context");
		}
		this.tradingBalance = 0.0;
	}

	public TradeResult buy(String customerName, String stockSymbol, int shares)
			throws ProcessingErrorException {
		log("buy (" + customerName + ", " + stockSymbol + ", " + shares + ")");

		double price = getStockPrice(stockSymbol);
		tradingBalance -= (shares * price); // subtract purchases from cash
											// account

		return new TradeResult(shares, price, TradeResult.BUY);
	}

	public TradeResult sell(String customerName, String stockSymbol, int shares)
			throws ProcessingErrorException {
		log("sell (" + customerName + ", " + stockSymbol + ", " + shares + ")");

		double price = getStockPrice(stockSymbol);
		tradingBalance += (shares * price);

		return new TradeResult(shares, price, TradeResult.SELL);
	}

	public double getBalance() {
		return tradingBalance;
	}

	public double getStockPrice(String stockSymbol)
			throws ProcessingErrorException {
		try {
			return ((Double) environment.lookup(stockSymbol)).doubleValue();
		} catch (NamingException ne) {
			throw new ProcessingErrorException("Stock symbol " + stockSymbol
					+ " does not exist");
		} catch (NumberFormatException nfe) {
			throw new ProcessingErrorException("Invalid price for stock "
					+ stockSymbol);
		}
	}
	
	public double testLocal(){
		Double balance=1.00;
		try{
		InitialContext ic = new InitialContext();
		
		TraderLocalHome localHome=(TraderLocalHome)ic.lookup("ejb/TraderEJB");
		TraderLocal localTrader = (TraderLocal) localHome.create();
		balance=localTrader.getBalance();
		localTrader.remove();
		
		}catch(Exception e){
			log("local exception");
		}
		return balance;
	}

	private void log(String s) {
		if (VERBOSE) {
			System.out.println(s);
		}
	}
}

 

6.自定义Exception:ProcessingErrorException

public class ProcessingErrorException extends Exception {
  public ProcessingErrorException() {}
  public ProcessingErrorException(String message) {super(message);}
}

 

7.Trade买卖结果封装的POJO:TradeResult

import java.io.Serializable;

public final class TradeResult implements Serializable {

  public static final int SELL = 0;
  public static final int BUY  = 1;

  private int    numberTraded;    // Number of shares really bought or sold
  private int    action;          // Whether shares were bought or sold
  private double price;           // Price shares were bought or sold at

  public TradeResult(int numberTraded, double price, int action) {
    this.numberTraded = numberTraded;
    this.price        = price;
    this.action       = action;
  }

  public int getNumberTraded() {
    return numberTraded;
  }

  public int getActionTaken() {
    return action;
  }

  public double getPrice() {
    return price;
  }

  public String toString() {
    String result = numberTraded + " shares";
    if(action == SELL) {
      result += "sold";
    } else {
      result += "bought";
    }
    result += " at a price of " + price;
    return result;
  }
}

 

8.客户端调用EJB的程序:Client.java

import java.rmi.RemoteException;
import java.util.Hashtable;
import javax.ejb.CreateException;
import javax.ejb.RemoveException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

public class Client {
	private static final String JNDI_NAME = "ejb20-statefulSession-TraderHome";
	private String url;
	private TraderHome home;

	public Client(String url) {
		this.url = url;
	}

	public static void main(String[] args) throws Exception {
		log("\nBeginning statefulSession.Client...\n");
		String url = "t3://localhost:7001";
		Client client = null;

		// Parse the argument list
		if (args.length > 1) {
			log("Usage: java examples.ejb.ejb20.basic.statefulSession.Client t3://hostname:port");
			return;
		} else if (args.length == 1) {
			url = args[0];
		}

		try {
			client = new Client(url);
			client.example();// remote
		} catch (NamingException ne) {
			log("Unable to look up the beans home: " + ne.getMessage());
			throw ne;
		} catch (Exception e) {
			log("There was an exception while creating and using the Trader.");
			log("This indicates that there was a problem communicating with the server: "
					+ e);
			throw e;
		}
		log("\nEnd statefulSession.Client...\n");
	}

	public void example() throws CreateException, ProcessingErrorException,
			RemoteException, RemoveException, NamingException {
		String customerName = "Matt";

		// Create a Trader
		log("Creating trader\n");
		home = lookupHome();
		Trader trader = (Trader) narrow(home.create(), Trader.class);

		// Sell some stock
		String stockName = "MSFT";
		int numberOfShares = 200;
		log("Selling " + numberOfShares + " of " + stockName);
		TradeResult tr = trader.sell(customerName, stockName, numberOfShares);
		log(tr.toString());

		// Buy some stock
		stockName = "BEAS";
		numberOfShares = 250;
		log("Buying " + numberOfShares + " of " + stockName);
		tr = trader.buy(customerName, stockName, numberOfShares);
		log(tr.toString());

		// Get change in Cash Account from EJBean
		log("Change in Cash Account: $" + trader.getBalance() + "\n");

		log("Local Ejb test start...");

		log("testing localTrader balance is:" + trader.testLocal());

		log("Local Ejb test end...");
		log("Removing trader\n");
		trader.remove();

	}

	/**
	 * RMI/IIOP clients should use this narrow function
	 */
	private Object narrow(Object ref, Class c) {
		return PortableRemoteObject.narrow(ref, c);
	}

	/**
	 * Lookup the EJBs home in the JNDI tree
	 */
	private TraderHome lookupHome() throws NamingException {
		// Lookup the beans home using JNDI
		Context ctx = getInitialContext();
		try {
			Object home = ctx.lookup(JNDI_NAME);
			return (TraderHome) narrow(home, TraderHome.class);
		} catch (NamingException ne) {
			log("The client was unable to lookup the EJBHome.  Please make sure ");
			log("that you have deployed the ejb with the JNDI name "
					+ JNDI_NAME + " on the WebLogic server at " + url);
			throw ne;
		}
	}

	/**
	 * Using a Properties object will work on JDK 1.1.x and Java2 clients
	 */
	private Context getInitialContext() throws NamingException {
		try {
			// Get an InitialContext
			Hashtable<String, String> h = new Hashtable<String, String>();
			h.put(Context.INITIAL_CONTEXT_FACTORY,
					"weblogic.jndi.WLInitialContextFactory");
			h.put(Context.PROVIDER_URL, url);
			return new InitialContext(h);
		} catch (NamingException ne) {
			log("We were unable to get a connection to the WebLogic server at "
					+ url);
			log("Please make sure that the server is running.");
			throw ne;
		}
	}

	private static void log(String s) {
		System.out.println(s);
	}

}

 

9.ejb-jar.xml

<ejb-jar>
	<enterprise-beans>
		<session>
			<ejb-name>TraderEJB</ejb-name>
			<home>ejb.stateful.TraderHome</home>
			<remote>ejb.stateful.Trader</remote>
			<local-home>ejb.stateful.TraderLocalHome</local-home>
			<local>ejb.stateful.TraderLocal</local>
			<ejb-class>ejb.stateful.TraderBean</ejb-class>
			<session-type>Stateful</session-type>
			<transaction-type>Container</transaction-type>
			<env-entry>
				<env-entry-name>BEAS</env-entry-name>
				<env-entry-type>java.lang.Double</env-entry-type>
				<env-entry-value>100.00</env-entry-value>
			</env-entry>
			<env-entry>
				<env-entry-name>MSFT</env-entry-name>
				<env-entry-type>java.lang.Double</env-entry-type>
				<env-entry-value>150.00</env-entry-value>
			</env-entry>
		</session>
	</enterprise-beans>
	<assembly-descriptor>
		<container-transaction>
			<method>
				<ejb-name>TraderEJB</ejb-name>
				<method-name>*</method-name>
			</method>
			<trans-attribute>Required</trans-attribute>
		</container-transaction>
	</assembly-descriptor>
</ejb-jar>

 

10.weblogic-ejb-jar.xml

<weblogic-ejb-jar>
	<weblogic-enterprise-bean>
		<ejb-name>TraderEJB</ejb-name>
		<stateful-session-descriptor/>
		<jndi-name>ejb20-statefulSession-TraderHome</jndi-name>
		<local-jndi-name>ejb/TraderEJB</local-jndi-name>
	</weblogic-enterprise-bean>
</weblogic-ejb-jar>

 

11.run Client.java测试结果

Beginning statefulSession.Client...

Creating trader

Selling 200 of MSFT
200 sharessold at a price of 150.0
Buying 250 of BEAS
250 sharesbought at a price of 100.0
Change in Cash Account: $5000.0

Local Ejb test start...
testing localTrader balance is:0.0
Local Ejb test end...
Removing trader


End statefulSession.Client...

 

分享到:
评论

相关推荐

    ejb实例包括session bean和实体bean

    ejb实例包括session bean和实体bean

    EJB2.0 实例开发

    里面清楚的讲解各个部分, ,资料仅作参考, 有兴趣兄弟赶紧去学学啊。希望有所帮助

    ejb入门录像 sessionBean

    ejb入门录像,MyEclipse开发sessionBean实例

    EJB的开发及应用,Session Bean的开发

    简要介绍JNDI,EJB及其开发应用技术,附有Session Bean的开发实例

    Java EJB中有、无状态SessionBean的两个例子

    Java EJB中有、无状态SessionBean的两个例子,的无状态SessionBean可,会话Bean必须实现SessionBean,获取系统属性,初始化JNDI,取得Home对象的引用,创建EJB对象,计算利息等;  在有状态SessionBean中,用累加...

    ejb3实例(包括sessionbean和entitybean)

    ejb3实例(包括sessionbean和entitybean,sql),sqlserver数据库,配置好JNDI数据源后即可运行,值得关注。

    Java SessionBean状态判断的例子.rar

    Java SessionBean状态判断的例子,代码包中的两个实例,分别对无状态SessionBean和有状态SessionBean进行了演示,请注意,Home对象是EJB对象的制作生成库,该方法生成EJB对象,value参数用于计数器的初始化,在无状态...

    Java中的EJB编程实例代码

    Java中的EJB编程实例代码,内容有:简单的EJB、无状态SessionBean、有状态SessionBean、BMP位图实例、cmp实例、Message-Driven Bean、JNDI的使用、112各种EJB之间的调用、B-S结构EJB、 C-S结构EJB、UML建模与J2EE...

    基于Java的实例源码-EJB中有、无状态SessionBean的两个例子.zip

    基于Java的实例源码-EJB中有、无状态SessionBean的两个例子.zip

    基于Java的实例开发源码-EJB中有、无状态SessionBean的两个例子.zip

    基于Java的实例开发源码-EJB中有、无状态SessionBean的两个例子.zip

    EJB3.0 实例教程 -- 切片1

    绍之中,应用实例更是少之又少,所以作者拟写本书,以简单的实例展现EJB3.0 的开发过程,希望对大家有所帮 助。 EJB3 最激动人心的是POJO 编程模型,我想对开发人员的影响将是非常大的,因为他降低了开发人员编写EJB ...

    Ejb技术入门级实例大全

    包括的实例有:session bean的 statuless bean,statuful bean,entity bean的 BMP bean,CMP bean,messageDriver bean。并使用统一客户端调用,并附有数据库脚本。供大家下载布暑运行。 本Ejb运行环境:jdk1.42 + ...

    EJB 3.0实例教程

    EJB 3.0实例教程,通过实例描述,详细介绍了Session Bean,Entity Bean和Message Driven Bean

    Java中Enterprise JavaBeans(EJB)编程实例代码.rar

    Java中Enterprise JavaBeans(EJB)编程实例代码,内容有:简单的EJB、无状态SessionBean、有状态SessionBean、BMP位图实例、cmp实例、Message-Driven Bean、JNDI的使用、112各种EJB之间的调用、B-S结构EJB、 C-S结构...

    EJB3.0 实例教程 -- 切片2

    EJB3.0 实例教程 第一章 前言......4 1.1 本教程适合人群4 1.2 联系作者..4 第二章运行环境配置4 2.1 下载与安装........4 2.2 运行一个EJB3例子.......9 2.3 在独立的TOMCAT 中调用EJB....9 2.4 发布在JBOSS集成...

    简单的ejb实例,Java初学实例

    一个简单的Stateless Session Bean的例子,里面主要实现一个与时间有关的... 同时编写了一个客户端测试程序,展现的是一个简单的Stateless Session Bean的实现过程,希望能够对复杂的EJB的开发起一些抛砖引玉的作用。

    经典JAVA EE企业应用实战基于WEBLOGIC JBOSS的JSF+EJB 3+JPA整合开发——源码第9章

    EJB 3部分则包含Session Bean、Message Driven Bean的详细介绍。本书内容主要包括三部分,第一部分介绍Java EE开发的基础知识,以及如何搭建开发环境;第二部分详细讲解了JSF RI、EJB 3的Session Bean等Java EE知识...

    Java 简单的ejb实例代码.rar

    简单的Java ejb实例代码,一个简单的Stateless Session Bean的例子,通过Bean使用远程接口方法访问数据,里面主要实现一个与时间有关的方法函数,同时编写了一个客户端测试程序。创建一个访问EJB的客户端应用程序,...

Global site tag (gtag.js) - Google Analytics