EJB的名聲很不好,尤其在Spring框架出現以後,而EJB3似乎脫胎換骨了。而我現在學習的仍然是EJB2,原因是EJB3的書很難找。暑假時大概把《精通EJB》和《EJB》這兩本書看過一下,現在想復習,加深理解,就從第一個HelloWorld開始。
文件結構:
E:.
│ build.XML
│
└─src
├─META-INF
│ application.XML
│ ejb-jar.XML
│ jboss.XML
│
├─powerwind
│ ClIEntServlet.Java
│ Hello.Java
│ HelloBean.Java
│ HelloHome.Java
│
└─WEB-INF
jboss-web.XML
web.XML
ant文件
build.XML
todir="${jboss.home}/server/default/deploy" />
Java源文件
Hello.Java
package powerwind;
import Java.rmi.RemoteException;
import Javax.ejb.EJBObject;
publicinterface Hello extends EJBObject {
public String sayHello() throws RemoteException;
}
HelloHome.Java
package powerwind;
import Java.rmi.RemoteException;
import Javax.ejb.CreateException;
import Javax.ejb.EJBHome;
publicinterface HelloHome extends EJBHome {
public Hello create() throws RemoteException, CreateException;
}
HelloBean.Java
package powerwind;
import Java.rmi.RemoteException;
import Javax.ejb.EJBException;
import Javax.ejb.SessionBean;
import Javax.ejb.SessionContext;
publicclass HelloBean implements SessionBean {
private SessionContext context;
publicvoid ejbCreate() throws EJBException, RemoteException {
}
publicvoid ejbActivate() throws EJBException, RemoteException {
}
publicvoid ejbPassivate() throws EJBException, RemoteException {
}
publicvoid ejbRemove() throws EJBException, RemoteException {
}
publicvoid setSessionContext(SessionContext newContext)
throws EJBException {
context = newContext;
}
public String sayHello() throws EJBException {
return"Hello from ejb";
}
}
用於測試的Servlet
ClIEntServlet.Java
package powerwind;
import Java.io.IOException;
import Java.io.PrintWriter;
import Javax.naming.InitialContext;
import Javax.rmi.PortableRemoteObject;
import Javax.servlet.ServletException;
import Javax.servlet.http.HttpServlet;
import Javax.servlet.http.HttpServletRequest;
import Javax.servlet.http.HttpServletResponse;
publicclass ClIEntServlet extends HttpServlet {
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/Html");
PrintWriter out = response.getWriter();
String message = null;
try {
InitialContext ic = new InitialContext();
Object obj = ic.lookup("HelloEJB");
HelloHome home = (HelloHome) PortableRemoteObject.narrow(obj,
powerwind.HelloHome.class);
Hello hello = home.create();
message = hello.sayHello();
} catch (Exception e) {
e.printStackTrace();
}
out.println(message);
out.flush();
out.close();
}
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}