# Step 3: Define the Session Bean

In this step you will create the (stateless) session bean Hello. The session bean will have one method, hello, which is invoked by a client application and takes a visitor's name as an argument. The session bean in turns calls the Visit entity bean to determine whether this visitor is known, and if so, how many times the visitor has visited before, and returns an appropriate greeting to the client application. In other words, the session bean implements the business logic that governs a particular interaction.

The tasks in this step are:

- To Create a Session Bean
- To Reference the Entity Bean
- To Add an ejb-local-ref Tag
- To Add a Component Method
- Build and Deploy

To Create a Session Bean

1. Right-click the hello folder in the Application tab, and select New-->Session Bean.
2. Enter the file name HelloBean.ejb.
3. Click Create.

The file HelloBean.ejb should now appear in the Application tab above VisitBean.ejb in the hello folder. Also notice that the bean opens in Design View, and that the Property Editor shows that a number of properties have been automatically set. In particular notice that the remote business interface, set in the Bean class name property, is Hello, the remote home interface, set in the Home class name property, is HelloHome, and that the remote JNDI name is ejb.HelloRemoteHome. JNDI naming is discussed in more detail below.

When you go to Source View, you will notice that an ejbCreate method with no arguments has already been defined. This method is called to create a new session bean instance. A stateless session bean, like the Hello bean, will always have this ejbCreate method. Unlike entity beans, a stateless session bean cannot have additional ejbCreate methods.

To Reference the Entity Bean

The Hello bean will use the Visit bean to determine if a visitor is new or returning. In order for the Hello bean to invoke the Visit bean's methods, it must first locate and obtain a reference to the bean's home interface. To do so, you modify the Hello bean's ejbCreate method to include code that obtains this reference.

1. Select the Source View tab.
2. Locate the ejbCreate method in HelloBean.ejb, and modify its definition as shown in red below:

         public void ejbCreate() {
            try {
               javax.naming.Context ic = new InitialContext();
               visitHome = (VisitHome)ic.lookup("java:comp/env/ejb/MyVisitBean");
            }
            catch (NamingException ne) {
               throw new EJBException(ne);
            }
         }

3. Locate the import section at the top of the file and add the following import statements, or use Alt+Enter when prompted by the IDE to automatically add these import statements:

       import javax.naming.InitialContext;
       import javax.naming.NamingException;

4. Go to the beginning of the class definition and define visitHome as shown in red below:

       public class HelloBean
         extends GenericSessionBean
         implements SessionBean
       {
         private VisitHome visitHome;

         public void ejbCreate() {
         ...

When the ejbCreate method executes, the Visit bean is looked up using JNDI API, a standard naming and directory API. This API is described in more detail below. (More information can also be found in many books on J2EE and at http://java.sun.com.) Notice that the lookup method returns a reference to the local home interface of the Visit bean, which is called VisitHome (as you saw in the previous step), and stores this reference in the visitHome variable.

To Add an ejb-local-ref Tag

The Java Naming and Directory Interface (JNDI) API provides a set of methods to map an easy-to-remember name to the actual location of an object. It works essentially the same as other naming services you are already familiar with, such as the telephony naming system. A phone directory lists phone numbers, which are easy-to-remember names to call certain telephones. Each phone number is mapped to an actual phone somewhere, such that when you call the number the appropriate phone starts ringing. The telephone company does this mapping for you; all you need to remember is the telephone number and the context in which this phone number is relevant, meaning whether you are calling locally and don't need an area code, whether you do need an area code, or whether you are calling internationally and need a country code too.

In the above ejbCreate method the name ejb/MyVisitBean is used to refer to the Visit bean. To make the lookup procedure successful, you must map this name to the actual EJB location, in this case the Visit bean. This mapping is done in an XML file called the deployment descriptor. However, in WebLogic Workshop you don't modify the deployment descriptor directly but use ejbgen tags inserted in the ejb file instead. To map this name to the actual Visit bean definition, you need to insert an ejbgen:ejb-local-ref tag.

1. Ensure that the Hello bean is displayed in Design View.
2. Right-click the Design View, and select Insert EJB Gentag-->ejb-local-ref. A new ejbgen:ejb-local-ref section appears in the Property Editor.
3. In the Property Editor, make the following changes:

By adding this tag, you specify that the reference ejb/MyVisitBean as used in the Hello bean's code maps to an entity bean with the JNDI name ejb.VisitLocalHome, the local business interface name Visit, and the local home interface VisitHome. (Remember that you defined these names for the entity bean in the previous step.) Notice that this mapping uses another JNDI name reference, ejb.VisitLocalHome, which is the Visit bean reference used in the entire EJB container (the latter reference is automatically mapped for you). This concatenation of mapping is similar to the concatenation of country code, area code, and local phone number in the telephony naming system.

The ejb/MyVisitBean reference is only valid within the context of the Hello bean. If you were to create another bean that refers to the Visit bean, you might name that reference ILikeThisVisitBean, and map this name to the Visit bean location using a ejbgen:ejb-local-ref tag in the new bean's definition

To Add a Component Method

Now you will implement the business logic to receive a client's request and return a response.

1. Ensure that the Hello bean is displayed in Design View.
2. Right-click the Hello bean and choose Add Component Method. A component method called void method() appears in the Component Methods section.
3. Rename the method String hello(String visitorName). If you step off the method and need to rename it, right-click the method and select Rename.
4. Click the component method to go to Source View and modify the method as shown in red below:

           /**
            * @ejbgen:remote-method
            */
           public String hello(String visitorName)
           {
              Visit theVisit;
              int visitNumber;

              try {
                 // Find the visitor in the database
                 theVisit = visitHome.findByPrimaryKey(visitorName);
              }
              catch(FinderException fe) {
                 try {
                    // Name of visitor not found. Enter the visitor in the database
                    visitHome.create(visitorName);
                    return "Hello, " + visitorName + "!";
                 }
                 catch(CreateException ce) {
                    throw new EJBException(ce);
                 }
              }
              // visitor was found. Find the number of previous visits
              visitNumber = theVisit.getVisitNumber();
              theVisit.setVisitNumber(visitNumber + 1);
              if(visitNumber == 1) {
                 return "Hello again, " + visitorName + "!";
              }
              else {
                 return "Hello, " + visitorName + "!  This is visit number " + theVisit.getVisitNumber() + ".";
              }
           }

5. Save your results.

In this method, you use the reference stored in the visitHome variable to find the record corresponding to the visitor name using the findByPrimaryKey method. You did not explicitly define this method for the Visit bean, because this method was automatically generated for you and defined in the bean's home interface by the EJB container. If the name of the visitor cannot be found, a FinderException will be thrown and caught. When caught, a new record will be created for this new visitor and a welcoming message is returned. If the visitor's name was found in the database, his/her number of previous visits is obtained, the number of visits is increased by one, and a message is returned to the invoking client application. Visitors who have one prior visit will be returned a different message than visitors who have multiple prior visits.

When you return to Design View, the Hello bean should look like this:

Build and Deploy

Now let's build both beans to make sure they are defined correctly. Again, once compiled these beans will be automatically deployed on the server.

1. Locate the Build window in the IDE. If the Build window is not there, select View-->Windows-->Build.
2. In the Application pane, right-click MyEJBProject, and select Build MyEJBProject.
3. Monitor the Build window and verify that the build completes correctly, and that the EJB JAR MyProjectEJB.jar is recreated. You will see this Jar disappear and re-appear in the MyEJBProject folder.
4. After the build completes, the EJB deploys: Watch the green ball in the WebLogic Server status bar at the bottom of WebLogic Workshop turn yellow with the message Updating Server. Wait until the ball turns green again. The EJB is deployed on the server.

If you encounter build errors, verify that the hello method has been created correctly.

Related Topics

Getting Started with Session Beans

Click one of the following arrows to navigate through the tutorial: