EJB学习文挡
文件状态
[ ] 草稿文件 [√] 正式文件 [ ] 更改正式文件 | 文件标识: |
|
当前版本: | 1.0 | |
作 者: | 宋海龙 | |
完成日期: | 2005年6月8日 |
版 本 历 史
版本/状态 | 作者 | 参与者 | 起止日期 | 备注 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
这是一个Servlet调用SessionBean,SessionBean调用CMP的小例子,功能非常简单,就是从数据库中读一条数据出来。
环境:Jbuilder9+Weblogic8.1+Oracle9i
关于环境的配置在此就不多说了,在Jb9中要把Weblogic配置好。
1. 第一步当然是数据库操作
建表,并写入一条实验数据。打开Oracle客户端工具中的SQL Plus Work Sheet小工具。输入并执行以下命令:
CREATE TABLE DDDD
(
DEPTNO number(10) PRIMARY KEY NOT NULL,
DNAME varchar(50),
LOC varchar(50)
);
INSERT INTO DDDD VALUES(20,'宋海龙','长沙');
2. 建立一个CMP
新建一个工程,工程名为cmpseservlet.
点击Next,直到它变灰,点击Finish.
建立一个EJB Module,取名字为CMPBean。
导入Schema .
这里要注意的是,应该在Weblogic Console中建立好连接池和数据源。我的连接池名为MyJDBC Connection Pool2,数据源名为MyJDBC Data Source2,与此数据源相对应的JNDI名为myjndi2。Oracle数据库所在的主机IP地址为:192.168.0.7,数据库名为:certdb,用户名为:certdb。
下面配置数据库的连接以及JNDI名。
配置成功以后,Jbulder将影射数据库的表
选择DDDD表点右键,新建Create CMP 2.0 EntityBean
选择inferfaces选项,选择local/Remote。
这样一个CMP就建成了,编译并部署这个实体Bean。当然要部署Bean的话,首先要启动Weblogic服务器才行,在此不妨先建立一个启动WeblogicServer的运行信息。点击Run菜单的Run Project,出现如下对话框
点New按钮,出现下图
在此配置一个Server
点Ok这样就配置好了服务器运行信息,即在Jb中可以直接启动服务器了。
下边我们新建一个测试程序来测试一下这个CMP
选择新建EJB Test Client
在main函数的DdddTestClient1 client = new DdddTestClient1();后面添加如下代码:
System.out.println("===========START==============");
DdddRemoteHome home = client.getHome();
try{
DdddRemote r = home.findByPrimaryKey(new java.math.BigDecimal(20));
System.out.println(r.getDeptno());
System.out.println(r.getDname());
System.out.println(r.getLoc());
System.out.println("============END=============");
}
catch(Exception ex) {
ex.printStackTrace();
}
运行测试客户端,成功后显示下列结果:
3. 建立一个Stateless SessionBean
选择File菜单的New子菜单,出现如下
新建一个SessionBean Module,名字为SesDDDD,
新建一个SessionBean,如下图
给这个SessionBean取名字为SesDDDD,
选择interfaces选项,选择local/Remote。
添加greet方法,returnType :String,interfaces选项为local/Remote。
Jb将自动在SesDDDD接口中添加greet() 方法
package cmpseservlet;
import javax.ejb.*;
import java.util.*;
import java.rmi.*;
public interface SesDDDD extends javax.ejb.EJBObject {
public String greet() throws RemoteException;
}
Jb也将自动在SesDDDDLocal接口中添加greet() 方法
package cmpseservlet;
import javax.ejb.*;
import java.util.*;
public interface SesDDDDLocal extends javax.ejb.EJBLocalObject {
public String greet();
}
修改SesDDDDBean类中greet方法,修改以后为:
public String greet() {
/**@todo Complete this method*/
try {
//get naming context
Context context = getInitialContext();
//look up jndi name
Object ref = context.lookup("DdddRemote");
//look up jndi name and cast to Home interface
DdddRemoteHome ddddRemoteHome = (DdddRemoteHome) PortableRemoteObject.
narrow(ref, DdddRemoteHome.class);
return ddddRemoteHome.findByPrimaryKey(new java.math.BigDecimal(50)).getDname().
toString();
}
catch (Exception e) {
e.printStackTrace();
}
return "=============error===========";
}
需要注意的是,要在头上加入这几个包
import javax.naming.Context;
import java.util.*;
import javax.rmi.*;
修改SesDDDDBean类中getInitialContext方法,修改以后为:
//getInitialContext()为新加的
private Context getInitialContext() throws Exception {
String url = "t3://localhost:7001";
String user = null;
String password = null;
Properties properties = null;
try {
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
properties.put(Context.PROVIDER_URL, url);
if (user != null) {
properties.put(Context.SECURITY_PRINCIPAL, user);
properties.put(Context.SECURITY_CREDENTIALS, password == null ? "" : password);
}
return new javax.naming.InitialContext(properties);
}
catch(Exception e) {
throw e;
}
}
好了,编译并部署这个SessionBean。
新建一个SessionBean的客户端测试程序:
注意选中Generate logging messages这一项。
在Step3中注意选中Create a runtime configuration,这样可以创建一个运行配置信息。
修改initialize方法以后,变成如下
public void initialize() {
long startTime = 0;
if (logging) {
log("Initializing bean access.");
startTime = System.currentTimeMillis();
}
try {
//get naming context
Context context = getInitialContext();
//look up jndi name
Object ref = context.lookup("SesDDDD");
//look up jndi name and cast to Home interface
sesDDDDHome = (SesDDDDHome) PortableRemoteObject.narrow(ref, SesDDDDHome.class);
if (logging) {
long endTime = System.currentTimeMillis();
log("Succeeded initializing bean access through Home interface.");
log("Execution time: " + (endTime - startTime) + " ms.");
}
//新加的
SesDDDD sesDDDD = sesDDDDHome.create();
System.out.println("@@@@@@@@@@@@"+ sesDDDD.greet());
System.out.println("===========test Successed=====");
}
catch(Exception e) {
if (logging) {
log("Failed initializing bean access.");
}
e.printStackTrace();
}
}
运行测试,将打出如下结果
Succeeded initializing bean access through Home interface.
Execution time: 1922 ms.
##############
宋海龙
##############
===========test Successed=====
4. 建立一个Servlet
首先要建立一个Web应用,不妨取名为myservweb
新建一个Servlet,
注意在第5步选中Create a runtime configuration。
Servlet1.java的源代码如下:
package cmpseservlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
//新加的
import java.rmi.RemoteException;
import javax.rmi.PortableRemoteObject;
import javax.naming.InitialContext;
import javax.naming.*;
import javax.ejb.Handle;
import javax.ejb.EJBMetaData;
import javax.ejb.HomeHandle;
/**
<p>Title: </p>
<p>Description: </p>
<p>Copyright: Copyright (c) 2005</p>
<p>Company: </p>
@author not attributable
@version 1.0
*/
public class Servlet1 extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//新加的
SesDDDD remote;
SesDDDDHome home;
//Initialize global variables
public void init() throws ServletException {
//以下为新加的
String url = "t3://localhost:7001";
String user = null;
String password = null;
Properties properties = null;
try {
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
properties.put(Context.PROVIDER_URL, url);
if (user != null) {
properties.put(Context.SECURITY_PRINCIPAL, user);
properties.put(Context.SECURITY_CREDENTIALS,
password == null ? "" : password);
}
InitialContext ic = new InitialContext(properties);
Object objref = ic.lookup("SesDDDD");
System.out.println(" == Servlet MySchedule lookup ok");
home = (SesDDDDHome) PortableRemoteObject.narrow(objref, SesDDDDHome.class);
remote = home.create();
System.out.println(" == Servlet home.create ok");
}
catch (Exception e) {
e.printStackTrace();
}
//以上为新加的
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
//以下一行为新加的
String str = (String) remote.greet();
out.println("<html>");
out.println("<head><title>Servlet1</title></head>");
out.println("<body bgcolor=/"#008000/">");
//以下一行为新加的
out.println(str);
out.println("<p>The servlet has received a GET. This is the reply.</p>");
out.println("</body></html>");
}
//Clean up resources
public void destroy() {
}
}
运行Servlet1显示页面如下:
源代码见:cmpseservlet.rar