In this lab, you will create a stateless session bean that could be used in a Web-based, e-commerce application. The session bean will process credit card payments. Actually, your implementation will not really process credit cards, but it will do a quick check to see if a given card number follows the rules for valid numbers.
Here is a UML diagram for your lab:

The chargeCard method in the CreditCard interface accepts three arguments: the card-number String, the date of the charge and the amount. In this lab, the chargeCard method will check the credit card number and throw the InvalidCardNumberException if it's bad. In this release of the program, you will not implement checking of expiration date and charge amount.
You need to create a project that will hold your application. Follow these steps:
From the Eclipse menu, choose File - New - Dynamic Web Project.
On the first wizard page, for the Project name, enter Lab04Web.
Note that the target server is your Tom EE server.
Press Next.
On the next wizard page, note the defaults, then press Next.
On the next page, put a checkmark in the Generate web.xml deployment descriptor box, then press Finish.
You should see the new project in the Project Explorer view.
Expand the Lab04Web/Java Resources entry.
Right-click on src and choose New - Package. Name the new package creditcard.
Right-click on the new package and run the New-Class wizard three times to create Java source files for each of the three exception classes as described in the UML diagram in Figure 1.
Be sure to specify java.lang.Exception as the superclass for each.
Each of the exception classes should define a zero argument constructor that calls the superclass with an informative string, e.g.:
public InvalidCardNumberException()
{
super ( "Number does not follow rules" );
}
Right-click on the project, then choose New - Other - EJB - Session Bean (EJB 3.x) and press Next to start the wizard.
On the first wizard page, for the EJB project, select Lab04Web.
For the Java package, enter creditcard.
For the Classname, enter CreditCardBean.
In the Create business interface section, uncheck the No-interface view checkbox, then put a checkmark in the Remote checkbox. Then enter creditcard.CreditCard for the interface name. Press Next.
On the next wizard page, uncheck the Inherited abstract method and Constructors from superclass checkboxes, then press Finish.
Look in the Project Explorer and note that you can see the source files under the Java Resources/src/creditcard folder.
Double-click CreditCard to open the business interface into the Java editor. Note how the wizard inserted the @Remote annotation, then within the interface, write the business method definition:
public void chargeCard (String cardNo, Date date, double amount)
throws ExpiredException,
InvalidCardNumberException,
RejectedException;
Press Ctrl+S to save.
You will need an import for java.util.Date (choose Source - Organize Imports).
Double-click CreditCardBean to open it into the Java editor, then define a business-logic method:
public void chargeCard ( String cardNo, Date date, double amount )
throws ExpiredException,
InvalidCardNumberException,
RejectedException
{
}
Press Ctrl+S to save.
You will need an import for java.util.Date.
To implement the chargeCard method, you should determine if the card number follows the basic rules governing card numbers. To help you validate (and save you typing), you can copy and paste the private validate method from the provided validate.txt file in the {Lab Installation Directory}/starters/lab04 directory. Be sure to paste the method text within the class, but outside of the chargeCard method.
The completely written validate method uses a well-known algorithm to determine if a number is valid. Note that the algorithm does not actually check the account balance that the number represents -- it simply determines if the number is a proper number and returns a boolean that indicates if the number is valid.
Your chargeCard method should call the validate() method, passing the card number. If the number is not valid (i.e., validate() returns false), your chargeCard method should throw a new InvalidCardNumberException object back to the client. And as stated above, you don't need to check the date or amount, so you are done (i.e. you don't need to do anything if the number is valid).
In this part, you write client program for your credit-card checking EJB. The client will be web-based -- the user will enter credit card info into an HTML form and press a Submit button. The submit button invokes a Java servlet that will act as the EJB client and generate an HTML response back to the user's browser.
The servlet will use dependency injection to retrieve a reference to the EJB and then call the EJB's chargeCard method to validate the credit-card number entered by the user.
Import the fully completed CreditCard.html file via the File System from the {Lab Installation directory}/starters/lab04 folder:
In the Project Explorer, right-click on the new project's WebContent folder and choose Import... to start the import wizard.
On the first wizard page, choose General - File system, then press Next.
On the next wizard page, for the From directory, press the Browse button and navigate to the {Lab Installation Directory}/starters/lab04 folder, then press OK. If your computer has the standard lab setup on Windows XP, the proper directory is:
c:\jeeclass\starters\lab04
On Windows Vista or later:
c:\Users\username\jeeclass\starters\lab04
In the left pane, click on lab04 to highlight it, then put a checkmark next to CreditCard.html and snippets.txt entries in the right pane.
Press Finish to complete the import. You should see the imported files in the project's WebContent folder.
Double-click on CreditCard.html to open it into the editor.
Then examine the HTML and note how it defines an input form that invokes a servlet named CheckCardServlet and how the form defines input fields, including a field for the credit card number.
Next, create the Java class for your servlet. Follow these steps:
In the Project Explorer, in the Lab04Web project, right-click on Java Resources/src and choose New - Servlet to start the wizard.
On the first wizard page, for the Java package enter servlets.
For the Class name, enter CheckCardServlet, then press Next.
On the next page, note the URL Mapping, which assigns a URL to the servlet, then press Next.
On the next wizard page, uncheck the doPost checbox, then press Finish. Eclipse opens the servlet class into the editor.
Complete the servlet:
Define a private field named cardService of type CreditCard.
You will need to import creditcard.CreditCard.
Use dependency injection so that the container initializes the field.
You will need to import javax.ejb.EJB.
Next, complete the doGet method. Follow these steps:
Copy and pasting from the snippets.txt file, set the content type and retrieve a PrintWriter:
resp.setContentType ( "text/html" );
PrintWriter out = resp.getWriter();
Retrieve the data from the input form's cardType, cardholderName, cardNumber, expirationDate and amount widgets into Strings:
String cardType = req.getParameter ( "cardType" );
String cardNumber = req.getParameter ( "cardNumber" );
String cardHolderName = req.getParameter ( "cardholderName" );
String sExpiry = req.getParameter ( "expirationDate" );
String sAmount = req.getParameter ( "amount" );
Convert the amount and date Strings into proper Java types:
SimpleDateFormat df =
new SimpleDateFormat ( "MM/yyyy" );
Date date = null;
double amount = 0;
try
{
date = df.parse ( sExpiry );
amount = Double.parseDouble ( sAmount );
}
catch ( Exception exc )
{
throw new ServletException ( exc );
}
You will need to import types as necessary. Choose java.util.Date for the Date import.
Call the chargeCard method, passing the checkNumber, date and amount parameters.
Highlight that line of code, then choose Source - Surround With - Try/catch block so that Eclipse writes simple exception handling code.
Within the try block, output an HTML message that indicates success:
out.println ( "Charge was successful" );
Within each catch block, modify the generated code to output a failure message:
out.println(e.getMessage());
To test, right-click on CreditCard.html and choose Run As - Run on Server, then wait for the Web page to appear.
Enter all of the information, using a valid credit card number e.g. 49927398716. Then press Submit. Do you see your "OK" message? Try again using an invalid number e.g. 49927398717 (last number different). What happens?
Remove the project from the server and close all Eclipse windows.