Java Platform, Enterprise Edition

Java EE Journal

Subscribe to Java EE Journal: eMailAlertsEmail Alerts newslettersWeekly Newsletters
Get Java EE Journal: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn

J2EE Journal Authors: Jeremy Geelan, Zakia Bouachraoui, Douglas Lyon, Stackify Blog, APM Blog

Related Topics: Java EE Journal, Java Developer Magazine

J2EE Journal: Article

Developing EJBs and Servlets with EAServer, Pt. 2

Developing EJBs and Servlets with EAServer, Pt. 2

Welcome to Part 2 of our exploration of EAServer's J2EE capabilities. In PBDJ's July issue (Vol. 7, issue 7) we constructed an Enterprise JavaBean (EJB) that housed the business logic rules for craps. This EJB, built as a session bean using PowerJ 3.5, was deployed with a simple point-and-click exercise into Sybase's Java 2 Platform, Enterprise Edition (J2EE) application server: EAServer 3.5. We also provided a simple test applet to call the EJB for preliminary testing.

However, we still need to review the process of setting up a servlet client into the EJB. Servlets, like EJBs, are a core piece of the overall J2EE suite of technologies. As mentioned in Part 1, servlets provide a very scalable approach to deploying dynamic Web sites. This is because they're generally instantiated only once to serve all clients. The first servlet will then support all subsequent incoming clients through additional threads to it - a far less taxing approach on the server's memory requirements than the more traditional Common Gateway Interface (CGI). Hence, we often see dramatic performance gains with the use of servlet technology. Also, servlets are written in 100% Pure Java as opposed to less robust (and often proprietary) scripting languages, which often lock you into a particular vendor's toolset.

Different Roles for EJBs and Servlets
Whereas servlets can indeed incorporate business logic similar to the way EJBs can, it's wiser to confine a servlet's mission to merely calling out to EJBs for their business logic requirements. The servlet should then simply convert the EJB results into HTML for passback to browser clients. A key advantage to this partitioned approach is that it allows non-HTML clients, such as Java, PowerBuilder, Visual Basic and CORBA, to share the same EJBs invoked by the servlet. Servlets usually support only HTML clients. In addition, EJBs do a much better job than servlets of insulating the developer from low-level service APIs such as security, transaction management and life-cycle management.

A Note on JavaServer Pages and EAServer 3.6
Sybase will soon be releasing the 3.6 versions of both PowerJ and EAServer. These versions will include JavaServer Pages support. The JSP specification is a relatively recent add-on to the J2EE technology suite, allowing Web page designers to get involved in the servlet creation process without needing to learn Java. JSPs get converted into servlets at runtime, so there's a tight relationship between the two technologies. For our purposes we'll focus on the more mature servlet technology. Once you get comfortable with servlets, start reading up on JSP technology as well to complete the picture.

Our Example: A Las Vegas Craps Game Simulator
Recall that our sample application from Part 1 was a Las Vegas Craps Game Simulator. The servlet we're about to develop will call a business logic method housed within the EJB we developed in Part 1. Although both the servlet and the EJB are run by EAServer (Jaguar), from the EJB's particular perspective the servlet is, in fact, just a client. From the servlet's perspective the Web browser is the true client. Figure 1 shows (amongst other J2EE technologies) how the servlet engine/container within EAServer is distinct from the EJB component server.

Figure 2 is an example of the servlet output as seen from Internet Explorer, also shown in Part 1.

We see that this particular game consisted of seven rolls of the dice before a win occurred. The servlet's job is to initiate a single craps game by calling our EJB and then to send back the results to the user's browser. If the user wishes to play additional times, she or he merely needs to click on the Another Game? button. Review Part 1 if you need a refresher on craps rules or how the EJB development process took place.

Defining a Craps Servlet Target and Class
In Part 1 we created a PowerJ 3.5 workspace to house our EJB target, which we called VegasCraps. Now launch PowerJ. Open the same workspace as we're going to add a new target to house the Craps Java Servlet class we're about to build. To create the new target, right-click in the Views window on the Workspace tab, select New and the New window will pop up (see Figure 3).

Select the target tab and then select the Java Classes option. (Note: If you're using PowerJ 3.6 use the Servlet 2.2 option.) Skip through the windows that ask if there are any dependencies to other targets in the workspace - there are none. Fill in the target name with CrapsServlet (see Figure 4). When you click Finish, this new (third) target will appear in your VegasCraps workspace. We'll create our servlet as a new class within this target and then finally deploy it to EAServer as well, where we can invoke it from a browser.

To create our servlet class we'll create a standard framework Java class and adapt it. (PowerJ 3.6 will generate a servlet class automatically when you create a servlet target.) Right-click on the new target and select New. When the New window pops up, select the Class tab, then click on the Framework Class object.

Fill in the Package Name as Vegas and the Class Name as CrapsServlet (see Figure 5). Change the Extends to HttpServlet, as all HTTP servlets must inherit from this standard servlet class. Click Next. The wizard will ask you to add interfaces if you desire. Do not add any so click Finish. The code editor will then open up within your new class. You can close it for the moment.

Figure 6 shows how the Workspace View has now been altered to reflect the new target and class. In addition to the original two EJB-related targets of CrapsEJB and CrapsEJBAll from Part 1, there's now a third one, CrapsServlet.

Building Our Craps Servlet Class
To code, deploy and finally run the craps servlet there are nine steps we'll need to follow, most of which are quite easy and straightforward. Before we walk through these steps, make sure you're on the Views window as shown in Figure 6.

Step 1: Add the CrapsEJB remote interface stub to the Jaguar toolbar palette.

Using PowerJ, we need our new servlet to reference the remote interface of our CrapsEJB so it can access the newCrapsGame() public method. To do this we'll first add the stubs for the home and remote interfaces to the Jaguar toolbar palette within PowerJ. Java client applets and servlets must access methods on these stubs, even though they have no proper knowledge of the internal workings of the EJB implementation bean. (Stubs are known as "proxies" in the PowerBuilder and ActiveX worlds.) The palette will serve as a PowerJ repository for all desired EJB stubs so we can easily include a reference to the remote and/or the home interfaces within the servlet class. The tight PowerJ integration with EAServer makes importing and using these EJB stubs quite easy.

To accomplish this task, first be sure your Jaguar server is running (see Part 1 for details). Then click on the main PowerJ menu by choosing Components —> Add Jaguar Component. This will launch a wizard that asks you to select which EJB you're intending to add to the palette.

Once the wizard gets started, you can reply to its prompts according to the information in Table 1. The wizard will interrogate the current repository of your Jaguar server (EAServer) and provide you with a list of components from which to select.

Clicking on Finish will trigger the stub import process, which takes about half a minute or so to run. You'll see a progress meter screen advance throughout this process.

When the meter screen completes, you'll be able to see the updated Jaguar toolbar palette from the PowerJ main menu. Just click on the Jaguar tab. Figure 7 shows this clearly where you see the two Fred Flintstone icons. One is for the Home interface (CrapsEJBHome), the other for the remote interface (CrapsEJB). They share the same icon but you can tell which is which by the tip description that appears when you position the mouse pointer over each icon. Try it! Both interface stubs are now available for any client application you wish to code with PowerJ.

Step 2: Add the CrapsEJB remote interface and InitialContext stubs to the Servlet class.

You should now click on the remote interface icon for CrapsEJB and then click again anywhere within the servlet's design-time form window. This will drop in a reference to this nonvisual stub so the client can successfully access the EJB's public methods. The servlet also needs an initial context object so at runtime it can locate and then instantiate the EJB on the proper application server within your network. You can click on this object's icon and drop it on the form as you did with the CrapsEJB remote interface. The initial context object is available on the Jaguar menu palette at the far right; there's a doughnut-shaped red circle in the icon, which you'll easily spot in Figure 7. When you've dropped both of these two stubs on your form, it should look similar to Figure 8.

Now go to the Objects tab of the Views window for the CrapsServlet target and expand our servlet class Vegas.CrapsServlet. You should see both objects that you just added - the remote interface and the initial context object (see Figure 9).

Select the remote interface crapsejb_1 and click in the lower right of its Properties tab. Then, as per the right pane of Figure 9, tie the remote interface to the initial context object by selecting the option "Use this design-time Initial Context component," and selecting the CrapsServlet.jctx_1 context object. Now you're ready to make method calls to the CrapsEJB component from within the servlet itself without having to manually write this setup code.

You may also wish to verify that your InitialContext object is pointed at your localhost Jaguar server on port 9000, though it usually will be. Select jctx_1 in the left pane and go to its Jaguar CTS Server subtab pane under the main Properties tab pane. You should be sure that the "Use this static IOR or URL" option is selected, and that the URL specified indeed points to the localhost 9000 port: iiop://localhost:9000. Try the Test Connection button to verify that all is well between the initial context object and your local running copy of Jaguar.

Step 3: Add the imports to the new Servlet class.

Double-click the Imports folder in the Views window on the Workspace tab for the Vegas.CrapsServlet class. (You can see this folder clearly in Figure 6.) Carefully type in these three import statements within the PowerJ code editor:

import javax.servlet.http.*;
import javax.servlet.*;

These packages are standard Sun servlet and I/O classes that are required in order to support browser-based (HTTP) servlets.

Step 4: Add the class variables.

Double-click the DataMembers folder in the Views window for the CrapsServlet class. When the code editor opens, import the file ServletDataMembers.txt

This file can be found on the PBDJ Web site inside a zip file PBDJCrapsImports.Zip that was extracted in Part 1. (To import, you position the cursor in the code editor and then select the menu options Edit—> Insert from File.) Its contents are also shown here:

// add your data members here
String outcome = null;
int arrayidx = 0;
int[] dicerolls = {0};
PrintWriter out;
String title = "EJB Craps Servlet Example";
As you'll recall from writing the EJB in Part 1, the integer array dicerolls stores the history of the dice rolls from the latest craps game. We'll use the same variable name again in the servlet. The integer arrayidx is merely the array subscript value. The PrintWriter variable is a standard servlet class that allows one to send desired HTML back to the client browser. Other variables are minor and will be clear by examining the upcoming doGet() method code.

Step 5: Add the three methods needed to run our servlet: init(), destroy() and doGet().

The specification for servlets recommends that at least three methods be coded. Two out of three are life-cycle methods - init() and destroy() - and are frequently a simple coding task. The doGet() method is a bit more complicated, though still not overly difficult. We'll discuss that one last. (Unlike PowerJ 3.5, PowerJ 3.6 will prepare template code for all three of these methods.)

1. Add the init() method.
The init method is typically used to perform servlet initialization and setup. It's called when the servlet is first instantiated. We have no unusual initializations to perform so we'll simply call the parent class (super) init() method. This class is called GenericServlet and allows the servlet to access its ServletConfig instance (where useful initial variables are stored) outside of the init() method and is a highly recommended step for all servlets.

Remember that to add a new method you simply start the method wizard by right-clicking on the class within the Views window and selecting Insert—> Method. This will bring up a wizard screen asking for a name and a prototype. Provide the method name and prototype shown here and then click Finish.

Method Name: init
Prototype: public void init(ServletConfig config) throws ServletException

The PowerJ 3.5 code editor will open. To implement this method, simply type in this call to the parent's init method beneath the //TO DO comment line:


Thus, when coded, your whole method for init() will look as follows:

public void init(ServletConfig config) throws ServletException
// TODO: implement

Close the code editor and prepare to add the second method, destroy().

2. Add the destroy() method.
The destroy method is called by Jaguar whenever the servlet is about to be unloaded. It can be used to free up resources (such as database connections) that the garbage collection process may not automatically clean up. We have no such resources in this example so we'll simply make a note in the Jaguar log file that the destroy process is taking place. This log can help us with debugging later on and can be easily viewed from the Jaguar Manager program.

To add this method repeat the steps you followed when you added init(), using the method name and prototype below.

Method Name:    destroy
Prototype:     public void destroy()
To implement this, add the following single line of code beneath the //TO DO comment line for the destroy() method:
System.out.println("CrapsServlet destroyed.");
Close the code editor and prepare to add the third and final method, doGet().

3. Add the doGet() method.
The doGet method handles GET requests coming from HTML forms. It's where the majority of the servlet work is performed. Add a new method called doGet with the following prototype:

Method Name:    doGet
Prototype:    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
To provide the implementation code for this method, you should import directly from the file ServletDoGet.txt, which you'll find in the zip file you downloaded earlier that contains the unzipped text files for this article (see also Listing 1).

Much of this code is HTML embedded within the out.println() statements. This is the HTML that gets delivered by the servlet to the browser clients. Even if you're new to HTML, there isn't a lot of difficult coding here. But as mentioned earlier, JSP support in EAServer 3.6 promises to make this coding task easier.

Review of the doGet() Code
Refer to the code for ServletDoGet.txt. The early lines set up the HTML for the header lines on the craps Web page. They also set up the HTML form "Another Game" button that allows the user to rerun subsequent craps games. Now find the line that reads "dicerolls = crapsejb_1.newCrapsGame()", about 20 lines down. It should be in bold within Listing 1. This is a key line of code, as it directly links our client servlet to the EJB. Specifically, it's where the EJB's newCrapsGame() method gets called via the EJB Remote Interface reference (crapsejb_1), along with a passback of the EJB's dice roll history array to the servlet's class variable dicerolls.

After this the doGet() method prints out the dice roll history, beginning with the coming out roll and then looping through a complete set of point rolls (if any exist for a given game). When the loop encounters a value of 1 (win) or 0 (loss), the method then realizes it's at the last element of the array and goes on to print the final game result to the browser. The servlet also keeps and displays ongoing "per user" win and loss counts for the overall session, using a nice feature of servlets called the HTTP session object (and its associated session.getValue and session.putValue methods). The HTTP session objects allows a single servlet to support many browsers simultaneously and still maintain distinct variable values for each of these users. Frequently, a servlet engine will use cookies or URL rewriting under the covers to implement this feature. Refer to other documentation on servlets to learn more about this topic.

Step 6: Set up the Jaguar deployment option.
Now that you have the import statements, class variables and three servlet methods defined, the servlet coding is complete. Now select the target CrapsServlet with a right-mouse click and select build to verify that all your code can be properly interpreted by PowerJ's Java compiler and turned into a ready-to-run class file. If you encounter an error message, review the previous steps carefully to discover where you might have typed an error. If the build worked well, you're now almost ready to run the servlet from a browser. But first we need to deploy the servlet to EAServer (Jaguar).

Before deploying for the first time, you need to tell PowerJ where to install your servlet class file so Jaguar can see it. Once this is done, PowerJ will always properly deploy the servlet for you whenever you request it with a simple right-mouse click. Set the destination path via the Configure button. This path is %JAGUAR%\java\classes. Jaguar will automatically search for servlets here. In my own case, Jaguar is installed in D:\Sybase\Jaguar CTS 3.5. For most users, however, Jaguar is usually installed in C:\Program Files\Sybase\Jaguar CTS 3.5. You can determine your root path (i.e., the path represented here by the notation %JAGUAR%) by examining the System Variables section of the Environment tab within the System window of your Windows Control Panel.

Step 7: Deploy the servlet to Jaguar.
Right-mouse click the servlet CrapsServlet target and select the Deploy option. PowerJ will quickly rebuild and deploy your servlet. You can use Windows Explorer to visit the Step 6 target directory and verify that the CrapsServlet class file now appears there in a folder called Vegas, our Java package name.

Step 8: Define the servlet to Jaguar via Jaguar Manager.
Servlets deployed to Jaguar should also be initially defined to it by using Jaguar Manager. To do this launch your Jaguar Manager program and connect to the localhost 9000, as you did earlier in Step 5 under the EJB Development task. One of the folders available under the default server named Jaguar is Installed Servlets. Right-click on this folder. In the Servlet Wizard that gets triggered, select Create and Install a New Servlet. You're then prompted to "Enter the Servlet Name," which, as you know by this point, should be CrapsServlet. A Servlet Properties popup window appears. You can set various advanced options if you choose (see Chapter 23 of the Jaguar CTS Programmer's Guide for more detail). But at a minimum you should define for Jaguar the new servlet's fully qualified class name as Vegas.CrapsServlet within the General tab(see Figure 10).

You can then right-click the Installed Servlets folder and select refresh to be sure the Jaguar server is aware of your changes. Close Jaguar Manager if you'd like, but you shouldn't need to recycle Jaguar itself.

Step 9: Run the servlet.
Be sure Jaguar is running and then launch Internet Explorer (or Netscape, if you prefer).

Surf to the following URL: http://localhost:8080/servlet/Vegas.CrapsServlet.

Jaguar, by default, listens for HTTP requests on port number 8080. You can alter this if necessary in Jaguar Manager via the Listeners folder, in case other software is running that also requires this port.

You can rerun a new craps game from the same session by clicking on the Another Game? button. The win/loss counts should increment.

Congratulations, you now have a working craps servlet invoking a craps session bean EJB, both created with PowerJ!

Summary Wrap-Up
This paper discussed how to use EAServer and PowerJ to implement the rules for the basic Pass Line bet at the craps table. We first developed an EJB (session bean) in Part 1, followed by an HTTP servlet here in Part 2. The servlet delivers HTML to a browser showing the results of the servlet's invocation of the session bean. Both the session bean and servlet were developed with Sybase's integrated Java IDE: PowerJ. Note that third-party Java IDEs can also write EJBs and servlets, and these can be easily deployed into EAServer. So, while I recommend PowerJ to you due to its tight integration with EAServer and other strong features, if you're comfortable using another IDE, this is perfectly fine. You can still use EAServer very effectively as an EJB component server and/or a servlet engine, importing classes created by another IDE.

Thanks for taking the time to learn about using EAServer, J2EE, EJBs and servlets within this two-part article. I hope you'll continue to build on these skills as the demand for such people is only going up. Also check out Sybase newsgroups when you hit a technical roadblock. Sybase newsgroups have won industry awards for their ability to deliver quick and informative replies from dedicated Sybase staff as well as Team Sybase volunteers. Information on the newsgroups is at

Finally, next time you're in Las Vegas, you can consider walking over to the craps table to try your luck. The house margin in craps is quite small compared to most casino games. (No, I don't own MGM stock!)

For Further Reading
This relatively short article naturally can't serve as a substitute for a more thorough overview of EJB and servlet technologies. If you find yourself lost in part or in whole, consider these Web sites and books to enhance your understanding:

Web Sites

  2. (see: Hot Topics)
  1. Monson-Haefel, R. (1999). Enterprise JavaBeans (1.1 edition) O'Reilly & Associates.
  2. Roman, E. (1999). Mastering Enterprise JavaBeans. Wiley.
  3. Hunter, J., and Crawford, W. (1998) Java Servlet Programming. O'Reilly & Associates.
  4. Flanagan, D., Farley, J., Crawford, W., and Manusson, K. (1999). Java Enterprise in a Nutshell. O'Reilly & Associates.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.