Enterprise JavaBeans - Part 7

Gopalan Suresh Raj

Developing an N-tier EJB Application - The EJB Servlet Session Bean Client

The EJB Servlet client talks to the Cart session EJB and enables clients to buy books and music albums on the Web. The servlet instantiates a Cart session bean in its init() method and communicates with the bean via the doGet() and doPost() methods.

The init() class method and class members of the Online servlet class are defined as Listing 19 :

/** 
 * To run this servlet, you may have to specify the root directory 
 * in the path since it needs to get at the stubs present in the
 * package com.gopalan.Shop.Cart.
 * 
 * You should also move the Online.class file to the directory 
 * specified in the -d option below.
 * 
 * eg.,
 * servletrunner -p 6060 -d E:\ -s E:\com\gopalan\Shop\Cart\servlet.properties
 * 
 */ 

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.rmi.*;
import com.gopalan.Shop.Cart.*;

public class Online extends HttpServlet { 
 
 CartHome	home = null;
 Cart		cart = null;
 
 Vector    bookList = new Vector();
 Vector    musicList= new Vector();
 Vector    bookCart = new Vector();
 Vector    musicCart= new Vector();

 public void init(ServletConfig config) throws ServletException { 
  
  super.init(config);
  System.out.println( "Called from Online::init..." );
  try{
   home = (CartHome)Naming.lookup("Cart");
   if( null == home ) { 
    System.out.println( "null CartHome returned..." );
   }
   else { 
    cart = home.create();
    System.out.println( "Naming.lookup successful..." );
    System.out.println( "home.create successful..." );
   }
  } catch(Exception e){System.out.println( e );}
 }
 
 public void doGet(HttpServletRequest req, HttpServletResponse res)
  throws ServletException, IOException { 
  
  System.out.println( "Called from Online::doGet..." );
  displayForm(res, "Welcome");   
 }
 
 public void doPost(HttpServletRequest req, HttpServletResponse res)
  throws ServletException, IOException { 
  
  System.out.println( "Called from Online::doPost..." );
  
  int item = 0;
  
  System.out.println( "Content Type ="+
                      req.getContentType());
  
  if ("application/x-www-form-urlencoded".equals(req.getContentType())) { 
   Enumeration enum = req.getParameterNames();
   while (enum.hasMoreElements()) { 
    System.out.println("---------------------------------------------");
    String name = (String) enum.nextElement();
    System.out.println("name = " + name);
    
    String values[] = req.getParameterValues(name);
    System.out.println("The No. of Values selected are ="+values.length);
    
    
    if( name.equals("MusicCombo") ) { 
     for (int i = 0; i < values.length; i++) { 
      
      System.out.println(values[i]);
      item = (Integer.valueOf(values[i])).intValue();
      cart.addToMusicCart (((ReturnSet)musicList.elementAt(item-1)).code);
     }
    }

    if( name.equals("BooksCombo") ) { 
     for (int i = 0; i < values.length; i++) { 
      
      System.out.println(values[i]);
      item = (Integer.valueOf(values[i])).intValue();
      cart.addToBooksCart (((ReturnSet)bookList.elementAt(item-1)).code);
     }
    }
    
    if( name.equals("BuyButton") ) { 
     cart.flushBooksCart();
     cart.flushMusicCart();
    }
    System.out.println("---------------------------------------------");
   }
  }     displayForm(res, "Welcome");   
 }
 
 
 private void displayForm(HttpServletResponse response, String message) 
  throws IOException { 
  
  System.out.println( "Called from Online::displayForm..." );
  if( ( home == null ) || (cart == null)) { 
   try{
    home = (CartHome)Naming.lookup("Cart");
    cart = home.create();
   } catch(Exception e){ System.out.println( e ); }
  }
  response.setContentType("text/html");

  PrintWriter  out = response.getWriter();
  out.println("<html><body bgcolor=\"#FFFFFF\">");

  out.println("<p align=\"center\"><font size=\"2\" face=\"Verdana\">");
  out.println("<strong>Horse and Stable Online, Inc.</strong></font></p>");
  
  out.println("<p><font size=\"1\" face=\"Verdana\">");
  out.println("<strong>List of Books Available-Make your Selection</strong></font></p>");

  out.println("<form method=\"POST\">");
  out.println("<p><font size=\"1\" face=\"Verdana\">");
  out.println("<select name=\"BooksCombo\" multiple size=\"2\">");
  
  bookList = cart.getBooksList();
  System.out.println("Book List of size "+bookList.size()+" is...");
  for(int i = 0; i < bookList.size(); i++) { 
   ReturnSet set = (ReturnSet)bookList.elementAt(i);
   System.out.println( "code = " +set.code + 
                       " Title = " +set.title + 
                       " Author = " +set.authors);
   out.println("<option value=\""+ set.code + 
               "\">ISBN = "+
               set.code+" Title = "+set.title+" Authors = "+set.authors+" List Price = $"+set.price+" Discount = "+
               set.discount+"% Our Price = $"+set.ourPrice+
               "</option>");
  }
  out.println("</select><input type=\"submit\" name=\"BooksButton\"");
  out.println("value=\"Add to Books Shopping Cart\"></font></p></form>");
  
  out.println("<p><font size=\"1\" face=\"Verdana\">");
  out.println("<strong>Books you added to your Shopping Cart</strong></font></p>");
  out.println("<div align=\"center\"><center>");

  out.println("<table border=\"1\"><tr>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>ISBN</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Book Title</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Author(s)</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Actual Price(in US Dollars)</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Discount(% in Percentage)</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Your Price(in US Dollars)</strong></font></td></tr>");
  
  bookCart = cart.getBooksCart();
  System.out.println("Book Cart of size "+bookCart.size()+" is...");
  for(int i = 0; i < bookCart.size(); i++) { 
   ReturnSet set = (ReturnSet)bookCart.elementAt(i);
   System.out.println( "code = " +set.code + 
                       " Title = " +set.title + 
                       " Author = " +set.authors);
   out.println("<tr>");
   out.println("<td align=\"right\"><font size=\"1\" face=\"Verdana\">" + set.code);
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">"+set.title);
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">"+set.authors);
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">$"+set.price);
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">"+set.discount+ " %");
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">$"+set.ourPrice);
   out.println("</tr>");
  }
  out.println("</table></center></div>");
  out.println("<p align=\"left\"><font size=\"1\" face=\"Verdana\">");
  out.println("You have selected "+ cart.getNumberBooks() +
              " books for a total cost of $"+ cart.getBooksTotal() + "</font></p>");
  

  out.println("<p><font size=\"1\" face=\"Verdana\">");
  out.println("<strong>List of Music CDs Available-Make your Selection</strong></font></p>");

  out.println("<form method=\"POST\">");
  out.println("<p><font size=\"1\" face=\"Verdana\">");
  out.println("<select name=\"MusicCombo\" multiple size=\"2\">");
  
  musicList = cart.getMusicList();
  System.out.println("Music List of size "+musicList.size()+" is...");
  for(int i = 0; i < musicList.size(); i++) { 
   ReturnSet set = (ReturnSet)musicList.elementAt(i);
   System.out.println( "code = " +set.code + 
                       " Title = " +set.title + 
                       " Author = " +set.authors);
   out.println("<option value=\""+ set.code + 
               "\"> Code ="+
               set.code+" Album = "+set.title+" Composers = "+set.authors+" List Price = $"+set.price+" Discount = "+
               set.discount+"% Our Price = $"+set.ourPrice+
               "</option>");
  }
  out.println("</select><input type=\"submit\" name=\"MusicButton\"");
  out.println("value=\"Add to Music Shopping Cart\"></font></p></form>");
  
  out.println("<p><font size=\"1\" face=\"Verdana\">");
  out.println("<strong>Albums you added to your Shopping Cart</strong></font></p>");
  out.println("<div align=\"center\"><center>");

  out.println("<table border=\"1\"><tr>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>code</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Album Title</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Composer(s)</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Actual Price(in US Dollars)</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Discount(% in Percentage)</strong></font></td>");
  out.println("<td><font size=\"1\" face=\"Verdana\"><strong>Your Price(in US Dollars)</strong></font></td></tr>");
  
  musicCart = cart.getMusicCart();
  System.out.println("Book Cart of size "+musicCart.size()+" is...");
  for(int i = 0; i < musicCart.size(); i++) { 
   ReturnSet set = (ReturnSet)musicCart.elementAt(i);
   System.out.println( "code = " +set.code + 
                       " Title = " +set.title + 
                       " Author = " +set.authors);
   out.println("<tr>");
   out.println("<td align=\"right\"><font size=\"1\" face=\"Verdana\">" + set.code);
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">"+set.title);
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">"+set.authors);
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">$"+set.price);
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">"+set.discount+ " %");
   out.println("</font></td><td align=\"right\"><font size=\"1\" face=\"Verdana\">$"+set.ourPrice);
   out.println("</tr>");
  }
  out.println("</table></center></div>");
  out.println("<p align=\"left\"><font size=\"1\" face=\"Verdana\">");
  out.println("You have selected "+ cart.getNumberAlbums() +
              " CD Albums for a total cost of $"+ cart.getAlbumsTotal() + "</font></p>");
  

  out.println("<hr><p align=\"left\"><font size=\"1\" face=\"Verdana\">");
  out.println("<strong>Total Price of Items selected = $"+ cart.getGrandTotal() + "</strong></font></p>");

  out.println("<form method=\"POST\"><p><font size=\"2\" face=\"Verdana\">");
  out.println("<input type=\"submit\" name=\"BuyButton\" value=\"Buy\"></font></p>");
  out.println("</form>");
  out.println("</body></html>");
 }
 
}

Listing 19: Listing of the Online Servet class

As shown earlier in Figure 6, the browser client starts the whole process by sending a GET message to the Online servlet, which resides on a Web server. This causes the init() method of the Online servlet class to look up the Cart bean from the EJB server and to create it. The Cart EJB’s setSessionContext() method, which is one of the first methods called when the session bean is created, looks up the Books entity EJB and the Music entity EJB and creates them. As mentioned earlier, entities are a direct mapping of the records in the domain model of the database Shop, which is associated with these entities. The entity EJBs (Books and Music) then interact with the database (Shop) to service requests from the session EJB (Cart).

I assume the servlet engine is obtained from Sun’s Servlet Development Kit, although the example servlet should also run fine with any other engine. To run the servlet:

  1. Copy the Online.class and the servlet.properties files to the root directory.
  2. Make sure the EJB Server is up and running.
  3. Start up the servletrunner with the command.

servletrunner -p 6060 -d E:\ -s E:\com\gopalan\Shop\ServletClient\servlet.properties

The console screen should then resemble

E:\>copy .\com\gopalan\Shop\ServletClient\Online.class
1 file(s) copied.
E:\>
copy .\com\gopalan\Shop\ServletClient\servlet.properties
1 file(s) copied.
E:\
>servletrunner -p 6060 -d E:\ -s E:\com\gopalan\Shop\ServletClient\servlet.properties
servletrunner starting with settings:
port = 6060
backlog = 50
max handlers = 100
timeout = 5000
servlet dir = E:\
document dir = .\examples
servlet propfile = E:\
com\gopalan\Shop\ServletClient\servlet.properties
Online: init
Called from Online::init...
Naming.lookup successful...
home.create successful...
Called from Online::doGet...
Called from Online::displayForm...
Book List of size 4 is...
code = 1 Title = Book1 Author = Author1
code = 2 Title = Book2 Author = Author2
code = 3 Title = Book3 Author = Author3
code = 4 Title = Book4 Author = Author4
Book Cart of size 0 is...
Music List of size 4 is...
code = 1 Title = Album1 Author = Composer1
code = 2 Title = Album2 Author = Composer2
code = 3 Title = Album3 Author = Composer3
code = 4 Title = Album4 Author = Composer4
Book Cart of size 0 is...
Called from Online::doPost...
Content Type =application/x-www-form-urlencoded
---------------------------------------------
name = BooksButton
The No. of Values selected are =1
---------------------------------------------
---------------------------------------------
name = BooksCombo
The No. of Values selected are =2
1
2
---------------------------------------------
Called from Online::displayForm...
Book List of size 4 is...
code = 1 Title = Book1 Author = Author1
code = 2 Title = Book2 Author = Author2
code = 3 Title = Book3 Author = Author3
code = 4 Title = Book4 Author = Author4
Book Cart of size 2 is...
code = 1 Title = Book1 Author = Author1
code = 2 Title = Book2 Author = Author2
Music List of size 4 is...
code = 1 Title = Album1 Author = Composer1
code = 2 Title = Album2 Author = Composer2
code = 3 Title = Album3 Author = Composer3
code = 4 Title = Album4 Author = Composer4
Book Cart of size 0 is...
Called from Online::doPost...
Content Type =application/x-www-form-urlencoded
---------------------------------------------
name = MusicCombo
The No. of Values selected are =2
2
4
---------------------------------------------
---------------------------------------------
name = MusicButton
The No. of Values selected are =1
---------------------------------------------
Called from Online::displayForm...
Book List of size 4 is...
code = 1 Title = Book1 Author = Author1
code = 2 Title = Book2 Author = Author2
code = 3 Title = Book3 Author = Author3
code = 4 Title = Book4 Author = Author4
Book Cart of size 2 is...
code = 1 Title = Book1 Author = Author1
code = 2 Title = Book2 Author = Author2
Music List of size 4 is...
code = 1 Title = Album1 Author = Composer1
code = 2 Title = Album2 Author = Composer2
code = 3 Title = Album3 Author = Composer3
code = 4 Title = Album4 Author = Composer4
Book Cart of size 2 is...
code = 2 Title = Album2 Author = Composer2
code = 4 Title = Album4 Author = Composer4

Now start your Web browser and access the servlet’s URL:

http://127.0.0.1:6060/servlet/Online

Figure 7 shows a typical browser client session interacting with the server to purchase books and music CDs from our online bookstore.

Fig 7: The client’s view of the online bookstore

Go to Part 8 of this article

You can always refer to my Homepage at http://www.execpc.com/~gopalan for more EJB source code. Another good resource is the EJB-INTEREST@JAVA.SUN.COM mailing list from Sun and the EJBHome mailing list ejbhome-discuss@iona.com from Iona.

click here to go to
My EJB HomePage...

 

About the Author...
Gopalan Suresh Raj is a Software Architect, Developer and an active Author. He is contributing author to a couple of books "Enterprise Java Computing-Applications and Architecture" and "The Awesome Power of JavaBeans". His expertise spans enterprise component architectures and distributed object computing. Visit him at his Web Cornucopia© site (http://www.execpc.com/~gopalan) or mail him at gopalan@execpc.com.

Go to the Component Engineering Cornucopia page

This site was developed and is maintained by Gopalan Suresh Raj

This page has been visited times since September 21,1998.

Last Updated : Dec 19, '98

If you have any questions, comments, or problems regarding this site, please write to me I would love to hear from you.


Copyright (c) 1997-2000, Gopalan Suresh Raj - All rights reserved. Terms of use.

All products and companies mentioned at this site are trademarks of their respective owners.