ejb2 写一个简单的demo
时间: 2023-07-29 12:07:15 浏览: 167
好的,以下是一个简单的 EJB2 示例:
1. 创建一个接口 MyRemoteInterface,定义一个方法 sayHello:
```java
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
public interface MyRemoteInterface extends EJBObject {
public String sayHello() throws RemoteException;
}
```
2. 创建一个实现 MyRemoteInterface 接口的 bean MyBean:
```java
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
public class MyBean implements SessionBean, MyRemoteInterface {
private static final long serialVersionUID = 1L;
public void ejbCreate() throws CreateException {
}
public String sayHello() throws RemoteException {
return "Hello World!";
}
public void ejbRemove() throws EJBException, RemoteException {
}
public void ejbActivate() throws EJBException, RemoteException {
}
public void ejbPassivate() throws EJBException, RemoteException {
}
public void setSessionContext(SessionContext arg0) throws EJBException, RemoteException {
}
}
```
3. 在 ejb-jar.xml 文件中声明 MyBean:
```xml
<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>MyBean</ejb-name>
<home>MyRemoteInterface</home>
<remote>MyRemoteInterface</remote>
<ejb-class>MyBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
```
4. 部署到服务器上,可以通过 JNDI 查找 MyBean 并调用 sayHello 方法:
```java
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class MyClient {
public static void main(String[] args) throws NamingException, RemoteException {
InitialContext ctx = new InitialContext();
MyRemoteInterface myBean = (MyRemoteInterface) ctx.lookup("MyBean/remote");
System.out.println(myBean.sayHello());
}
}
```
以上就是一个简单的 EJB2 示例,它展示了如何创建一个远程 EJB,并在客户端调用它的方法。
阅读全文