一边看书,一边看网上前辈的文章做实验 书上固然理论多一些,网上的文章实践多很多,受益匪浅
1. bean的构造方法
一个组件至少要由
3
个
java
类构成。
home
接口:定义了创建、删除和定位
ejb
组件的方法;
remote
接口:用于定义了客户机程序可以在
bean
中调用的方法;
实现类:则用于实现
home
接口中定义的组件生命期方法以及
remote
接口中定义的商务方法。
2. ejb
的部署
首先启动
j2ee
服务器
j2ee -verbose
打开一个新的命令行窗口,输入:
deploytool
稍等片刻,出现部署窗口
1
)新建一个服务器端应用程序:选择
file > new > application
2
)
添加
ejb
:选择
file > new > enterprise bean…
然后,按照向导开始部署
ejb
3
)在
contents
栏中,需要添加所有必须的
class
文件,点击
“edit…”
,添加编译好的
3
个
class
文件
4
)向导提示选择
ejb
类型。
ejb 2
共有
3
种
bean
:
session bean
,
entity bean
和
message-driven bean
,我们编写的是
session bean
,并且选择
stateless
,表示该
session bean
是无状态会话
bean
。
5
)注意我们没有编写
local home
和
local interface
,因此让它们保持为空
6)
主窗口多了一个
ejb1
,选中它,我们还需要在
jndi names
一栏填入
ejb/hello
,客户端将根据
jndi name
来查找我们编写的
bean
7
)选择
file > save
,保存我们创建的
application
。接下来,我们将把这个
application
部署到服务器上。
8
)选择
tools > deploy
,出现
deploy
向导
对话框提示我们将要部署的应用程序是
hello
,目标服务器是
localhost
,然后,一定要选中
return client jar
,因为要从客户端访问部署在
j2ee sdk
服务器上的应用,必须要有这个
jar
包。如果使用其他服务器,也需要相应的
jar
包,如
jboss
客户端需要
jbossall-client.jar
。这里,我们选择好存放
client jar
的目录,然后
next
即可。
最后,
j2ee
服务器开始编译并部署我们的
hello bean
当进度条填满时,表示部署成功!
3.
编写客户端程序访问
ejb
编写一个基于控制台的
application
客户端来访问
ejb
:
// client.java
import javax.naming.*;
import javax.rmi.*;
public class client {
public static void main(string[] args) throws exception {
// init context:
c ctx = new initialcontext();
// 通过 jndi 查找 hellobean:
object obj = ctx.lookup("ejb/hello");
// 获得 home object:
hellohome home = (hellohome)portableremoteobject.narrow(obj, hellohome.class);
// 创建 ejb object:
hello hello = home.create();
// 调用商业方法 :
string words = hello.say();
system.out.println(words);
}
}
import javax.naming.*;
import javax.rmi.*;
public class client {
public static void main(string[] args) throws exception {
// init context:
c ctx = new initialcontext();
// 通过 jndi 查找 hellobean:
object obj = ctx.lookup("ejb/hello");
// 获得 home object:
hellohome home = (hellohome)portableremoteobject.narrow(obj, hellohome.class);
// 创建 ejb object:
hello hello = home.create();
// 调用商业方法 :
string words = hello.say();
system.out.println(words);
}
}
然后打开控制台,先设置好
classpath
,主要是将部署时生成的
helloclient.jar
添加到
classpath
中:
c:client>set classpath=%classpath%;c:client
helloclient.jar
然后编译:
c:client>javac client.java
运行:
c:client>java client
屏幕输出:
hello, world.
我们的第一个
ejb
终于调用成功!
转载于:https://blog.51cto.com/36225/4421