A simple EJB 3 + Servlet application

In previous post, I wrote a simple EJB3 bean invoked from a standalone java client. Standalone java client is convenient for prototyping and testing purpose. The most common way to invoke EJB is from a web app. Here I will add such a simple web app to invoke the foo-ejb module written in previous post.

Steps 1 - 5 are the same as in previous post, except in step 2, foo/Client.java is not needed here.

6. Servlet class

package foo;
import java.io.*;
import javax.ejb.EJB;
import javax.servlet.*;
import javax.servlet.http.*;

public class FooServlet extends HttpServlet {
private FooRemote foo;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<title>Servlet FooServlet</title>");
out.println("<h1>FooRemote.echo returned: " + foo.echo("From FooServlet") + "</h1>");

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
7. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

8. Make sure foo.FooRemote.class is in the webapp's classpath. For example, C:\simple-ejb\build\classes directory is included in the webapp's classpath.

9. Build the webapp to produce a simple-web.war with the following content:
10. Make sure the ejb jar is already deployed (in step 5). Start glassfish server and deploy the war file:
set JAVAEE_HOME=C:\glassfish
%JAVAEE_HOME%\bin\asadmin.bat start-domain
C:\simple-web\dist> copy simple-web.war %JAVAEE_HOME%\domains\domain1\autodeploy
Another way to deploy the war is using asadmin command:

C:\simple-web\dist> %JAVAEE_HOME%\bin\asadmin deploy simple-web.war
11. Run it by entering the following url in browser:

Update: Starting from EJB 3.1, EJB classes can be packaged in WAR files. So if the target server supports EJB 3.1, the ejb jar file in this example can be merged into WAR (typically by putting all EJB classes under WEB-INF/classes).