Home > Articles > Programming > Java

  • Print
  • + Share This
  • 💬 Discuss

A "Hello World" Session Bean

The structure of Enterprise JavaBeans can be a little awkward to work with at first, but after you get a feel for the structure, EJBs aren't too bad. Fortunately, you can become familiar with the basic EJB structure without worrying about database connections or transactions. To do this, start with a good old-fashioned "Hello World" bean.

When you design EJB applications, you might wonder whether you should start with the bean and then create the interfaces, or start with the interfaces and then create the bean. Your best bet here is to start with the interfaces. If you can't describe how a client is going to use the bean, you aren't ready to write it.

Creating the Remote Interface

Listing 6.1 shows the HelloWorldSession interface, which is the Remote interface for the "Hello World" session bean.

Listing 6.1 Source Code for HelloWorldSession.java

package usingj2ee.hello;

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

/** Defines the methods you can call on a HelloWorldSession object */

public interface HelloWorldSession extends EJBObject
{

/** Returns the session's greeting */
    public String getGreeting() throws RemoteException;

/** Changes the session's greeting */
    public void setGreeting(String aGreeting) throws RemoteException;

}     
						

Creating the Home Interface

You might recall from Chapter 5, "Overview of Enterprise JavaBeans," that the Home interface for a session bean contains methods for creating a new session. For the "Hello World" example, there are two different create methods, one that takes no parameters and a second that allows you to provide your own greeting. Listing 6.2 shows the HelloWorldSessionHome interface.

Listing 6.2 Source Code for HelloWorldSessionHome.java

package usingj2ee.hello;

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

/** Defines the methods for creating a HelloWorldSession */

public interface HelloWorldSessionHome extends EJBHome
{

/** Creates a HelloWorldSession bean with default settings */
    public HelloWorldSession create() throws RemoteException, CreateException;

/** Creates a HelloWorldSession bean with a specific initial greeting */
    public HelloWorldSession create(String aGreeting)
        throws RemoteException, CreateException;

}     
						

Creating the Implementation Class

The interfaces are the easy part of EJB development. The session bean requires a bit more work. When you write a session bean, there are a few methods that you must include in the bean to satisfy the EJB container. These extra methods are setSessionContext, ejbRemove, ejbActivate, and ejbPassivate. In addition, when you implement your create methods, you must name them ejbCreate instead of just create.

Note

Keep in mind that the container calls these methods. When you use a method in the Home interface to create a new EJB, the container ends up invoking your ejbCreate method. Likewise, when you remove a bean, the container invokes the ejbRemove method to tell the bean it has been removed.

Listing 6.3, the implementation for the HelloWorldSession and HelloWorldSessionHome interfaces, should make things clearer.

Listing 6.3 Source Code for HelloWorldSessionImpl.java

package usingj2ee.hello;

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

/** The implementation class for the HelloWorldSession bean */

public class HelloWorldSessionImpl implements SessionBean
{
/** Holds the session's greeting */
    protected String greeting;

/** The session context provided by the EJB container. A session bean must
    hold on to the context it is given. */

    private SessionContext context;

/** An EJB must have a public, parameterless constructor */     

    public HelloWorldSessionImpl()
    {
    }

/** Called by the EJB container to set this session's context */

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

/** Called by the EJB container when a client calls the create() method in
    the Home interface */

    public void ejbCreate()
        throws CreateException
    {
        greeting = "Hello World!";
    }

/** Called by the EJB container when a client calls the
    create(String) method in the Home interface */     

    public void ejbCreate(String aGreeting)
        throws CreateException
    {
        greeting = aGreeting;
    }

/** Called by the EJB container to wake this session bean up after it
    has been put to sleep with the ejbPassivate method. */

    public void ejbActivate()
    {
    }

/** Called by the EJB container to tell this session bean that it is being
    suspended from use (it's being put to sleep). */

    public void ejbPassivate()
    {
    }

/** Called by the EJB container to tell this session bean that it has been
    removed, either because the client invoked the remove() method or the
    container has timed the session out. */

    public void ejbRemove()
    {
    }

/** Returns the session's greeting */

    public String getGreeting()
    {
        return greeting;
    }

/** Changes the session's greeting */

    public void setGreeting(String aGreeting)
    {
        greeting = aGreeting;
    }
}     
						

All you wanted to do was make a bean with getGreeting and setGreeting methods and you ended up with two Java interfaces and an implementation class with eight methods. Enterprise JavaBeans obviously involve a lot of extra work, and for small projects, it might seem like you're doing almost as much work creating EJB methods as you are implementing your business logic. As your application grows, however, you'll find that the amount of work you're putting into your EJBs will begin to pay off as it becomes easier to mix objects together to implement new features.

Some Integrated Development Environments (IDEs) provide some support for creating Enterprise JavaBeans. Mostly, these IDEs generate the required methods and some helper methods. Unfortunately, most of the tools that provide these utilities are the expensive "Enterprise versions." The Kawa Enterprise IDE from Allaire (http://www.allaire.com) is reasonable inexpensive and has good EJB support. Hopefully, you will soon find some free tools for creating EJBs as well.

Tip

Because you end up with so many files when writing EJB applications, it is important to have a consistent naming convention for your classes. The Remote and Home interfaces are usually named XXX and XXXHome where XXX is the name of the bean. The implementation class is usually named XXXBean or XXXImpl. You might also consider naming the implementation class XXXEB or XXXSB depending on whether the bean is a session bean or an entity bean. No matter how you decide to name your classes, be consistent. It makes it easier when there are multiple developers.

Note

This book uses the XXX for the Remote interface, XXXHome for the Home interface and XXXImpl for the implementation. It also refers to the bean using the Remote interface name. If the Remote interface is called ShoppingCart, the Home interface is ShoppingCartHome, the implementation is in ShoppingCartImpl, and the bean is referred to as the ShoppingCart bean.

Deploying the Bean

One of the other aspects of Enterprise JavaBeans that might be difficult to get used to is that you don't run EJBs, you deploy them. You use a packaging tool of some kind to create a JAR file containing the EJB classes, some XML deployment descriptor files, and some helper classes that are specific to the container you're using.

Although you'll get a more thorough introduction to EJB deployment in Chapter 10, "Mapping Objects to a Relational Database," you really can't go on learning about EJBs without writing your own beans and trying them out.

Each EJB vendor supplies its own custom deployment tool. Although some tools are easier to use than others, most of them follow the same general pattern. In this chapter, you'll see how to package the bean and deploy it using the Java 2 Enterprise Edition SDK (J2EE SDK) from Sun. The deployment tool for the J2EE SDK is called deploytool and in the bin directory of the SDK.

After starting deploytool, select New Application from the File menu. In the New Appli cation dialog box, enter the name of the EAR (Enterprise Archive) file you want to create. An EAR file is a JAR file for J2EE applications. Figure 6.1 shows the dialog box with the information for the Hello World session bean filled in.

Figure 6.1. Enter the name of the EAR file you want to create.

Next, from the File menu, select New Enterprise Bean. You can also change the display name for the JAR if you like.

In the New Enterprise Bean Wizard, click the Add button on the lower-right section next to the Contents area. You should see a dialog box like the one in Figure 6.2. The dialog box allows you to select the class files that make up your EJB. In this case, select the HelloWorldSession.class, HelloWorldSessionHome.class, and HelloWorldSessionImpl. class files and click the Add button.

Figure 6.2. Select the files that make up the Enterprise JavaBean.

Next, tell deploytool what classes to use for the Enterprise Bean class, the Home interface, and the Remote interface. You can also give the bean a display name, which is only used within deploytool. You must also tell the tool whether the bean is a session bean or an entity bean, and if it is a session bean, whether it is stateless or stateful. Figure 6.3 shows the configuration entries for the Hello World bean.

Figure 6.3. Specify which classes implement which parts of the EJB.

Because the Hello World example is a simple session bean that doesn't have any other configuration requirements, you can continue to click Next and then click Finish when you have the opportunity. You should now be ready to deploy the bean.

Make sure the EJB server is running before you deploy to it. You might also need to tell deploytool which server to use by selecting Add from the Server menu option. After the server is running, select Deploy Application from the Tools menu. You should see a dialog box like the one shown in Figure 6.4.

Figure 6.4. Select the server where you want to deploy and generate a client JAR file.

When you deploy an EAR file or a JAR file, you usually end up generating a number of additional classes that the server needs to handle network access to the bean. For servers such as BEA's WebLogic server, you generate these classes when you create the JAR file. For the J2EE SDK, you generate the classes when you deploy the JAR file. Many EJB servers also generate a client JAR file, which contains classes that a client needs to access the EJB. Not all servers need to generate a client JAR file, however. WebLogic, for example, manages to load important classes dynamically at runtime without needing a special JAR file. The J2EE SDK, however, does require a client JAR file. Make sure you tell deploytool to generate a client JAR file. In this case, the client JAR is called helloClient.jar.

Finally, tell deploytool what JNDI name you want the EJB to be known by. Again, this setting is something that some servers let you configure into the JAR file. The J2EE SDK doesn't ask for the name until deploy time, however, allowing you to deploy the same bean to different servers under different names. Figure 6.5 shows the dialog box that allows you to set the name for the bean.

Figure 6.5. Specify the JNDI name that is used to access the EJB.

Creating a Client to Access the Session Bean

After all the work you had to do to implement and deploy a session bean, you might expect that writing a client is equally painful. Fortunately, that's not the case. It's easy to write a client program to use an Enterprise JavaBean.

The only tricky part about using an EJB is getting a reference to the EJB's Home interface. After you have a reference to the Home interface, you just use one of the create methods to create an instance of the bean and then invoke methods on the bean's Remote interface.

The first thing you need to do, of course, is get a reference to the JNDI naming context, which is your interface to the naming system. You use the naming system to locate EJBs and other objects. The easiest way to get a reference to the naming context is just to create an InitialContext object, like this:

						
Context namingContext = new InitialContext();

Depending on your application server, you might need to either provide a Properties object with additional information or define a system property when you run your client. The reason for the extra information is that the JNDI API (the Java Naming API) provides an interface into a naming system but doesn't provide the naming service itself. If you are running WebLogic, for example, you use the WebLogic naming service. Likewise, if you're running JRun, you use the JRun naming service. JNDI uses something called a context factory to create a Context object. You just need to tell it what class to use as the context factory.

If you're running WebLogic, the context factory is called weblogic.jndi.WLInitialContextFactory. You can specify it on the command line, like this:

						
java -Dnaming.factory.initial=weblogic.jndi.WLInitialContextFactory

You can also specify the context factory via a Properties object, like this:

						
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory");

Context context = new InitialContext(p);

The advantage of the Properties object is that you don't need to do anything special on the command line. The disadvantage is that your code only works with a WebLogic server. Although you might only use one brand of server, it's still a good idea to keep vendor- specific information out of your source code whenever possible.

Now that you have the naming context, you use the lookup method to locate the EJB you want. For example, if you deployed the HelloWorldSession bean with a JNDI name of "HelloWorld", the following code would locate the bean's Home interface for you:

						
HelloWorldSessionHome home = (HelloWorldSessionHome)
    PortableRemoteObject.narrow(
        context.lookup("HelloWorld"),
        HelloWorldSessionHome.class);

When you use EJB, you can't cast remote references using the standard Java cast operator. Instead, you must use PortableRemoteObject.narrow. EJB uses a special form of RMI called RMI-IIOP that requires this special syntax for casting.

Remember, too, that you never locate EJB Remote interfaces, only Home interfaces. You then use the create and find methods in the Home interface to get the Remote interface.

You will learn much more about JNDI in Chapter 18, "JNDI-Java Naming and Directory Interface."

Listing 6.4 shows a complete client program that creates a HelloWorldSession bean first using the default create method, and then again by using the create(String) version.

Listing 6.4 Source Code for TestHello.java

package usingj2ee.hello;

import java.util.*;
import javax.naming.*;
import javax.rmi.*;

public class TestHello
{

    public static void main(String[] args)
    {
        try
        {

/** Creates a JNDI naming context for location objects */
            Context context = new InitialContext();

/** Asks the context to locate an object named "HelloWorld" and expects the
    object to implement the HelloWorldSessionHome interface */
            HelloWorldSessionHome home = (HelloWorldSessionHome)
                PortableRemoteObject.narrow(
                    context.lookup("HelloWorld"),
                    HelloWorldSessionHome.class);
/** Asks the Home interface to create a new session bean */
            HelloWorldSession session = (HelloWorldSession) home.create();

            System.out.println("The default greeting is: "+
                session.getGreeting());

            session.setGreeting("Howdy!");

            System.out.println("The greeting is now: "+session.getGreeting());

/** Destroy this session */
            session.remove();

/** Now create a session with a different greeting */
            session = (HelloWorldSession) home.create("Guten Tag!");

            System.out.println("Created a new session with a greeting of: "+
                session.getGreeting());

/** Destroy this session */
            session.remove();

        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}         
						

Figure 6.6 shows the output from the TestHello program.

Figure 6.6. The TestHello class exercises the capabilities of the HelloWorldSession bean.

Creating a Stateless Session Bean

From a programming standpoint, it's just as easy to create a stateless session bean as it is to create a stateful one. The only real difference, other than changing a setting in the deployment tool, is in the initial design of the bean. A stateless session bean doesn't remember anything from one method invocation to the next, so any information the bean requires must be passed in from the client. Although it's true that a stateless session bean doesn't remember session-oriented data, you can store data in a stateless session bean. You just can't store client-specific data.

In the HelloWorldSession example bean, the bean had a greeting string that it remembered between method invocations. For instance, you called the setGreeting method to change the greeting, and then when you called getGreeting, the session remembered the greeting you had saved.

Listing 6.5 shows the Remote interfaces for a stateless version of the "Hello World" session bean.

Listing 6.5 Source Code for StatelessHello.java

package usingj2ee.hello;

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

/** Defines the methods you can call on a StatelessHello object */

public interface StatelessHello extends EJBObject
{

/** Returns a greeting for the named object */
    public String greet(String thingToGreet) throws RemoteException;

}

In this example, the Remote interface provides only a greet method that takes an item and returns a greeting. For example, if you pass "World" as the thing to greet, the greet method returns "Hello World!".

Listing 6.6 shows the Home interface for the StatelessHello bean.

Listing 6.6 Source Code for StatelessHelloHome.java

package usingj2ee.hello;

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

/** Defines the methods for creating a StatelessHelloWorld */

public interface StatelessHelloHome extends EJBHome
{

/** Creates a StatelessHello session bean. A stateless session bean
    can't have a create method that takes parameters. */
    public StatelessHello create() throws RemoteException, CreateException;

}

A stateless session bean can only have one create method and it can't take any parameters. Although it might seem strange to not allow parameters to the create method, it makes sense when you think about what it means for the session bean to be stateless. The bean must not remember anything about a particular client. In fact, the container might, for performance reasons, let a different session handle a particular client's method invocations from time to time. Because the session isn't supposed to remember anything about a particular client, there shouldn't be any problem in letting another bean handle the load.

Now, if the bean's create method took any parameters, that would be saying that one instance of the session bean might behave differently than another because you've supplied a different value to the create method.

It's as easy to implement a stateless session bean as it is to implement a stateful bean. Listing 6.7 shows the StatelessHelloImpl class, which implements the Remote and Home interfaces.

Listing 6.7 Source Code for StatelessHelloImpl.java

package usingj2ee.hello;

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

/** The implementation class for the StatelessHello bean */

public class StatelessHelloImpl implements SessionBean
{
/** The session context provided by the EJB container. A session bean must
    hold on to the context it is given. */
    private SessionContext context;

/** An EJB must have a public, parameterless constructor */

    public StatelessHelloImpl()
    {
    }

/** Called by the EJB container to set this session's context */

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

/** Called by the EJB container when a client calls the create() method in
    the Home interface */
    public void ejbCreate()
        throws CreateException
    {
    }

/** Called by the EJB container to wake this session bean up after it
    has been put to sleep with the ejbPassivate method. */

    public void ejbActivate()
    {
    }

/** Called by the EJB container to tell this session bean that it is being
    suspended from use (it's being put to sleep). */

    public void ejbPassivate()
    {
    }     

/** Called by the EJB container to tell this session bean that it has been
    removed, either because the client invoked the remove() method or the
    container has timed the session out. */

    public void ejbRemove()
    {
    }

/** Returns a greeting for the named object */

    public String greet(String thingToGreet)
    {
        return "Hello "+thingToGreet+"!";
    }
}     
					

Note

The deployment procedure for the stateless session bean is almost identical to the deployment procedure for the stateful bean. Just make sure you indicate that the bean is stateless. You might need to check a box such as Stateless or make sure a box such as Manages Conversational State is unchecked.

Finally, Listing 6.8 shows a client that tests the stateless session bean.

Listing 6.8 Source Code for TestStatelessHello.java

package usingj2ee.hello;

import java.util.*;
import javax.naming.*;
import javax.rmi.*;
public class TestStatelessHello
{
    public static void main(String[] args)
    {
        try
        {     

/** Creates a JNDI naming context for location objects */
            Context context = new InitialContext();

/** Asks the context to locate an object named "HelloWorld" and expects the
    object to implement the HelloWorldSessionHome interface */

            StatelessHelloHome home = (StatelessHelloHome)
                PortableRemoteObject.narrow(
                    context.lookup("StatelessHello"),
                    StatelessHelloHome.class);
/** Asks the Home interface to create a new session bean */
            StatelessHello session = (StatelessHello) home.create();

            System.out.println(session.greet("World"));
            System.out.println(session.greet("Solar System"));
            System.out.println(session.greet("Universe"));

/** Destroy this session */
            session.remove();
        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}     
					

Figure 6.7 shows the output from the TestStatelessHello program.

Figure 6.7. The TestStateless Hello class exercises the capabilities of the StatelessHello bean.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus