当前页面: 开发资料首页 → Java 专题 → 循速渐进学用Session Bean(五)
循速渐进学用Session Bean(五)
摘要: HelloWorldSession例子的主要目的是帮助你熟悉一个session bean的整体结构。现在你已经熟悉了session bean的结构
创建一个实用的Session Bean
HelloWorldSession例子的主要目的是帮助你熟悉一个session bean的整体结构。现在你已经熟悉了session bean的结构,你可以写一个更实用的bean了。特别地,你可以写一个由数据库中接收数据的bean。
以下的例子,假定你拥有一个SQL表格,里面包含有产品的代码和价格,你也可以使用以下SQL命令建立它:
<table width="100%" bgColor=#ffffff>
<tr>
<td>create table price
(product_code varchar(10) not null primary key,
price decimal(10,2) not null)</td></tr></table>
Pricing session bean可以列出全部有效的产品代码,并且可以返回某个产品代码的价格,该代码由Remote接口指定,如6.9列表所示:
<table width="100%" bgColor=#ffffff>
<tr>
<td>Listing 6.9 Source Code for Pricing.java
package usingj2ee.pricing;
import java.rmi.*;
import javax.ejb.*;
/** Defines the methods you can call on a Pricing session */
public interface Pricing extends EJBObject
{
/** Returns all the available product codes */
public String[] getProductCodes() throws RemoteException;
/** Returns the price for a specific product code */
public double getPrice(String productCode)
throws RemoteException, InvalidProductCodeException;
}
</td></tr></table>
Pricing session bean并不需要记得某个客户的任何信息,所以可以用一个无状态的session bean实现。PricingHome接口如列表6.10所示,它仅需要一个create方法。
<table width="100%" bgColor=#ffffff>
<tr>
<td>Listing 6.10 Source Code for PricingHome.java
package usingj2ee.pricing;
import java.rmi.*;
import javax.ejb.*;
/** Defines the methods for creating a Pricing session */
public interface PricingHome extends EJBHome
{
/** Creates a Pricing session bean */
public Pricing create() throws RemoteException, CreateException;
}
</td></tr></table>
当一个session bean需要访问一个数据库连接时,它通常在setSessionContext方法中分配一个连接,最后在ejbRemote方法中释放它。当然,如果你拥有一个数据库的连接,在容器调用ejbPassivate方法时,你必须准备关闭它,在容器调用ejbActivate时,重新得到连接。
↑返回目录
前一篇:
J2EE的安全认证机制
后一篇:
循速渐进学用Session Bean(四)