当前位置:天才代写 > tutorial > JAVA 教程 > 循速渐进学用Session Bean(五)

循速渐进学用Session Bean(五)

2017-11-12 08:00 星期日 所属: JAVA 教程 浏览:515

副标题#e#

建设一个实用的Session Bean

HelloWorldSession例子的主要目标是辅佐你熟悉一个session bean的整体布局。此刻你已经熟悉了session bean的布局,你可以写一个更实用的bean了。出格地,你可以写一个由数据库中吸收数据的bean。

以下的例子,假定你拥有一个SQL表格,内里包括有产物的代码和价值,你也可以利用以下SQL呼吁成立它:

create table price
(product_code varchar(10) not null primary key,
price decimal(10,2) not null)

Pricing session bean可以列出全部有效的产物代码,而且可以返回某个产物代码的价值,该代码由Remote接口指定,如6.9列表所示:

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;
}

Pricing session bean并不需要记得某个客户的任何信息,所以可以用一个无状态的session bean实现。PricingHome接口如列表6.10所示,它仅需要一个create要领。

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;
}

当一个session bean需要会见一个数据库毗连时,它凡是在setSessionContext要领中分派一个毗连,最后在ejbRemote要领中释放它。虽然,假如你拥有一个数据库的毗连,在容器挪用ejbPassivate要领时,你必需筹备封锁它,在容器挪用ejbActivate时,从头获得毗连。

你将会发明大部门的EJB开拓者利用一个要领来返回一个毗连;这样你就今后就可以修改获得毗连的要领,而不会影响利用这些毗连的代码。你也应该利用DataSource工具来建设毗连。DataSource让修改数据库的驱动变得容易,而且可以在需要的时候利用毗连池。

列表6.11展示了Pricing session bean的实现类PricingImpl

Listing 6.11 Source Code for PricingImpl.java
package usingj2ee.pricing;
import java.rmi.*;
import java.util.*;
import javax.ejb.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
/** The implementation class for the Pricing bean */
public class PricingImpl implements SessionBean
{
/** The session context provided by the EJB container. A session bean must
hold on to the context it is given. */
private SessionContext context;
/** The database connection used by this session */
private Connection conn;
/** An EJB must have a public, parameterless constructor */
public PricingImpl()
{
}
/** Called by the EJB container to set this session's context */
public void setSessionContext(SessionContext aContext)
{
context = aContext;
}
/** Called by the EJB container when a client calls the create() method in
the Home interface */
public void ejbCreate()
throws CreateException
{
try
{
// Allocate a database connection
conn = getConnection();
}
catch (Exception exc)
{
throw new CreateException(
"Unable to access database: "+exc.toString());
}
}
/** Called by the EJB container to tell this session bean that it is being
suspended from use (it's being put to sleep). */
public void ejbPassivate()
throws EJBException
{
try
{
// Shut down the current database connection
conn.close();
conn = null;
}
catch (Exception exc)
{
throw new EJBException("Unable to close database connection: "+
exc.toString());
}
}
/** Called by the EJB container to wake this session bean up after it
has been put to sleep with the ejbPassivate method. */
public void ejbActivate()
throws EJBException
{
try
{
// When the bean wakes back up, get a database connection again
conn = getConnection();
}
catch (Exception exc)
{
throw new EJBException(
"Unable to access database: "+exc.toString());
}
}
/** Called by the EJB container to tell this session bean that it has been
removed, either because the client invoked the remove() method or the
container has timed the session out. */
public void ejbRemove()
throws EJBException
{
try
{
// Shut down the current database connection
conn.close();
conn = null;
}
catch (Exception exc)
{
throw new EJBException("Unable to close database connection: "+
exc.toString());
}
}
/** Returns a list of the available product codes */
public String[] getProductCodes()
throws EJBException
{
Statement s = null;
try
{
s = conn.createStatement();
ResultSet results = s.executeQuery(
"select product_code from price");
Vector v = new Vector();
// Copy the results into a temporary vector
while (results.next())
{
v.addElement(results.getString("product_code"));
}
// Copy the vector into a string array
String[] productCodes = new String[v.size()];
v.copyInto(productCodes);
return productCodes;
}
catch (Exception exc)
{
throw new EJBException("Unable to get product codes: "+
exc.toString());
}
finally
{
// Close down the statement in a finally block to guarantee that it gets
// closed, whether an exception occurred or not
try
{
s.close();
}
catch (Exception ignore)
{
}
}
}
/** Gets the price for a particular product code */
public double getPrice(String productCode)
throws EJBException, InvalidProductCodeException
{
PreparedStatement ps = null;
try
{
// It's always better to use a prepared statement than to try to insert
// a string directly into the query string. This way you don't have to
// worry if there's a quote in the product code
ps = conn.prepareStatement(
"select price from price where product_code = ?");
// Store the product code in the prepared statement
ps.setString(1, productCode);
ResultSet results = ps.executeQuery();
// If there are any results, get the first one (there should only be one)
if (results.next())
{
return results.getDouble("price");
}
else
{
// Otherwise, if there were no results, this product code doesn't exist
throw new InvalidProductCodeException(productCode);
}
}
catch (SQLException exc)
{
throw new EJBException("Unable to get price: "+
exc.toString());
}
finally
{
// Close down the statement in a finally block to guarantee that it gets
// closed, whether an exception occurred or not
try
{
ps.close();
}
catch (Exception ignore)
{
}
}
}
protected Connection getConnection()
throws SQLException, NamingException
{
// Get a reference to the naming service
InitialContext context = new InitialContext();
// Get the data source for the pricing database
DataSource ds = (DataSource) context.lookup(
"java:comp/env/jdbc/PriceDB");
// Ask the data source to allocate a database connection
return ds.getConnection();
}
}


#p#副标题#e#

#p#分页标题#e#

PricingImpl中的getConnection值得寄望一下。它利用JNDI(定名处事)来定位到一个名字为java:comp/env/jdbc/PriceDB的数据源。java:comp/env指的是你的session bean利用的JNDI naming context。当session bean被设置在一个EJB容器时,容器为你的bean配置了一个带有各个项目标naming context,这些项目是在你设置bean时成立的。java:comp/env naming context让你将逻辑名字和各类差异资源接洽起来。这样你就可以在编写bean时,无需知道数据源可能Home接口的精确名字。当在设置bean到容器中时,配置bean利用的名字和真正资源名相关联。这样bean就并不绑定到某个出格的资源名字,可以晋升bean的移植性。

在设置Pricing bean时,必需指定jdbc/PriceDB的一个体名。假如利用J2EE SDK带有的Cloudscape数据库,这个体名必需是jdbc/Cloudscape。不然,必需在EJB处事器中成立一个数据源,指向要利用的数据库。当设置Pricing bean时,指定jdbc/PriceDB引用的数据源名字。jdbc/PriceDB是一个逻辑名,Pricing bean可以利用多种差异的数据库,只要在设置bean时修改一下关联就可以了。

假如利用差异的数据源,可以在设置的时候修改它。还可以成立一个default.properties文件,内里包括有你需要利用的驱动和数据库信息。譬喻,对付Oracle数据库,可以利用以下的default.properties文件:

jdbc.drivers=oracle.jdbc.driver.OracleDriver
jdbc.datasources=jdbc/Oracle|jdbc:oracle:thin:@localhost:1521:orcl

这样就成立了一个可选的数据源,它的名字是jdbc/Oracle,jdbc/PriceDB关联可以修改以便利用Oracle数据源。再次说明的是,你并不需要修改Pricing bean,你只要修改设置属性。

假定正在运行J2EE SDK设置东西,在设置东西的资源引用部门(Resource References section)配置了jdbc/PriceDB naming项目,如图6.8所示。

循速渐进学用Session Bean(五)

********图6.8**************

资源引用对话框答允你配置一个session bean的naming context

Prcing bean和HelloWorldSession bean在设置上只有一点差异,这就是你必需在JNDI Names的标志页中指定jdbc/PriceDB的别名,如图6.9所示。

循速渐进学用Session Bean(五)

********图6.9**************

JNDI names页让你配置bean利用的各类JNDI别名

#p#副标题#e#

写一个客户来测试Pricing bean是很简朴的,这个措施和你已经看到过的其它客户措施雷同。列表6.12展示了Pricing的测试客户措施。

#p#分页标题#e#

Listing 6.12 Source Code for TestPricing.java
package usingj2ee.pricing;
import java.util.*;
import javax.naming.*;
import javax.rmi.*;
public class TestPricing
{
public static void main(String[] args)
{
try
{
/** Creates a JNDI naming context for location objects */
Context context = new InitialContext();
/** Asks the context to locate an object named "Pricing" and expects the
object to implement the PricingHome interface */
PricingHome home = (PricingHome)
PortableRemoteObject.narrow(
context.lookup("Pricing"),
PricingHome.class);
/** Asks the Home interface to create a new session bean */
Pricing session = (Pricing) home.create();
/** Get a list of valid product codes */
String[] codes = session.getProductCodes();
for (int i=0; i < codes.length; i++)
{
System.out.println(codes[i]+": "+
session.getPrice(codes[i]));
}
try
{
session.getPrice("f00b4r");
}
catch (InvalidProductCodeException exc)
{
System.out.println("Got invalid product code exception: "+
exc.toString());
}
/** Destroy this session */
session.remove();
}
catch (Exception exc)
{
exc.printStackTrace();
}
}
}

最后,列表6.10展示了pricing测试客户的输出。要留意的是,无论是在源代码可能输出中,都没有处所显示该bean由一个数据库中获得数据。

循速渐进学用Session Bean(五)

***********图6.10*******************

客户并不知道session bean由数据库中获得数据

留意

可以利用以下呼吁为pricing数据库插手数据

INSERT INTO price (product_code, price) VALUES (‘A1’, 1.59);

#p#副标题#e#

问题解答

设置问题

Q:为什么设置东西不发生EAR可能JAR文件?

A:在实现类中实现的要领,有大概违反了EJB的限制可能要求。很多设置东西都带有一个选项,可测试兼容性。譬喻,在J2EE SDK中,这个选项被称为Verifier;在WebLogic的设置东西中,它被称为Check Compliance。并且对windows的查抄也大概包括有错误的信息。某些东西并不会一直弹出窗口汇报你那边错了,你可以查抄各类的log文件,它们放在J2EE SDK的子目次logs中。

Q:为什么东西不发生客户JAR文件?

A:除了Remote和Home接口类外,可以不需要其它的对象,所以无需要东西建设JAR文件。不外在大大都的环境下,客户端的JAR文件是必须的,这是因为设置东西会发生一些用作客户端开拓的实用类。

运行时的问题

Q:为什么我的客户端措施不能定位JNDI naming处事?

A:首先,要确认你的EJB处事器正在运行。接着,需要在呼吁行界说初始的naming context factory 类。查察你的EJB处事器的文档,看你是否需要其它的呼吁行选项。尚有,确定bean是被设置了的。假如利用设置东西来设置bean,然后从头启动处事器,你的处事器大概已经忘掉了谁人bean。这时你可以实验从头设置。尚有,确认客户措施请求的名字和你为bean设置的JNDI名字是一样的,必需完全一致,包罗巨细写。

Q:为什么在会见数据源时呈现错误?

A:大概没有为你的EJB处事器配置好数据源,也大概是没有正确地配置关联,即EJB利用的逻辑名和JNDI目次利用的真正数据源名。

 

    关键字:

[contact-form-7 id="17097" title="form2"]天才代写-代写联系方式