Developing and Testing a Complete J2EE "Hello World" App with WebSphere Studio V5

By Staff

First published by IBM developerWorks at
All rights retained by IBM and the author.

In October 2001, Sheldon Wosnick published an article on completing and testing a complete J2EE application using WebSphere Studio. That article was based on the very first beta of WebSphere Studio. There have been about eight or nine releases since then, and a lot has changed!  We felt an updated article for Version 5.0 of WebSphere Studio would serve the developer community well by showing off some of the new features like J2EE Application Clients, automatic data source creation for Cloudscape, and how to create and configure resource references.

In this tutorial, we will be using WebSphere® Studio Application Developer Version 5.0 to develop, test, run and debug a complete J2EE application, consisting of entity and session EJBs, a servlet, a JSP™ page and an HTML home page. We will be focusing extensively on EJB development. The entire application will use only the Application Developer tools and run times available straight "out of the box."

Keeping true to developer tradition, this J2EE application will be a "Hello World" application in which all components will be named HelloWorld. So, for example, the entity bean you will create and deploy will be called HelloWorldEntity, the session bean will be called HelloWorldSession, the servlet called HelloWorldServlet, and so forth. This will let us concentrate on the main ideas without getting too bogged down in specifics and let us keep the code simple. The source code and listings are provided in the download. For those who would rather work through this tutorial with a pre-created application, we have also provided this with the download. The download ZIP file contains the completed EAR module and the code listings used in this tutorial. With this ready-made version, you can simply import the EAR module, create the tables, create and configure the Server project, instance and configuration, and then run, debug and test the application. However, our hope is that you create everything from scratch to get a good sense of the development environment and the tight integration of the various parts.

Our goal, then, is to highlight the Application Developer tools. The purpose of this article is not to teach you how to create J2EE applications -- we are sure many of you are masters at this -- but rather to show you how the tools seamlessly integrate all of the steps required to code and unit-test J2EE applications, thus increasing programmer productivity and satisfaction.

Artifacts you will create
In the "Hello World" end-to-end, multi-tiered, distributed J2EE application, we plan to demonstrate that it is possible to create and use all of the following J2EE artifacts spanning the three main tiers in a typical distributed J2EE application -- client (presentation), application and data.

  • J2EE application (EAR module)
  • J2EE Web application (WAR module)
  • J2EE EJB module
  • stateless session EJB
  • container-managed entity EJB (CMP)
  • datasource (mapped to Cloudscape)
  • J2EE application client module
  • Java™ bean (used in servlet and JSP)
  • servlet
  • JSP page
  • HTML page

Architecture for "Hello World"
The architecture used in this application utilizes the so-called J2EE "Model 2" architecture (a version of the classic MVC, model-view-controller architecture) in which servlets are used as controllers and JSPs are used to display the final output. In this case, a session bean is used to control workflow and interact directly with the client (which happens to be a servlet) and it in turn interacts with an entity bean that further interacts with the datastore that persists it. This simple distributed "Hello World" J2EE application, then, is actually quite complex when you think about it. We will show you how easy it is to develop and test it in WebSphere Studio Application Developer.

J2EE view of the completed "Hello World" end-to-end application
Figure 1.
J2EE view of the completed "Hello World" end-to-end application

Working through the tutorial
The following steps and procedures should be followed exactly to build and test the "Hello World" J2EE application. This is the procedure to follow if you plan to create the application from scratch. The pre-created versions (in EAR module format) are available for download and simply need to be imported as you import any other EAR module to Application Developer. It is our expectation that when we say "create an entity bean…" you know what we're talking about. If this is not the case, check out the Application Developer help documentation for details on how to use the Application Developer tools.

WebSphere® Studio Application Developer Version 5.0 supports both the EJB 1.1 and EJB 2.0 specifications.  The EJB 2.0 specification will be used in this tutorial. However, the steps involved will be very similar to using the EJB 1.1 specification.

When you have completed this tutorial, you will have a number of different types of projects and artifacts, each one representing a different J2EE artifact such as a Web module and an EJB module. The complete, end-to-end application seen through the eyes of the "J2EE view" should look like Figure 1, when you’re done.

Development steps

Step 1. Create the EJB project and the HelloWorldEntity container-managed entity bean (CMP)

  1. Create a new 2.0 EJB project called HelloWorldEJBProject, and a new EAR project name called, HelloWorldEARProject. Click Finish, and accept all other defaults.
  2. Select the HelloWorldEJBProject project. Create a new CMP 2.0 bean called HelloWorldEntity, in a package called helloworld.ejb, with the persistent fields listed below. Check the Remote client view checkbox before creating the fields.  Make sure to check the Promote getter and setter methods to remote interface checkbox and the Promote getter and setter methods to local interfacecheckbox for each field, except for the id field, which you must make the key field. Supply default values:
    firstName (String)
    lastName (String)
    id (int, Key Field)
  3. Once you have added all three fields, click the Finish button.

Step 2. Create the EJB to RDB mapping using Cloudscape for the HelloWorldEntity CMP

  1. Select the HelloWorldEJBProject project and perform a default top-down EJB to RDB mapping to Cloudscape V5.0 as the target database using a new backend folder. You should specify the following:

    Target Database: Cloudscape, V5.0
    Database Name: SAMPLE
    Schema Name: NULLID

    Figure 2.
    Creating an EJB to RDB mapping for Cloudscape

Step 3. Create a HelloWorldSession stateless session bean

  1. Select the HelloWorldEJBProject project and create a new stateless session bean called HelloWorldSession in the helloworld.ejb package. Make sure the Remote client view is created.  Accept all the defaults, and click Finish.
  2. Open the Java editor on for this HelloWorldSession bean. Add a protected member of type HelloWorldEntity, and assign it a value of null:
    protected HelloWorldEntity helloWorldEntity = null;
    Now, add code to enable the session bean to manage workflow and interact with the entity bean’s remote interface. The Web browser client will never interact with the entity bean directly, not even with its remote interface. The client will only interact with the session bean. Using session beans to control workflow is a typical way in which J2EE applications are implemented. To reiterate, we are not suggesting that the "Hello World" code and implementation is typical or a best practice; we are simply using this code to demonstrate how well the tools integrate.
  3. Create the method getHelloWorldEntity() in the HelloWorldSessionBean class, but do not promote it to the remote interface since it does not need to be exposed to the client. It is internal to this class and can be hidden.
    protected HelloWorldEntity getHelloWorldEntity(int id) {
    return helloWorldEntity;
    See Listing 1in the download ZIP file for the full implementation of this method.
  4. Add the following import statements to
    import javax.ejb.*;
    import javax.naming.*;
    import java.rmi.RemoteException;
  5. Add the following remote methods to talk to the HelloWorldEntity entity bean:
    public String getFirstName(int id) {
    public void setFirstName(int id, String firstName) {
    public String getLastName(int id) {
    public void setLastName(int id, String lastName) {
    See Listing 2in the download ZIP file for the implementation of these four methods.
  6. Promote those four methods to the remote interface of the HelloWorldSession bean.

Step 4. Generate WebSphere deployed code
Generate deployed code and run RMIC for both HelloWorldSession and HelloWorldEntity beans by selecting the project HelloWorldEJBProject, and then from the pop-up menu, select Generate => Deploy and RMIC code...

Step 5. Create a server project

  1. Create a new server project called HelloWorldServerProject.
  2. Using the server project you just created, create a new Server and Server Configuration. Set the Server name to HelloWorldServer, and use the WebSphere version 5.0 Test Environment server type. If a different HTTP port than the default 9080 is required, go to the next page and change this value. Otherwise, click Finish.
  3. You will now be in the Server perspective. Use the Server Configuration view to add the project HelloWorldEARProjectto the HelloWorldServer configuration.

    Server configuration view
    Figure 3.
    Server configuration view

Step 6. Binding the datasource to the HelloWorldEntity CMP
Create a binding of a datasource to our particular CMP, we need to edit the EJB bindings using the EJB deployment descriptor editor.

  1. Select the HelloWorldEJBProject project in the J2EE Hierarchy view.  Right-click and perform an Open with on this file using the Deployment Descriptor Editor.
  2. Select the Beans tab, and then select the HelloWorldEntity bean to configure the binding. Enter the following values for the JNDI name for the binding under the WebSphere Bindings section. Use the JNDI value shown below for this tutorial (although you can enter any CMP container factory JNDI name).

    JNDI name: ejb/helloworld/ejb/HelloWorldEntityHome
    CMP Container Factory JNDI name: jdbc/cloudscape/HelloWorldDatasource
    Container authorization type: Per_Connection_Factory

    Binding the data source to the CMP EJB
    Figure 4.
    Binding the data source to the CMP EJB

    When you are finished, type Ctrl-S or click the Save icon on the toolbar to save the configuration.

Step 7. Create a data source and Cloudscape database tables
In WebSphere Studio Application Developer Version 5.0, there is a really cool feature that allows you to set up the Cloudscape data source and database tables for CMPs automatically. This new feature allows you to quickly test your CMPs without drilling down into details on creating the database and data source manually. (See Resources for more information on how to create container managed persistence with Cloudscape.)

Cloudscape data source and table creation.
Figure 5.
Cloudscape data source and table creation.

To create the data source and Cloudscape database tables automatically, right click on the HelloWorldServer in the Servers view, and select the Create tables and data sources menu item. A dialog will then display showing that the data source and database tables were created successfully (Figure 5).

The HelloWorldEntity CMP bean is now ready for testing.

First round of unit testing: the Universal Test Client
Since you have actually created, developed, deployed, and configured quite a bit to this point, we suggest that some testing is in order before proceeding to the next set of steps to implement the servlet, the JSP and the associated code. This is where we believe (biased, of course, but you judge for yourself) that the Application Developer tools really shine and provide you seamless, integrated and powerful testing capabilities. Since the Universal Test Client is already added to the Server by default and runs in the Application Server itself, use the Universal Test Client first to make sure that your EJBs are at least functional, and that the persistence mechanism works properly to Cloudscape.

Running the Universal Test Client Run on Server command
Figure 6.
Running the Universal Test Client Run on Server command

  1. Right-click the HelloWorldSession bean in the HelloWorldEJBProject project in the J2EE Hierarchy view, and select Run on Server from the pop-up menu.

    This is one of the numerous "automatic" features of Server Tools that we think is cool. It will do just "the right thing" for you to configure the selected module (EJB or Web application component), initialize and start the application server for the selected type of module. In the case of an EJB, install the Web-based Universal Test Client, execute the Universal Test Client on this bean in the embedded Web browser, do a lookup on the name service, find the home and make it available to you. You can do this all with one simple menu command to Run on Server. Now this is automation!
  2. Check the console in the Server Perspective to make sure the beans fired up properly. If you see no exception or load module errors, you can assume it succeeded. If not, there is likely something wrong with the generated code or your data source configuration. Once started successfully, the status will change to Started.

    Checking the server status: server is started
    Figure 7.
    Checking the server status: server is started

  3. If the server started properly, use the Web-based, integrated, Universal Test Client, which will automatically surface for you, to create an instance of the HelloWorldSession. Doing so in this application will create an instance of HelloWorldEntity. Make sure that there are no messages in the console indicating that the persistor code failed to generate or that the data source was not bound properly.
  4. Try out some of the remote methods on the session bean which in turn invoke similar methods on the entity bean. This allows the two beans to talk to each other and persists data to the configured data source.  The setting method (setFirstName and setLastName) on the HelloWorldSession bean will create the entry in the database if the given id does not already exist.  

    Universal Test Client testing the HelloWorldSession bean
    Figure 8.
    Universal Test Client testing the HelloWorldSession bean

  5. After you have finished testing using the Universal Test Client, stop the server by right click on the HelloWorldServer in the Servers view and select Stop on the pop up menu.

Second round of unit testing: the J2EE application client
If you were successful with the Universal Test Client, you may now want to test the beans using a standards-based J2EE Application Client, which is part of a J2EE application module. This means that it is a built-in part of the application as a whole and is part of the EAR module.

Step 8. Creating a Java application client project and implementation

  1. Create a new J2EE 1.3 Application Client project called HelloWorldApplicationClientProject, using the existing HelloWorldEARProject EAR. Since the application client will need to access the classes in the EJB project HelloWorldEJBProject, you need to add the EJB project to the dependent JARs list to make the classes in the EJB project visible during compilation.

    Add the EJB project as a dependent JAR to the Application Client Project.
    Figure 9.
    Add the EJB project as a dependent JAR to the Application Client Project.

    When creating the project, the server tools will automatically detect that the new application client project has been added to the EAR project and will prompt for repairing the server configuration. Click OKon the dialog box to make the necessary update to the server configuration.
  2. In the appClientModule folder, create a new J2EE application client class with a main method HelloWorldEJBTestClient in a helloworld.ejb.clientspackage.
  3. See Listing 3 in the download ZIP file for the full implementation for the HelloWorldEJBTestClient.
    package helloworld.ejb.clients;
    import javax.naming.*;
    Import java.util.*;
    Import javax.rmi.*;
    Import helloworld.ejb.*;

    public class HelloWorldEJBTestClient {
    public static void main(String[] args) {
    One thing you should notice is that since this is a J2EE-compliant application client packaged with the EAR module, there is no need to use a network-specific JNDI InitialContext and use the java:comp JNDI name instead. You do not need to specify the service provider to connect to the J2EE server; this demonstrates that J2EE application clients have location transparency. The real power of location transparency is that the "Hello World" application client component does not need to know the exact location of the EJBs it needs to connect to and work with.

    Set the main class of the Application Client
    Figure 10.
    Set the main class of the Application Client

  4. Open the application client deployment descriptor by right clicking on the HelloWorldApplicationClientProject and select the menu item Open With => Deployment Descriptor Editor. Then, edit the Main Class of the application client to the created client class helloworld.ejb.clients.HelloWorldEJBTestClient.  This settings tells which main class to run when the application client is launched.
  5. Add an EJB reference called ejb/HelloWorldSession to reference the session bean HelloWorldSession. (Hint: All the fields will be filled automatically for you if you browse and select the HelloWorldSessionbean from the Link. This reference name is used in the code when doing a JNDI name lookup.  Therefore, you have to follow this reference name unless you make the corresponding changes in the code.

        Add the EJB reference to the Application Client using the Client Deployment Descriptor.
    Figure 11.
    Add the EJB reference to the Application Client using the Client Deployment Descriptor.

  6. Save the changes in the Client Deployment Descriptor Editor and the JAR Dependency Editor.
  7. Start WebSphere Application Server in the Server Configuration panel. Wait until it is fully started without exceptions.
  8. Run your home-grown HelloWorldEJBTestClient class using the Application Client Launcher (not the Server Launcher). In WebSphere Studio Application Developer Version 5.0, there is a application client launcher available to run the application client easily with minimal setup.  From the J2EE Perspective, select the HelloWorldEJBTestClient Java file on the J2EE Navigator view and select the menu item Run => Run... . Create a new WebSphere V5 Application Client called HelloWorldEJBTestClientLauncher, select HelloWorldEARProjectas the Enterprise Application, and keep other default settings. You can stay in the J2EE perspective where you can see the console output.
  9. You should get a clean run without exceptions, and will see the following in the console window after the application finishes its run:
    Getting the InitialContext...
    Performing the lookup..
    Parameters passed to the commandline:
    Parameter 'id' = 99
    Parameter 'firstName' = John
    Parameter 'lastName' = Smith
    Calling Session bean methods..
    Verifying method calls happened...
    First Name Returned: John
    Last Name Returned: Smith
    If this is not the case for you, then go back and trace through your steps to see where you might have made a mistake. If the application runs successfully, you have now ensured your core application logic works properly in yet a different (open standards, non-proprietary) client configuration.
  10. After you have finished testing using the application client, stop the server HelloWorldServer.

Third round of unit testing: the full end-to-end J2EE application
Now that you have developed and tested your EJBs using the EJB Test Client that runs in the application server itself, and further tested them with an application client which runs completely outside the application server, you might want to do one more round of unit testing. You may want to create a servlet, JSP, Java bean and HTML home page so that you can run the J2EE application from end-to-end through all the various tiers, just as we illustrated in Figure 1 above. In this way, you have an authentic entry point that resembles closely how you would expect your users to access the application that is composed of this core logic.

Step 9. Create the Web project and a simple Java bean to read and write properties
The architecture used here is a typical separation of content presentation from content generation and is one of the suggested servlet and JSP implementations.

  1. Create a new J2EE 1.3 Web project called HelloWorldWebProject, using the existing EAR HelloWorldEARProject. Add the HelloWorldEJBProject to the dependent JARs list. Accept other defaults, and click Finish.  Click OKwhen prompted for repairing the server configuration to make the corresponding update on the HelloWorldServer.
  2. Create a simple Java bean called HelloWorldJavaBean in a new package called helloworld.servlet, in the Java Source folder of the Web project (where we will subsequently build our servlet). It will store the values returned from the session bean, so that the servlet you will create next can make the values available to the JSP you will also create. During compilation, the actual binaries will be moved over to the "Web Content" folder to the WEB-INF\classes location, but you should work with your source from only the source tree (i.e. the Java Source folder). See Listing 4 in the download ZIP file for the full implementation of HelloWorldJavaBean.

Step 10. Create the HelloWorldServlet servlet

  1. Use the Web tools to create a simple servlet called HelloWorldServlet in a helloworld.servlet package, implementing the doPost() method stub only. Then, implement the code required to communicate to the HelloWorldSession bean. Accept all the other defaults.

    The servlet will not be anything fancy and it is not really suggestive of the way to perform the JNDI lookup, which is typically done in an init()method. We will be referencing the HelloWorldJavaBean created above, so make sure that you have created it as described in Step 9.
  2. In the end, you should code the implemented servlet and the doPost() method. Refer to Listing 5 in the download ZIP file. This servlet is virtually identical to the application client above except that it is implemented as a servlet, and like the application client, the service provider and the network-specific JNDI initial context do not need to be specified because the servlet is part of a Web module. The Web module is part of the EAR module that contains your EJBs.

Step 11. Create the HTML home page
Using the Web tools, add a simple home page, index.html, to serve as a form to pass parameters and post them to the servlet. Since HTML is not considered "source," add it to the "Web Content" folder, which is the working document root. A specific style sheet is not required here so do not specify one. Then, using the design or source views, create three text fields for the ID number, First Name and Last Name fields and a Submit action to perform a POST. Refer to Listing 6 in the download ZIP file for an example of such a page.

Step 12. Create the JSP for final presentation to the user
Using the Web tools, create a simple JSP page called HelloWorldJSP.jsp without specifying a style sheet. Complete the same steps as you did to create the HTML page. The JSP could look as simple as the one provided in Listing 7 in the download ZIP file.

Step 13. Create a reference to the EJB session bean

Creating a reference to the EJB session bean
Figure 12.
Creating a reference to the EJB session bean

Since we will be referencing the session bean HelloWorldSession from the Web project when running the application, we have to add an EJB reference to the Web module deployment descriptor. Right click on the Web module HelloWorldWebProject in the J2EE Hierarchy view and select the menu item Open With => Deployment Descriptor Editor. Then, add the EJB reference to the HelloWorldSession bean with the reference name called ejb/HelloWorldSession. The detailed information of the reference is shown below:

        EJB reference name: ejb/HelloWorldSession
        Link: HelloWorldEJBProject.jar#HelloWorldSession
        Type: Session
        Home: helloworld.ejb.HelloWorldSessionHome
        Remote: helloworld.ejb.HelloWorldSession
        JNDI Name: ejb/helloworld/ejb/HelloWorldSessionHome

(Hint: All the fields will be filled automatically (except the reference name) for you if you browse and select the HelloWorldSession bean from the Link.)  

Running the application on the server
Figure 13.
Running the application on the server

This reference name is used in the code when doing a JNDI name lookup.  Therefore, you have to follow this reference name unless you make the corrresponding changes in the code. Save the changes that you have made in the Web Deployment Descriptor Editor.

Step 14. Run the full application on the server
By now, you have constructed all the various pieces of the full, end-to-end J2EE application and can test it from beginning to end in a simple, straightforward manner.

  1. Select the index.html file and use the Run on Server command to run the index.html form you created on the server. Select to use the existing server HelloWorldServerif it prompts you to select the server.  Just like we described earlier, the command will just do the "right thing" to process and run a specific component automatically for you. If the server is already running, you must stop it first and restart it to pick up the changes in the configuration from adding the new Web application (WAR module) to your enterprise application (EAR module).
  2. Enter some data in the entry fields and perform a submit. This will pass execution on through to the servlet controller to the session bean on to the entity bean. This bean is persisted to the datastore and then transfers execution back to the servlet which

    A simple HTML entry and submit form
    Figure 14.
    A simple HTML entry and submit form

    will place the values in a Java bean, set that bean into the session, and dispatch the entire request and response to the JSP for presentation to the user. Be patient, since the first time you submit the request, the JSP needs to be generated first and then compiled, which can take a few seconds. Subsequent submits will be almost instantaneous.
  3. Once the full application has run its course through all of the distributed tiers in Figure 1, above, the final output is HTML generated by the presentation JSP and sent back to the browser.

This article has described how to develop, test, run, and debug a complete, end-to-end, distributed, multi-tier application with the tools provided in WebSphere Studio Application Developer, Version 5.0. The Application Developer tools free you from being distracted by set-up and configuration issues, and let you concentrate fully on your core business logic and on creating and unit testing powerful, integrated J2EE artifacts.


First published by IBM developerWorks at