After seeing the question arise so many times about how to bind an EJB to the env/ejb/nameofbean context I have put together a quick tutorial to show that. the two included files are the complete ear file that does this, and a text file explaining what is happening. I didnt get into how to actually use ant, or create jar files, but if there is a call for that I can do that also. Hope this helps some people.
 
Al
 
Simple Hello World Jboss Tutorial

The purpose of this tutorial is to give a simple example of calling session EJB from a 
servlet. 

Step 1:  Create the EJB

We will create a simple stateless session ejb, with a single method sayHello. First 
let us create the home interface as follows, and save it as simple/helloHome.java

package simple;

import java.rmi.*;
import javax.ejb.*;

public interface helloHome extends EJBHome {
  public helloRemote create() throws RemoteException, CreateException;
}

then we will create the remote interface which allows us to acces the sayHello method 
on our instantiated ejb in the container. Name this file helloRemote.java

package simple;

import java.rmi.*;
import javax.ejb.*;

public interface helloRemote extends EJBObject {
  public String sayHello() throws RemoteException;
}

finally we will create our bean class and name it simple/hello.java

package simple;

import java.rmi.*;
import javax.ejb.*;

public class hello implements SessionBean {
  private SessionContext sessionContext;

  public void ejbCreate() {
  }

  public void ejbRemove() {
  }

  public void ejbActivate() {
  }

  public void ejbPassivate() {
  }

  public void setSessionContext(SessionContext context) {
    sessionContext = context;
  }

  public String sayHello() {
    return "Hello World!";
  }
}

now we will create the deployment descriptor for this ejb. Save this file as 
META-INF/ejb-jar.xml

<?xml version="1.0" encoding="Cp1252"?>

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN' 
'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>

<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>hello</ejb-name>
      <home>simple.helloHome</home>
      <remote>simple.helloRemote</remote>
      <ejb-class>simple.hello</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
  <assembly-descriptor>
    <container-transaction>
      <method>
        <ejb-name>hello</ejb-name>
        <method-name>*</method-name>
      </method>
      <trans-attribute>Required</trans-attribute>
    </container-transaction>
  </assembly-descriptor>
</ejb-jar>

finally we will create the session.jar which contains all our EJB information. 

Since this is a simple example I did not use ant to make the project. I use Jbuilder 
4, and simply made archives. You should create a jar file that contains the following 
structure

session.jar 
- META-INF
- ejb-jar.xml
- simple
- helloHome.class
- helloRemote.class
- hello.class

this completes the EJB creation phase. 


Step 2: Create the web application

This web application will be very simple, consisting of a single JSP file, and a 
servlet. The intent here is to keep it very simple so that the user can understand 
what is going on. 

First let us create a simple index.jsp this file will simply use a <jsp:forward ... /> 
call to forward the remote user to the hello servlet. It looks like the following.

<%@ page language="java" %>
<jsp:forward page="/hello" />

name this file index.jsp

next we will create our servlet. The servlet will get an initial context, and use our 
hello bean. This file should be saved as simple/helloServlet.java

package simple;

import java.io.*;
import java.util.*;

import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.*;
import javax.servlet.http.*;

import simple.*;

public class helloServlet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html";

    /**Initialize global variables*/

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    /**Process the HTTP Get request*/
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException {
        doPost(request, response);
    }

    /**Process the HTTP Post request*/
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
        InitialContext ctx = null;

        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Simple Hello</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Simple Hello World Call</h1>");
        try {
            //Lets get our context
            ctx = new InitialContext();

            //then do the lookup on the home object
            Object o = ctx.lookup("java:comp/env/ejb/hello");
            helloHome home = (helloHome)PortableRemoteObject.narrow(o, 
helloHome.class);

            //finally create an instance of the bean
            simple.helloRemote bean = home.create();

            //And make the call to sayHello
            out.println(bean.sayHello());
        }
        catch(Exception e) {
            throw new ServletException("Some error occurred " + e.getMessage());
        }
        finally {
            try {
                ctx.close();
            }
            catch(Exception e) {}
        }
        out.println("</body></html>");
    }

    /**Clean up resources*/
    public void destroy() {
    }
}

we now need to create several files to be used by our web container. The first is the 
web.xml file which is saved in WEB-INF/web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app>

<!-- Servlets and mappings -->
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>simple.helloServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

<!-- Welcome files -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

<!-- ejb references -->
    <ejb-ref>
        <ejb-ref-name>env/ejb/hello</ejb-ref-name>
        <ejb-ref-type>Session</ejb-ref-type>
        <home>simple.helloHome</home>
        <remote>simple.helloRemote</remote>
    </ejb-ref>
</web-app>

The first thing to talk about is our servlet mapping. We map our servlet class so that 
requests to /hello will be handled by our servlet. This means that our simple 
index.jsp will just call the helloservlet now. 


Also notice that we have included a reference to our ejb with a name of env/ejb/hello. 
This will allow our servlet to look up our bean as "java:comp/env/ejb/hello"  but how 
exactly does the name get bound to that? That is handled in our jboss-web.xml which is 
saved as WEB-INF/jboss-web.xml

<?xml version="1.0"?>
<jboss-web>

    <ejb-ref>
        <ejb-ref-name>env/ejb/hello</ejb-ref-name>
        <jndi-name>hello</jndi-name>
    </ejb-ref>

</jboss-web>

Notice here that the jndi name used here matches the jndi name that is in our 
ejb-jar.xml file that we created earlier. And that the ejb-ref-name is identical to 
the name used in our web.xml file. 

Now lets create the web app war file. This should be saved as webapp.war and should 
have the following structure.

Webapp.war
- WEB-INF
- web.xml
- jboss-web.xml
- classes
        - simple
                - helloServlet.class
                - helloHome.class
                - helloRemote.class
        - index.jsp

We will now prepare an application.xml which will describe our enterprise application. 
This file should be saved in META-INF/application.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<application>
        <display-name>Simple Hello</display-name>
        <description>
        </description>
        <module>
        <web>
                <web-uri>webapp.war</web-uri>
                <context-root>/</context-root>
        </web>
        </module>

        <module>
                <ejb>session.jar</ejb>
        </module>

</application>

Our web application has two modules, our webapp and our session ejb. 

Notice that in this case the web application is pointed at the default context of / so 
any calls to http://urltojboss-tomcat/ will result in our index.jsp being called and 
then a forward to our hello servlet. If you want to use something like 
http://urltojboss-tomcat/hello then you should change the <context-root> to /hello 
from /.

We will now prepare our enterprise archive. You can name this whatever you chose as 
long as the extension is ear. I named mine hello.ear. the structure is as follows. 

Hello.ear
        - META-INF
                - application.xml
        - session.jar
        - webapp.war

copy this file over to your jboss/deploy directory and it should deploy automatically. 

Now you can call your application like this....

http://urltojboss:8080/

(This assumes you have not changed the default jboss configuration. If you have then 
use the correct port that it is listening to. You should see something like the 
following displayed:

Simple Hello World Call

Hello World!

I hope this helps some people out. It was a quick tutorial, mainly aimed at showing 
how to bind the env/ejb/nameofbean. I didn't attempt to discuss how to actually build 
the files, or use some automated tool like ant. If there is a call for that I will 
expand this tutorial to include such things. 

Al

hello.ear

Reply via email to