You are on page 1of 39

 

Working with JBOSS Application Server


SkillSoft. (c) 2003. Copying Prohibited.

  

Reprinted for Ashutosh Patel, Accenture


ashutosh.patel@accenture.com

All rights reserved. Reproduction and/or distribution in whole or in part in electronic,paper or


other forms without written permission is prohibited.
Working with JBOSS Application Server

Appendix A: Creating a Resort Rental Application


Resort Rental is an enterprise application that enables you to view information about a group of holiday resorts. An end user can select a
resort from the group and view information about the rooms and suites available in these resorts.
The Web and middle tier components in the Resort Rental application are deployed on JBoss using the Java Management Extensions (JMX)
main deployer MBean. In addition, the JMX Agent provided by the JBoss management console, monitors Web-based activity, and enables the
JBoss-Jetty service to provide the runtime for Web components in this application. The Resort Rental Application uses the JBoss Naming
Service to enable Web components to obtain a reference to the home object of a session bean. The business methods of this session bean
perform local transactions using a predefined Java Connector Architecture (JCA) component called jboss-local-jdbc.rar.

This appendix explains the components in the Resort Rental application, which enables end users to register, view rental information, or book
rooms or suites in these resorts.

Describing the Application


This application implements J2EE design patterns that provide reusable solutions to common design problems. These design patterns enable
you to customize applications based on structure, scalability, and performance. The J2EE architecture for the Resort Rental application
comprises of presentation, business, and data tier components that implements design patterns such as the Front controller, Service Locator,
and Session Facade.
The Resort Rental application, including Web and server side components, is classified into two modules, the presentation tier and the middle
tier. The presentation tier module consists of JSP pages and a front controller servlet. The JSP pages provide the user interface for this
application and a front controller servlet helps process end user requests. In addition, this module includes Java classes that enable the front
controller servlet to centrally manage access to components in this application.

The middle tier components consist of classes, which encapsulate Java DataBase Connectivity (JDBC) logic required to access information
in database tables. The presentation tier components invoke the business methods of the session bean to view information about resorts and
book rooms or suites. The presentation tier and the middle tier components make use of value objects that represents database table or
information about the end user.

The Presentation Tier Module


The presentation tier module includes the following components:

n index.jsp: Contains the home page for the Resort Rental application.

n newuser.jsp: Provides a form used by an end user to register on the Web site.

n registered.jsp: Displays a message when an end user successfully creates a new user id.

n login.jsp: Enables a registered customer to login.

n nosuchuser.jsp: Displays a message when an unknown customer tries to login.

n wrongpassword.jsp: Displays a message when a registered end user submits a wrong password.

n display.jsp: Provides a link to display all available resorts.

n displayresorts.jsp: Displays information about all available resorts.

n displayresortdata.jsp: Displays information about rooms and rental rates and provides a form to rent a room or suite.

n message.jsp: Displays the booking confirmation and the total cost.

n ControllerServlet: Defines the front controller servlet.

n ControllerHelper: Defines a helper class for the front controller servlet.

n LoginDataAccessor: Defines a data accessor class that encapsulates information in a customer table.

n ResortBeansLocator: Defines a naming service locator class that enables application components to perform a JNDI lookup in the
JBossNS.

The Middle Tier Module


n ResortDataAccessor: Defines a data accessor class that encapsulates information in a resorts table.

n ResortSession: Defines a remote interface of the session bean.

n ResortSessionHome: Defines the home interface of the session bean.

Page 2 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

n ResortSessionBean: Defines the session bean class.

Creating the Value Objects


You create value objects to represent database table data and end user data. The Resort Rental application contains four value objects to hold
data about the available resorts, packages, rates of the resorts, and end user.

Creating the Resorts Value Object


The Resorts value object holds information about the available resorts. This value object contains getter and setter methods to set and get the
resort ID, name, and the location of the resort. Listing A-1 creates the Resorts value object as a serializable object:

Listing A-1: The Resorts.java File

package controller;
import java.io.Serializable;
// Declare a public class and implement Serializable interface
public class Resorts implements Serializable
{
private String resortID;
private String resortName;
private String resortLocation;
public Resorts()
{
}
// Accessor and mutator methods
public String getResortID()
{
return resortID;
}
public void setResortID(String resortID)
{
this.resortID = resortID;
}
public String getResortName()
{
return resortName;
}
public void setResortName(String resortName)
{
this.resortName = resortName;
}
public String getResortLocation()
{
return resortLocation;
}
public void setResortLocation(String resortLocation)
{
this.resortLocation = resortLocation;
}
}

Creating the Packages Value Object


The Packages value object holds information about the various package types of the available resorts. This value object contains getter and
setter methods to set and get data about package types, such as luxury, presidential, and penthouse and the resort ID. Listing A-2 creates the
Packages value object as a serializable object:

Listing A-2: The Packages.java File

package controller;
// Import necessary package
import java.io.Serializable;
public class Packages implements Serializable
{
// Declaring variables
private String resortID;

Page 3 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

private int luxury;


private int Presedential;
private int pentHouse;
// Default constructor
public Packages()
{
}
// Accessor and mutator methods
public String getResortID()
{
return resortID;
}
public void setResortID(String resortID)
{
this.resortID = resortID;
}
public int getLuxury()
{
return luxury;
}
public void setLuxury(int luxury)
{
this.luxury = luxury;
}
public int getPresedential()
{
return Presedential;
}
public void setPresedential(int Presedential)
{
this.Presedential = Presedential;
}
public int getPentHouse()
{
return pentHouse;
}
public void setPentHouse(int pentHouse)
{
this.pentHouse = pentHouse;
}
}

Creating the Rates Value Object


The Rates value object holds information about the rates of various resort package types. This value object contains getter and setter methods
to set and get data about rates of package types, such as luxury, presidential, and penthouse. Listing A-3 creates the Rates value object as a
serializable object:

Listing A-3: The Rates.java File

package controller;
// Import necessary packages
import java.io.Serializable;
public class Rates implements Serializable
{
// Declare variables
private String resortID;
private int luxury;
private int Presedential;
private int pentHouse;
// Default constructor
public Rates()
{
}
// Accessor and mutator methods
public String getResortID()
{
return resortID;

Page 4 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

}
public void setResortID(String resortID)
{
this.resortID = resortID;
}
public int getLuxury()
{
return luxury;
}
public void setLuxury(int luxury)
{
this.luxury = luxury;
}
public int getPresedential()
{
return Presedential;
}
public void setPresedential(int Presedential)
{
this.Presedential = Presedential;
}
public int getPentHouse()
{
return pentHouse;
}
public void setPentHouse(int pentHouse)
{
this.pentHouse = pentHouse;
}
}

Creating the Customer Value Object


The Customer value object holds information about the end user. This value object contains getter and setter methods to set and get end user
data, such as email, password, name, and social security number. Listing A-4 shows the Customer class:

Listing A-4: The Customer.java File

package controller;
// Import necessary packages
import java.io.Serializable;
public class Customer implements Serializable
{
// Declaring variables
private String emailID;
private String password;
private String customerName;
private String address;
private String socialSecurityNumber;
// Create default constructor
public Customer()
{
}
// Create Customer object with all the data
public Customer(String emailID, String password, String customerName,
String address, String socialSecurityNumber)
{
this.emailID = emailID;
this.password = password;
this.customerName = customerName;
this.address = address;
this.socialSecurityNumber = socialSecurityNumber;
}
// Accessor and mutator method for member variables
public void setEmailID(String emailID)
{
this.emailID = emailID;
}

Page 5 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

public void setPassword(String password)


{
this.password = password;
}
public void setCustomerName(String customerName)
{
this.customerName = customerName;
}
public void setAddress(String address)
{
this.address = address;
}
public void setSocialSecurityNumber(String socialSecurityNumber)
{
this.socialSecurityNumber = socialSecurityNumber;
}
public String getEmailID()
{
return emailID;
}
public String getPassword()
{
return password;
}
public String getCustomerName()
{
return customerName;
}
public String getAddress()
{
return address;
}
public String getSocialSecurityNumber()
{
return socialSecurityNumber;
}
}

Creating the Bookings Value Object


The Bookings value object holds information about the booking to the resort made by the end user. This value object contains getter and setter
methods to set and get room booking data, such as booking person, number of luxury rooms required, numbers of penthouse, presidential
suites required, number of days of stay, and number of adults and children. Listing A-5 creates the Bookings value object as a serializable
object:

Listing A-5: Bookings Class

package controller;
import java.io.Serializable;
// Declare the class as public and implement the Serializable interface
public class Bookings implements Serializable
{
// Declare the member attributes
private String emailID;
private String resortID;
private String bookingPersonName;
private int luxuryNos;
private int PresedentialNos;
private int penthouseNos;
private int days;
private int adults;
private int children;
// Declare a null parameter constructor
public Bookings()
{ }
// Declare an overloaded constructor
public Bookings(String emailID, String resortID, String bookingPersonName,
int luxuryNos, int PresedentialNos, int penthouseNos, int days,

Page 6 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

int adults, int children)


{
this.emailID = emailID;
this.resortID = resortID;
this.bookingPersonName = bookingPersonName;
this.luxuryNos = luxuryNos;
this.PresedentialNos = PresedentialNos;
this.penthouseNos = penthouseNos;
this.days = days;
this.adults = adults;
this.children = children;
}
// Define the setter methods
public void setEmailID(String emailID)
{
this.emailID = emailID;
}
public void setResortID(String resortID)
{
this.resortID = resortID;
}
public void setBookingPersonName(String bookingPersonName)
{
this.bookingPersonName = bookingPersonName;
}
public void setLuxuryNos(int value)
{
this.luxuryNos = value;
}
public void setPresedentialNos(int value)
{
this.PresedentialNos = value;
}
public void setPenthouseNos(int value)
{
this.penthouseNos = value;
}
public void setDays(int value)
{
this.days = value;
}
public void setAdults(int value)
{
this.adults = value;
}
public void setChildren(int value)
{
this.children = value;
}
// Define the getter methods
public String getEmailID()
{
return emailID;
}
public String getResortID()
{
return resortID;
}
public String getBookingPersonName()
{
return bookingPersonName;
}
public int getLuxuryNos()
{
return this.luxuryNos;
}
public int getPresedentialNos()
{
return this.PresedentialNos;

Page 7 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

}
public int getPenthouseNos()
{
return this.penthouseNos;
}
public int getDays()
{
return this.days;
}
public int getAdults()
{
return this.adults;
}
public int getChildren()
{
return this.children;
}
}

Creating Presentation Tier Components


Presentation tier components provide the user interface to the resort rental application. They enable the customer to register in this site, and
view resort rental rates and room types available. The front controller servlet called ControllerServlet class controls all action in the presentation
tier. All requests from the application are directed to this servlet, which parses the request to identify the request parameters and redirects the
customer to appropriate JSP pages.

Creating the index.jsp Page


The index.jsp is the application home page. This page provides options to register a customer, or enables a customer to logon. Listing A-6
shows the index.jsp page:

Listing A-6: The index.jsp File

<%@ page language="Java" %>


<HTML>
<HEAD>
<TITLE>Home Page</TITLE>
<HEAD>
<BODY>
<CENTER>
<font size="7" color="blue" face="Lucida Console">
<i>ABC</i> Holiday Resorts
<HR>
</font>
<A HREF="Controller?option=member"><H4> [ Login ] </H4></A>
<A HREF="Controller?option=new"><H4> [ Sign Up ] </H4></A>
</CENTER>
</BODY>
</HTML>

The above listing provides hyperlinks to invoke the ControllerServlet class. These links assign a query string value member to enable existing
customer logon and a value new to redirect the end user to a registration page.

Creating the newuser.jsp Page


The newuser.jsp page provides a form to obtain information about an end user. Listing A-7 shows the newuser.jsp page:

Listing A-7: The newuser.jsp File

<%@ page language="Java"%>


<HTML>
<HEAD>
<TITLE>New User Login</TITLE>
<SCRIPT language="JAVASCRIPT">
<!--
function validate(a)
{

Page 8 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

var valid=true;
if(a.emailID.value.length==0)
{
valid=false;
alert("Username cannot be left blank");
a.emailID.focus();
}
else if(a.password.value.length==0)
{
valid=false;
alert("Password cannot be left blank");
a.password.focus();
}
else if(a.customerName.value.length==0)
{
valid=false;
alert("Name cannot be left blank");
a.customerName.focus();
}
else if(a.address.value.length==0)
{
valid=false;
alert("Address cannot be left blank");
a.address.focus();
}
else if(a.socialSecurityNumber.value.length==0)
{
valid=false;
alert("Social Security Number cannot be left blank");
a.socialSecurityNumber.focus();
}
return valid;
}
-->
</SCRIPT>
</HEAD>
<BODY>
<CENTER>
<FONT size="7" color="blue" face="Lucida Console">
<I>ABC</I> Holiday Resorts
<HR>
</FONT>
</CENTER>
<H3 ALIGN=center>New User Registration</H3>
<FORM ACTION="Controller?option=register" METHOD="post" onSubmit="return validate(this)">
<TABLE ALIGN=center WIDTH=75%>
<TR>
<TD>UserId</TD>
<TD><INPUT TYPE=text NAME="emailID"></TD>
</TR>
<TR>
<TD>Password</TD>
<TD><INPUT TYPE=password NAME="password"></TD>
</TR>
<TR>
<TD>Name</TD>
<TD><INPUT TYPE=text NAME="customerName"></TD>
</TR>
<TR>
<TD>Address</TD>
<TD><INPUT TYPE=text NAME="address"></TD>
</TR>
<TR>
<TD>Social Security Number</TD>
<TD><INPUT TYPE=text NAME="socialSecurityNumber"></TD>
</TR>
<TR>
<TD><INPUT TYPE=hidden NAME=option VALUE="register">
<TD><INPUT TYPE=submit VALUE=SUBMIT>

Page 9 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

</TR>
</TABLE>
</FORM>
<A HREF="index.jsp"><font color=blue face="Comic Sans" >[Home]</FONT></A>
</BODY>
</HTML>

The above listing provides a form to accept a customer name, address, email ID, and social security number. Validations are also performed
for the input information. The application registers an end user with the specified information and creates a record for this end user.

Creating the registered.jsp Page


The registered.jsp page is invoked when the end user successfully creates a new user id. Listing A-8 shows the code in the registered.jsp
page:

Listing A-8: The registered.jsp Page

<%@ page language="Java" %>


<HTML>
<HEAD>
<TITLE>Message Page</TITLE>
</HEAD>
<BODY>
<CENTER>
<FONT size="7" color="blue" face="Lucida Console">
<I>ABC</I> Holiday Resorts
<HR>
</FONT>
</CENTER>
<H3>You have been registered successfully !</H3>
<A href="index.jsp"><font color=blue face="Comic Sans" >[ Home ]</FONT></A>
</BODY>
</HTML>

The above listing shows a message and provides a link to the index.jsp page.

Creating the login.jsp Page


The login.jsp page provides a form to specify a registered customer name and ID. When the login is successful, the customer can view the
display JSP page. Listing A-9 shows the code for the login.jsp page:

Listing A-9: The login.jsp File

<%@ page language="Java" %>


<HTML>
<HEAD>
<TITLE>Login Page</TITLE>
<SCRIPT language="JAVASCRIPT">
function validate(a)
{
var valid=true;
if(a.emailID.value.length==0)
{
valid=false;
alert("Username cannot be left blank");
a.emailID.focus();
}
else if(a.password.value.length==0)
{
valid=false;
alert("Password cannot be left blank");
a.password.focus();
}
return valid;
}
-->
</SCRIPT>

Page 10 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

</HEAD>
<BODY>
<CENTER>
<FONT size="7" color="blue" face="Lucida Console">
<I>ABC</I> Holiday Resorts
<HR>
</FONT>
</CENTER>
<CENTER>
<FORM METHOD="post" ACTION="Controller?option=validate" onSubmit="return validate(this)"
<TABLE border="0" cellspacing="6" >
<TR>
<TD>UserId</TD>
<TD><INPUT type="text" name="emailID" size="20"></TD>
</TR>
<TR>
<TD>Password</TD>
<TD><INPUT type="password" name="password" size="20"></TD>
</TR>
<TR>
<TD>&nbsp;
<TD><INPUT type="submit" value="Login"></TR>
</TABLE>
</FORM>
</CENTER>
</BODY>
</HTML>

The above listing shows code to specify an email ID, which is the username of a registered end user and a password. When the end user
submits this form, a query string value, validate, is passed to the ControllerServlet class.

Creating the nosuchuser.jsp Page


The nosuchuser.jsp page is invoked when an invalid end user tries to login to the application. Listing A-10 shows the code for the
nosuchuser.jsp page:

Listing A-10: The nosuchuser.jsp File

<%@ page language="Java" %>


<HTML>
</HEAD>
<TITLE>Message Page</TITLE>
</HEAD>
<BODY>
<CENTER>
<FONT size="7" color="blue" face="Lucida Console">
<I>ABC</I> Holiday Resorts
<HR>
</FONT>
</CENTER>
<H3>No such user found !</H3>
<A HREF="index.jsp"><font color=blue face="Comic Sans" >[ Home ]</FONT></A>
</BODY>
</HTML>

The above listing displays an error message when an unknown end user tries to logon to the application. It provides a link to return to the home
page.

Creating the wrongpassword.jsp Page


The wrongpassword.jsp page is invoked when the customer performs a login with an incorrect password. Listing A-11 shows the
wrongpassword.jsp page:

Listing A-11: The wrongpassword.jsp File

<%@ page language="Java" %>


<HTML>

Page 11 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

</HEAD>
<TITLE>Message Page</TITLE>
</HEAD>
<BODY>
<CENTER>
<FONT size="7" color="blue" face="Lucida Console">
<I>ABC</I> Holiday Resorts
<HR>
</FONT>
</CENTER>
<H3>Wrong password !</H3>
<A HREF="index.jsp"><font color=blue face="Comic Sans" >[ Home ]</FONT></A>
</BODY>
</HTML>

The above listing shows code to displays a message, when an end user provides an incorrect password, and enables the end user to return to
the application home page.

Creating the display.jsp Page


The display.jsp page contains code to invoke the displayresorts page and enables the end user to view the list of resorts. Listing A-12 shows
the code for the display.jsp page:

Listing A-12: The display.jsp File

<%@ page language="Java" %>


<HTML>
<HEAD>
<TITLE>Resorts</TITLE>
</HEAD>
<BODY>
<CENTER>
<FONT size="7" color="blue" face="Lucida Console">
<I>ABC</I> Holiday Resorts
<HR>
</FONT>
</CENTER>
<%
String user=(String) request.getAttribute("emailID");
%>
<CENTER>
<A HREF="Controller?option=displayall&emailID=<%=user%>"><H2>Display Resorts </H2></A>
</CENTER>
</BODY>
</HTML>

The above listing shows the code to assign a query string value, displayall, to the ControllerServlet class. This query string is used to invoke
code to display links to all resorts.

Creating the displayresorts.jsp Page


The displayresorts.jsp page displays links for all resorts. The customer can select and resort to be redirected to another page that shows
information about the types of rooms and suites available in the selected resort. Listing A-13 shows the displayresorts.jsp page:

Listing A-13: The displayresorts.jsp File

<%@ page language="Java" import="java.util.*,controller.*" %>


<HTML>
<HEAD>
<TITLE>Resorts - All </TITLE>
</HEAD>
<BODY>
<CENTER>
<FONT size="7" color="blue" face="Lucida Console">
<I>ABC</I> Holiday Resorts
<HR>
</FONT>

Page 12 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

</CENTER>
<center>
<%
Vector resort = (Vector) request.getAttribute("resort");
String user=(String) request.getAttribute("emailID");
int sizeResort=resort.size();
if (sizeResort>0)
{
%>
<H3>Click on any one of the resorts</H3>
<%
for(int i=0;i<sizeResort;i++)
{
Resorts resorts=(Resorts) resort.get(i);
String key = resorts.getResortID();
String value = resorts.getResortName();
%>
<A HREF="Controller?option=dispResort
&emailID=<%=user%>&id=<%= key.trim() %>">
<%= value.trim() %></A><P>
<%
}
}
%>
</center>
</BODY>
</HTML>

The above listing shows the code to obtain a request attribute called resort. This attribute contains a Vector object that contains key-value
pairs of the ID and name of a resort. The ID is used to create an instance of a Java bean called Resorts. This class contains an accessor
method called getResorts(). This method is used to retrieve the names of the available resorts.

Creating the displayresortdata.jsp Page


The displayresortdata.jsp page is invoked when the customer selects a resort from the displayresorts page. The displayresortdata page
displays information about the luxury rooms or penthouses available for rent. This page also provides a form to specify the number of rooms
required and the number of days for which these rooms are rented.
Listing A-14 shows the code for the displayresortdata.jsp page:

Listing A-14: The displayresortdata.jsp File

<%@ page language="Java" import="controller.*,java.util.*"%>


<HTML>
<HEAD>
<TITLE>Resort Information</TITLE>
<script language="JAVASCRIPT">
<!--
function validate(a)
{
var valid=true;
if(a.bookingPersonName.value.length==0) {
valid=false;
alert("Name of the booking person cannot be left blank");
a.bookingPersonName.focus();
}else if(a.luxuryNos.value.length==0) {
valid=false;
alert("The Field cannot be left blank. Enter 0 if not required");
a.luxuryNos.focus();
}else if(a.PresedentialNos.value.length==0) {
valid=false;
alert("The Field cannot be left blank. Enter 0 if not required");
a.PresedentialNos.focus();
}else if(a.penthouseNos.value.length==0) {
valid=false;
alert("The Field cannot be left blank. Enter 0 if not required");
a.penthouseNos.focus();
}else if(a.days.value.length==0) {

Page 13 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

valid=false;
alert("Days cannot be left blank.");
a.days.focus();
}else if(a.adults.value.length==0) {
valid=false;
alert("The Field cannot be left blank. Enter 0 if not required");
a.adults.focus();
}else if(a.children.value.length==0) {
valid=false;
alert("The Field cannot be left blank. Enter 0 if not required");
a.children.focus();
}
if(valid)
{
valid=isItNumeric(a)
}
return valid;
}
function isItNumeric(a)
{
var luxNos=a.luxuryNos.value;
var presNos=a.PresedentialNos.value;
var pentNos=a.penthouseNos.value;
var days=a.days.value;
var adults=a.adults.value;
var children=a.children.value;
if (isNaN (luxNos))
{
alert (" Invalid Number ");
a.luxuryNos.select();
return false;
}
if (isNaN (presNos))
{
alert (" Invalid Number ");
a.PresedentialNos.select();
return false;
}
if (isNaN (pentNos))
{
alert (" Invalid Number ");
a.penthouseNos.select();
return false;
}
if (isNaN (days))
{
alert (" Invalid Number ");
a.days.select();
return false;
}
if (isNaN (adults))
{
alert (" Invalid Number ");
a.adults.select();
return false;
}
if (isNaN (children))
{
alert (" Invalid Number ");
a.children.select();
return false;
}
}
-->
</script>
</HEAD>
<BODY>
<CENTER>
<FONT size="7" color="blue" face="Lucida Console">

Page 14 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

<I>ABC</I> Holiday Resorts


<HR>
</FONT>
</CENTER>
<%
Vector vector = (Vector)request.getAttribute("resort");
String user=(String) request.getAttribute("emailID");
String resortID = (String)vector.get(0);
Packages packages = (Packages)vector.get(1);
Rates rates = (Rates)vector.get(2);
int luxuryRooms = packages.getLuxury();
int PresedentialRooms = packages.getPresedential();
int pentHouses = packages.getPentHouse();
int luxuryRate = rates.getLuxury();
int PresedentialRate = rates.getPresedential();
int pentHouseRate = rates.getPentHouse();
%>
<TABLE width="75%" align="center" border="0" cellspacing="6" >
<TR>
<TH>&nbsp;</TH>
<TH>LUXURY</TH>
<TH>PRESIDENTIAL</TH>
<TH>PENTHOUSE</TH>
</TR>
<TR>
<TD align="center"><B>ROOMS AVAILABLE</B></TD>
<TD align="center"><%= luxuryRooms %></TD>
<TD align="center"><%= PresedentialRooms %></TD>
<TD align="center"><%= pentHouses %></TD>
</TR>
<TR>
<TD align="center">
<B>RATES in US$</B><br>
<SMALL>[per day for one]</SMALL>
</TD>
<TD align="center"><%= luxuryRate %></TD>
<TD align="center"><%= PresedentialRate %></TD>
<TD align="center"><%= pentHouseRate %></TD>
</TR>
</table>
<H4>Fill the form to book a resort</H4>
<FORM METHOD="post" ACTION="Controller?option=book" onSubmit="return validate(this)">
<input type=hidden value="<%=resortID%>" name="id" >
<input type=hidden value="<%=user%>" name="emailID" >
<TABLE>
<TR>
<TD>Name of the booking person</TD>
<TD><INPUT type="text" name="bookingPersonName" size="20"></TD>
</TR>
<TR>
<TD>Number of luxury rooms</TD>
<TD><INPUT type="text" name="luxuryNos" maxlength="3" size="10"></TD>
</TR>
<TR>
<TD>Number of presidential rooms</TD>
<TD><INPUT type="text" name="PresedentialNos" maxlength="3" size="10"></TD>
</TR>
<TR>
<TD>Number of penthouse rooms</TD>
<TD><INPUT type="text" name="penthouseNos" maxlength="3" size="10"></TD>
</TR>
<TR>
<TD>Number of days to rent</TD>
<TD><INPUT type="text" name="days" maxlength="3" size="10"></TD>
</TR>
<TR>
<TD>No of adults</TD>
<TD><INPUT type="text" name="adults" maxlength="3" size="10"></TD>
</TR>

Page 15 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

<TR>
<TD>No of children</TD>
<TD><INPUT type="text" name="children" maxlength="3" size="10"></TD>
</TR>
<TR>
<TD><INPUT type="submit" value="BOOK RESORT"></TD>
</TR>
</TABLE>
</FORM>
<%
request.setAttribute("ResortDate",vector);
%>
</BODY>
</HTML>

The above listing creates instances of two Java bean classes, Packages and Rates. The Packages bean displays information about the
number of luxury rooms, penthouses, and presidential suites available in a resort. The Rates bean displays the rental rates for these rooms.

Creating the message.jsp Page


The message.jsp page is invoked when the customer books for a resort from the displayresortsdata page. This page displays the total cost for
booking the resort. Listing A-15 shows the code for the message.jsp page:

Listing A-15: The message.jsp File

<%@ page language="Java" import="java.util.*,controller.*" %>


<HTML>
<HEAD>
<TITLE>Booking Confirmation</TITLE>
</HEAD>
<BODY>
<CENTER>
<FONT size="7" color="blue" face="Lucida Console">
<I>ABC</I> Holiday Resorts
<HR>
</FONT>
</CENTER>
<CENTER>
<H3>Your booking has been confirmed</H3>
<H5>Further information will be sent through e-mail</H5>
<%
int cost=((Integer) request.getAttribute("cost")).intValue();
%>
<H4>Total Cost :<%=("US$ "+cost) %> </H4>
</BODY>
</HTML>

Creating the ControllerServlet Class


The ControllerServlet class manages access to the ResortRental application. It redirects requests to appropriate JSP pages depending on
request parameters passed from the browser. Listing A-16 shows the code for the ControllerServlet class:

Listing A-16: The ControllerServlet.java File

package controller;
// Import necessary packages
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ControllerServlet extends HttpServlet
{
private ServletConfig config;
// init method that gets config object
public void init(ServletConfig config)
throws ServletException
{

Page 16 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

super.init(config);
this.config=config;
}
// get method that receives request
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
processRequest(request,response);
}
// post method that receives request
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
processRequest(request,response);
}
// Method that delegates tasks to the helper class
private void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
/* All request parameters from the client is encapsulated in a
HashMap object and then sent to the helper class for providing
desired service. */
HashMap hmap=new HashMap();
Enumeration enum=request.getParameterNames();
while(enum.hasMoreElements())
{
String key=(String) enum.nextElement();
String value=request.getParameter(key);
hmap.put(key,value);
}
// Creating an object for helper class and passing the HashMap
// object to the helper method
ControllerHelper helper=new ControllerHelper(config);
HashMap returnMap = helper.processRequest(hmap);
String page = (String) returnMap.get("page");
String message = (String) returnMap.get("message");
Vector resort = (Vector) returnMap.get("resort");
if(resort != null)
{
request.setAttribute("resort",resort);
}
String emailID = (String)returnMap.get("emailID");
if(emailID != null)
{
request.setAttribute("emailID",emailID);
}
Integer cost = (Integer)returnMap.get("cost");
if(cost != null)
{
request.setAttribute("cost",cost);
}
forwardRequest(request,response,page);
}
// Local method that uses a RequestDispatcher object to forward
// requests and responses to the client
private void forwardRequest(HttpServletRequest request, HttpServletResponse response,
String page)
throws ServletException, IOException
{
RequestDispatcher dispatcher = request.getRequestDispatcher(page);
dispatcher.forward(request,response);
}
}

The ControllerServlet class in the above listing contains doGet() and doPost() methods to process HTTP GET and POST request. This class
defines a method called processRequest that is invoked by the doGet() and doPost() methods. The processRequest method stores request
parameters in a HashMap object. This method then creates an instance of a helper class called ControllerHelper. The ControllerHelper class
maintains information about a redirection page, message, and resort in a HashMap. This HashMap is retrieved by the ControllerServlet to

Page 17 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

redirect the customer to an appropriate page based on the request parameters.

Creating the ControllerHelper Class


The ControllerHelper class enables the ControllerServlet class to manage requests to this application. This class maintains request options
assigned from the ControllerServlet class in a HashMap object. The class uses the elements of this HashMap to register a new customer,
validate a login, display information about resorts, or obtain a reference to the home object of the session bean and invoke its business
methods. Listing A-17 shows the code for the ControllerHelper class:

Listing A-17: The ControllerHelper.java File

package controller;
// Import necessary packages
import java.util.HashMap;
import java.util.Vector;
import javax.servlet.ServletConfig;
public class ControllerHelper
{
// Declare necessary variables
private HashMap hashMap;
private ServletConfig config;
private ResortBeansLocator locator = null;
private ResortSessionHome home = null;
ResortSession remote = null;
// Create a default no argument constructor
public ControllerHelper()
{
}
// Create a constructor that accepts config object
public ControllerHelper(ServletConfig config)
{
this.config=config;
}
// Method that provides appropriate service to provide to client based on request
public HashMap processRequest(HashMap hashMap)
{
this.hashMap = hashMap;
String page = null;
String message = null;
HashMap hmap = null;
// Get the type of service required by the client
String option =(String)hashMap.get("option");
getSessionJNDI();
try
{
hmap = new HashMap();
// If client is not a member, ask him to register first
if(option.equals("new"))
{
// Redirecting to register page
page = "/WEB-INF/newuser.jsp";
}
// If a client wants to register, get his details
else if(option.equals("register"))
{
// Retrieve client details
String emailID=(String) hashMap.get("emailID");
String password=(String) (String) hashMap.get("password");
String customerName= (String) hashMap.get("customerName");
String address=(String) hashMap.get("address");
String socialSecurityNumber=(String)hashMap.get("socialSecurityNumber");
// Create a Customer ValueObject
Customer customerVO = new Customer();
// Use ValueObject setter method to set client data
customerVO.setEmailID(emailID);
customerVO.setPassword(password);
customerVO.setCustomerName(customerName);
customerVO.setAddress(address);
customerVO.setSocialSecurityNumber(socialSecurityNumber);

Page 18 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

/* Create a data accessor object for validating and inserting


client data */
LoginDataAccessor loginDAO = new LoginDataAccessor();
/* Invoke validate method on data accessor object to check if
client is already a member */
int validCust = loginDAO.validate(customerVO);
if(validCust == 1)
{
// Use data accessor object's insert method to insert
// client data
int j = loginDAO.insert(customerVO);
if(j > 0)
{
// Redirect to display insert feedback
page="/WEB-INF/registered.jsp";
}
}
else
{
// If client is a registered user, redirect him
page = "/WEB-INF/newuser.jsp";
}
// Close connection after validating
loginDAO.closeConnection();
}
// If client is a member, redirect to login once again
else if(option.equals("member"))
{
page = "/WEB-INF/login.jsp";
}
// Validate client login information
else if(option.equals("validate"))
{
// Retrieve user name and password from client
String emailID = (String) hashMap.get("emailID");
String password = (String) (String) hashMap.get("password");
// Create a Customer ValueObject with user name and password
Customer customerVO=new Customer();
customerVO.setEmailID(emailID);
customerVO.setPassword(password);
// Create a data accessor ValueObject
LoginDataAccessor loginDAO=new LoginDataAccessor();
// Invoke validate method on data accessor ValueObject
int result = loginDAO.validate(customerVO);
loginDAO.closeConnection();
if(result == 0)
{
// If user name and password are correct, redirect.
hmap.put("emailID",emailID);
page = "/WEB-INF/display.jsp";
}
if(result == 1)
{
// If user name not found, redirect him
page = "/WEB-INF/nosuchuser.jsp";
}
if(result == 2)
{
// If password is wrong, redirect him
page = "/WEB-INF/wrongpassword.jsp";
}
}
else if(option.equals("displayall"))
{
// Invoke session beans business method
// display all available resorts
String emailID=(String) hashMap.get("emailID");
Vector resortsAll=remote.displayResorts();
// Display all available resorts by redirecting to a jsp file

Page 19 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

page="/WEB-INF/displayresorts.jsp";
hmap.put("emailID",emailID);
hmap.put("resort",resortsAll);
}
// If client wants to look at all data for a particular resort
else if(option.equals("dispResort"))
{
String emailID = (String) hashMap.get("emailID");
// Invoke session beans business method
// Display details of a particular resort
String resortID = (String) hashMap.get("id");
// Display resort data by redirecting
page = "/WEB-INF/displayresortdata.jsp";
Vector resort = remote.displayResortData(resortID);
hmap.put("emailID",emailID);
hmap.put("resort",resort);
}
// If client wants to book a resort
else if(option.equals("book"))
{
// Get all booking information from HashMap
String emailID = (String) hashMap.get("emailID");
String resortID = (String) hashMap.get("id");
String bookingPersonName = (String)hashMap.get("bookingPersonName");
String luxuryNos = (String)hashMap.get("luxuryNos");
String PresedentialNos = (String)hashMap.get("PresedentialNos");
String penthouseNos = (String)hashMap.get("penthouseNos");
String days = (String)hashMap.get("days");
String adults = (String)hashMap.get("adults");
String children = (String)hashMap.get("children");
Bookings bookings = new Bookings();
bookings.setEmailID(emailID);
bookings.setResortID(resortID);
bookings.setBookingPersonName(bookingPersonName);
bookings.setLuxuryNos(Integer.parseInt(luxuryNos));
bookings.setPresedentialNos(Integer.parseInt(PresedentialNos));
bookings.setPenthouseNos(Integer.parseInt(penthouseNos));
bookings.setDays(Integer.parseInt(days));
bookings.setAdults(Integer.parseInt(adults));
bookings.setChildren(Integer.parseInt(children));
// Invoke session beans business method
// Display details of a particular resort
page="/WEB-INF/message.jsp";
int cost = remote.bookResort(bookings);
hmap.put("cost",new Integer(cost));
hmap.put("emailID",emailID);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
hmap.put("page",page);
hmap.put("message",message);
return hmap;
}
public void getSessionJNDI()
{
try
{
// Create an instance of session bean service locator
locator=ResortBeansLocator.getInstance();
// Get a reference to session bean's home object
home = (ResortSessionHome)
locator.getHome("ResortBean", ResortSessionHome.class);
// Get a reference to session bean's remote object
remote=(ResortSession)home.create();
}
catch(Exception e)

Page 20 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

{
System.out.println(e.getMessage());
}
}
}

The above listing shows the ControllerHelper class used to process requests received by the ControllerServlet class. The ControllerHelper
class contains methods that perform the following operations:
n Invokes the newuser.jsp page when the ControllerServlet assigns a request parameter value, new.
n Obtains the name, address, email ID, and social security number of a new customer and assigns these values to a Java bean class called
CustomerVO. The CustomerVO class encapsulates attributes that map to columns in a customer table and enables the application to
insert a record in this table.

n Validates a login using a data accessor class called LoginDataAccessor.


n Redirects customers to the wrongpassword, nosuchuser, display, and displayall JSPs depending on request parameters passed from the
ControllerServlet class.

n Uses a service locator class to obtain the home object reference of the session bean. This method then invokes the create method to
create a session bean instance.

Creating the LoginDataAccessor Class


The LoginDataAccessor class contains code to insert a record in the CustomerInfo table, or validate a login using data in this table. Listing A-
18 shows the LoginDataAccessor class:

Listing A-18: The LoginDataAccessor.java File

package controller;
// Import necessary packages
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Vector;
public class LoginDataAccessor
{
private Connection con;
public LoginDataAccessor()
{
try
{
// Create an initial context for JDBC lookup, get reference to data source
// and get connection
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:/AppendixDS");
this.con = ds.getConnection();
}
catch(NamingException e)
{
System.out.println(e.getMessage());
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
// Method that inserts client data in a database
public int insert(Customer customer)
{
int rowsInserted = 0;
PreparedStatement ps = null;
try

Page 21 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

{
ps = con.prepareStatement("INSERT INTO CustomerInfo VALUES(?,?,?,?,?)");
ps.setString(1,customer.getEmailID());
ps.setString(2,customer.getPassword());
ps.setString(3,customer.getCustomerName());
ps.setString(4,customer.getAddress());
ps.setString(5,customer.getSocialSecurityNumber());
rowsInserted = ps.executeUpdate();
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
// Close prepared statement object
if(ps != null)
{
ps.close();
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
return rowsInserted;
}
public int validate(Customer customer)
{
// Method that validates a customer
/* This Method returns the following values
0 = username and password are correct
1 = username not found in table
2 = incorrect password. */
int result = 0;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
// Select email id and password from CustomerInfo table
ps = con.prepareStatement("SELECT emailID,password from CustomerInfo WHERE emailID=?");
ps.setString(1,customer.getEmailID());
rs = ps.executeQuery();
// If client email id found, there is one record in result set, then, if
// condition becomes true
if(rs.next())
{
// Get the password from the CustomerInfo table
String dbPassword = rs.getString("password");
// Check whether client's password is the same as that from
// database
if(dbPassword.equals(customer.getPassword()))
{
// If other email id and password is the same, display
System.out.println("UserName and password are correct ..");
}
else
{
// If password is wrong, set a value to a variable
result = 2;
}
}
else
{
// if given user is wrong, display message
// set a value to a result

Page 22 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

result = 1;
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
// close prepared statement
if(ps != null)
{
ps.close();
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
// return current value for the variable
return result;
}
// method that closes database connections
public void closeConnection()
{
try
{
if(this.con != null)
{
this.con.close();
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}

The above listing contains code to perform the following operations:


n Obtain an InitialContext object to perform a lookup and obtain a handle to a javax.sql.DataSource object.

n Connect to the database and inserts new records into the CustomerInfo table.
n Validate a login by retrieving information from the CustomerInfo table.

Creating a Service Locator


You create a service locator class, ResortBeansLocator, to locate the remote object using its Java Naming Directory Interface (JNDI) name.
This class contains a method called getHome() that returns the home object of the session bean. Using the home object, the service locator
creates the remote object of the session beam. The service locator class enables the presentation tier components to locate the session bean
object. Listing A-19 shows the service locator class:

Listing A-19: Service Locator Class

// service locator class that looks up session beans


package controller;
// import necessary packages
import java.util.*;
import javax.naming.*;
import java.rmi.RemoteException;
import javax.ejb.*;
import javax.rmi.PortableRemoteObject;
import java.io.*;
public class ResortBeansLocator
{

Page 23 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

private static ResortBeansLocator locator=null;


InitialContext context = null;
Hashtable ht = null;
// Create an instance of ResortBeansLocator
static
{
try
{
if(locator==null)
{
locator = new ResortBeansLocator();
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
private ResortBeansLocator() throws Exception
{
try
{
context = new InitialContext();
ht=new Hashtable();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
// return the instance of ResortBeansLocator class
public static ResortBeansLocator getInstance()
{
return locator;
}
public EJBHome getHome(String jndiName,Class homeName)
throws Exception
{
try
{
if (homeName == null)
{
throw new IllegalArgumentException("homeName is null");
}
// Check if we have already cached the home
if (ht.containsKey(homeName) == false)
{
loadHome(jndiName,homeName);
}
return (EJBHome) ht.get(homeName);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
// method that returns a reference to beans home object
public void loadHome(String jndiName, Class classobj)
throws ClassNotFoundException
{
try
{
Object objref = context.lookup(jndiName);
EJBHome home = (EJBHome) PortableRemoteObject.narrow(objref, classobj);
ht.put(classobj,home);
}
catch(Exception e)
{

Page 24 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

System.out.println(e.getMessage());
}
}
}

The above listing shows that the session bean object is located using the InitialContext object.

Creating the Middle Tier Components


The Resort Rental application contains middle tier components to communicate with database. In addition, middle tier contains value objects
to hold database data. The value objects are returned to the end user through a session bean to the presentation tier components. As a result,
the middle tier components act as an interface between the presentation tier components and the backend database.

Creating a Java Class to Access Database


You create a Java class, ResortDataAccessor class to communicate with the database. This class retrieves data from various tables and sets
the retrieved data to the corresponding value objects. In addition, the ResortDataAccessor class contains a method to receive data from the
presentation tier and book a resort based on the received data. A session bean invokes the methods of the ResortDataAccessor class.
Listing A-20 shows the ResortDataAccessor class:

Listing A-20: The ResortDataAccessor.java File

package controller;
// Import necessary packages
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Vector;
import java.io.Serializable;
public class ResortDataAccessor implements Serializable
{
private Connection con;
public ResortDataAccessor()
{
try
{
// Get a reference to initial context
InitialContext ctx = new InitialContext();
// Use context to look up a datasource
DataSource ds = (DataSource)ctx.lookup("java:/AppendixDS");
// Get connection to the data source
con = ds.getConnection();
}
catch(NamingException e)
{
System.out.println(e.getMessage());
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
public Vector displayResorts()
{
// Display all available resorts for rent
Vector result = null;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
// Select resort id and resort name for available resorts
ps = con.prepareStatement("SELECT resortID,resortName FROM Resorts");
rs = ps.executeQuery();

Page 25 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

if(rs == null)
{
// If resorts are not available
System.out.println("No resorts available for rent ... ");
}
else
{
// Create a Vector to hold Resorts ValueObject
result = new Vector();
while(rs.next())
{
// Create a Resorts ValueObject
// Set the resortID and resortName to the ValueObject
Resorts resorts = new Resorts();
String resortID = rs.getString("resortID");
String resortName = rs.getString("resortName");
resorts.setResortID(resortID);
resorts.setResortName(resortName);
// Add ValueObject to result Vector
result.add(resorts);
}
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
// Close result set and prepared statement objects
if(rs != null)
{
rs.close();
}
if(ps != null)
{
ps.close();
}
}
catch(SQLException e)
{
System.out.println(e.getMessage()); }
}
// Return the Vector containing Resorts ValueObject
return result;
}
// Create a method that displays data associated with a particular resort
public Vector displayResortData(String resortID)
{
// Declare necessary variables
PreparedStatement ps = null;
ResultSet rs = null;
// Create Packages and Rates ValueObject that store package and rates info about
// a particular resort
Packages packages = new Packages();
Rates rates = new Rates();
// Create a Vector object to store multiple ValueObjects
Vector vector = new Vector();
try
{
// Select the number of each available package
ps = con.prepareStatement("SELECT luxury, Presedential, pentHouse
from Packages WHERE resortID=?");
ps.setString(1,resortID);
rs = ps.executeQuery();
if(rs.next())
{

Page 26 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

// Put all the data in a Packages ValueObject


packages.setLuxury(rs.getInt("luxury"));
packages.setPresedential(rs.getInt("Presedential"));
packages.setPentHouse(rs.getInt("pentHouse"));
}
// Close result set and prepared statement objects
rs.close();
ps.close();
// Select the rate for each package from Rates table
ps = con.prepareStatement("SELECT luxury, Presedential, pentHouse
from Rates WHERE resortID=?");
ps.setString(1,resortID);
rs = ps.executeQuery();
if(rs.next())
{
// Put all the data in a Rates ValueObject
rates.setLuxury(rs.getInt("luxury"));
rates.setPresedential(rs.getInt("Presedential"));
rates.setPentHouse(rs.getInt("pentHouse"));
}
// Close result set and prepared statement objects
rs.close();
ps.close();
// Add resort id and multiple ValueObjects to a Vector and return
vector.add(0,resortID);
vector.add(1,packages);
vector.add(2,rates);
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
// Return vector object containing all the data for request resort
return vector;
}
// Method that books a resort and returns the cost to the client
public int bookResort(Bookings bookings)
{
// Variable to hold cost
int totalCost = 0;
// Retrieve all client booking data from Booking ValueObject
String emailID = bookings.getEmailID();
String resortID = bookings.getResortID();
String bookingPersonName = bookings.getBookingPersonName();
int luxuryNos = bookings.getLuxuryNos();
int PresedentialNos = bookings.getPresedentialNos();
int penthouseNos = bookings.getPenthouseNos();
int days = bookings.getDays();
int adults = bookings.getAdults();
int children = bookings.getChildren();
// Declaring variables
PreparedStatement ps = null;
ResultSet rs = null;
int update = 0;
try
{
int luxRate=0;
int presRate=0;
int pentRate=0;
// Retrieve rates for each package type from Rates table
ps=con.prepareStatement("select * from Rates where resortID=?");
ps.setString(1,resortID);
rs=ps.executeQuery();
if(rs.next())
{
luxRate=rs.getInt("luxury");
presRate=rs.getInt("Presedential");
pentRate=rs.getInt("pentHouse");
}

Page 27 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

rs.close();
ps.close();
// Insert the client booking data in a Bookings table
String fields = "(emailID, bookingPerson, luxuryRooms,
PresedentialRooms, pentHouseRooms, numberOfDays, adults,
children, cost, resortID)";
ps = con.prepareStatement("INSERT INTO Bookings "+
fields+" VALUES(?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,emailID);
ps.setString(2,bookingPersonName);
ps.setInt(3,luxuryNos);
ps.setInt(4,PresedentialNos);
ps.setInt(5,penthouseNos);
ps.setInt(6,days);
ps.setInt(7,adults);
ps.setInt(8,children);
// Calculate cost for the customer, store in cost variable
int head = adults+children;
int cost = ((luxuryNos*luxRate) + (PresedentialNos*presRate) + (penthouseNos*pentRate))*
ps.setInt(9,cost);
ps.setString(10,resortID);
update = ps.executeUpdate();
System.out.println("Room booked for the client. Thank you ... ");
ps.close();
// Update Packages table to reduce rooms
ps=con.prepareStatement("update Packages set luxury=(luxury-?),Presedential=(Presedentia
pentHouse=(pentHouse-?) where resortID=?");
ps.setInt(1,luxuryNos);
ps.setInt(2,PresedentialNos);
ps.setInt(3,penthouseNos);
ps.setString(4,resortID);
int j = ps.executeUpdate();
totalCost=cost;
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
// Close prepared statement object
if(ps != null)
{
ps.close();
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
// Return cost to the client
return totalCost;
}
public void closeConnection()
{
try
{
// Close connection
if(this.con != null)
{
con.close();
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());

Page 28 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

}
}
}

In the above listing, the DataSource class is used to lookup the database.

Creating the Session Bean


You create a session bean to enable the presentation tier components to retrieve information about the resorts from the database. The
session bean contains business methods to return data to the presentation tier components. To develop a session bean, you need to code a
home and remote interface and a bean implementation class.
Creating the Home Interface

You create the home interface of the session bean to specify the create() method used to instantiate the bean. The home interface is created
by extending the EJBHome interface. Listing A-21 shows the home interface of the session bean:

Listing A-21: The ResortSessionHome.java File

package controller;
// import necessary packages
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface ResortSessionHome extends EJBHome
{
// create method that returns a reference to remote object
public ResortSession create() throws RemoteException,CreateException;
}

Creating the Remote Interface

You create the remote interface to expose the business methods of the session bean. These business methods are implemented in the bean
implementation class. You create the remote interface by extending the EJBObject. Listing A-22 shows the remote interface of the session
bean:

Listing A-22: The ResortSession.java File

package controller;
// import necessary packages
import javax.ejb.EJBObject;
import javax.ejb.EJBException;
import java.rmi.RemoteException;
import java.util.*;
public interface ResortSession extends EJBObject
{
// declaring business methods
public Vector displayResorts() throws RemoteException;
public Vector displayResortData(String resortID) throws RemoteException;
public int bookResort(Bookings bookings) throws RemoteException;
}

Creating the Bean Implementation Class

You create the session bean implementation class to provide implementation for the business methods exposed by the remote interface. The
business methods of the session bean use the methods of the ResortDataAccessor class to obtain data from the database. These methods
return the database data in the form of value objects. Listing A-23 shows the implementation class of the session bean:

Listing A-23: The ResortSessionBean.java File

package controller;
// Import necessary packages
import java.rmi.RemoteException;
import javax.ejb.*;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

Page 29 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

import java.util.*;
public class ResortSessionBean implements SessionBean
{
// Declaring variables
private SessionContext context = null;
private ResortDataAccessor dao = null;
// default constructor
public ResortSessionBean()
{
}
// Implementation method that displays all the available resorts
public Vector displayResorts()
{
// Returns HashMap with String objects resortId and resortName
// as key - value mapping.
Vector result = null;
try
{
// Create data accessor object
dao = new ResortDataAccessor();
// Get all the available resorts as a Vector
result = dao.displayResorts();
// Close connection
dao.closeConnection();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return result;
}
// Implementation method that displays all the data associated with a particular resort
public Vector displayResortData(String resortID)
{
// Returns Vector object containing
/*
0 = resortId as String object
1 = Packages object containing
int rooms available
2 = Rates object containing
rate/room/person
*/
Vector result=null;
try
{
// Create data accessor object
dao = new ResortDataAccessor();
// Invoke method on data accessor to get all the data associated with
// individual resort
result = dao.displayResortData(resortID);
// Close connection
dao.closeConnection();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return result;
}
// Method to book a resort
public int bookResort(Bookings bookings)
{
int result=0;
try
{
// Create a data accessor value object
dao = new ResortDataAccessor();
// Invoke method on data accessor value object to insert booking data
result = dao.bookResort(bookings);

Page 30 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

// Close connection
dao.closeConnection();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return result;
}
// EJB callback methods
public void ejbCreate() throws CreateException
{
}
public void ejbRemove()
{
}
public void ejbActivate()
{
}
public void ejbPassivate()
{
}
public void setSessionContext(SessionContext sc)
{
this.context=sc;
}
}

Running the Resort Rental Application


An ABCResort database is created in MySQL for the Resort Rental application. The java programs in this application use the jndi name
MySqlDS to access this database.

Creating Tables
The login information of the end user is stored in the CustomerInfo database. This table is used in the Presentation tier of the application.
Table A-1 lists the structure of the CustomerInfo table:
Table A-1: Structure of the
CustomerInfo Table

Fieldname Datatype

EmailID varchar(40)
Password varchar(20)
CustomerName varchar(40)

Address varchar(100)
SocialSecurityNumber varchar(15)

The information about the location of various resorts is stored in the Resorts table. This table is used by the session been in the middle tier.
Table A-2 lists the structure of the Resorts table:
Table A-2: Structure of the
Resorts Table

Fieldname Datatype

ResortID varchar(4)
resortName varchar(30)

ResortLocation varchar(40)

The information about the rooms available in various resorts is stored in the Packages table. Table A-3 lists the structure of the Packages
table:
Table A-3: Structure of
the Packages Table

Fieldname Datatype

Page 31 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

ResortID varchar(4)

Luxury int(4)
Presidential int(4)
PentHouse int(4)

The information about the rates to be charged for the various rooms available is stored in the Rates table. Table A-4 lists the structure of the
Rates table:
Table A-4: Structure of
the Rates Table

Fieldname Datatype
ResortID varchar(4)

Luxury int(4)
Presidential int(4)
PentHouse int(4)

The information about the bookings made by the end user for a resort, is stored in the Bookings table. Table A-5 lists the structure of the
Bookings table:
Table A-5: Structure of the Bookings Table

Fieldname Datatype
bookID int() PRIMARY KEY AUTO_INCREMENT
resorted varchar(4)

emailed varchar(40)
bookingPerson varchar(40)

luxuryRooms int(4)
presidentialRooms int(4)
pentHouseRooms int(4)

numberOfDays int(4)
Adults int(4)

Children int(4)
Cost int(4)

Creating the Deployment Descriptors


The deployment descriptor for the presentation tier components is described in the web.xml file. Listing A-24 shows the web.xml file:

Listing A-24: The web.xml File

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>controller.ControllerServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>newuser</servlet-name>
<jsp-file>/newuser.jsp</jsp-file>
</servlet>
<servlet>
<servlet-name>index</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet>
<servlet-name>login</servlet-name>
<jsp-file>/login.jsp</jsp-file>

Page 32 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

</servlet>
<servlet>
<servlet-name>displayresorts</servlet-name>
<jsp-file>/displayresorts.jsp</jsp-file>
</servlet>
<servlet>
<servlet-name>display</servlet-name>
<jsp-file>/display.jsp</jsp-file>
</servlet>
<servlet>
<servlet-name>displayresortdata</servlet-name>
<jsp-file>/displayresortdata.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/Controller</url-pattern>
</servlet-mapping>
</web-app>

The deployment descriptor for the middle tier components is described in the ejb-jar.xml file. Listing A-25 shows the ejb-jar.xml file:

Listing A-25: The ejb-jar.xml File

<?xml version="1.0"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"
"http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<display-name>ResortJAR</display-name>
<enterprise-beans>
<session>
<ejb-name>ResortBean</ejb-name>
<home>controller.ResortSessionHome</home>
<remote>controller.ResortSession</remote>
<ejb-class>controller.ResortSessionBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>

The presentation tier components must be deployed as a war file and the middle tier components must be deployed as a jar file. The jar file
and the war file are packaged together as an ear file for ease of deployment. The deployment descriptor for the ear file is described in
application.xml file. Listing A-26 shows the application.xml file:

Listing A-26: The application.xml File

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE application
PUBLIC '-//Sun Microsystems, Inc.//DTD J2EE Application 1.2//EN'
'http://java.sun.com/j2ee/dtds/application_1_2.dtd'>
<application>
<display-name>Rent Resort</display-name>
<description>Rent Resort</description>
<module>
<ejb>RentResort.jar</ejb>
</module>
<module>
<web>
<web-uri>RentResort.war</web-uri>
</web>
</module>
</application>

Deploying the Resort Rental Application


Create the build.xml file used by the ANT tool and place it in any user-defined directory. Create a folder called source under any working

Page 33 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

directory and place all Java files under a folder javaFiles in the source directory. XML and JSP pages need to be placed in the source
directory. Start the JBoss server before running the ANT tool. Listing A-27 shows the build.xml file used by this application:

Listing A-27: The build.xml File

<project name="RentResort App" default="build-all" basedir=".">


<property name="application" value="RentResort"/>
<property name="jboss.dir" value="/usr/java/jboss-3.2.1"/>
<property name="jboss.deploy.dir" value="${jboss.dir}/server/default/deploy"/>
<property name="source.dir" value="${basedir}/javaFiles"/>
<property name="build.dir" value="${basedir}/build"/>
<property name="build.classes.dir" value="${build.dir}/classes"/>
<property name="warfile" value="${application}.war"/>
<property name="jarfile" value="${application}.jar"/>
<property name="earfile" value="${application}.ear"/>
<!-- the build path that contains the classpath required to compile the source files -->
<path id="classpath">
<pathelement location="${build.classes.dir}"/>
<pathelement location="${jboss.dir}/server/default/lib/javax.servlet.jar"/>
<pathelement location="${jboss.dir}/client/jboss-j2ee.jar"/>
</path>
<!-- compile source files -->
<target name="compile">
<echo message="Compiling source files ...." />
<mkdir dir="${build.classes.dir}"/>
<javac srcdir="${source.dir}"
destdir="${build.classes.dir}"
deprecation="on"
classpathref="classpath"
includes="*"
/>
</target>
<!-- war, jar, ear files -->
<target name="war" depends="compile">
<echo message="Creating war file ...." />
<war warfile="${warfile}" webxml="web.xml">
<fileset dir="${basedir}">
<include name="index.jsp"/>
</fileset>
<webinf dir="${basedir}">
<include name="jboss-web.xml"/>
<include name="*.jsp"/>
</webinf>
<classes dir="${build.classes.dir}">
</classes>
</war>
</target>
<target name="jar" depends="war">
<echo message="Creating jar file ...." />
<jar jarfile="${jarfile}" basedir="${build.classes.dir}">
<metainf dir="${basedir}" includes="ejb-jar.xml"/>
</jar>
</target>
<target name="ear" depends="jar">
<echo message="Creating ear file ...." />
<ear earfile="${earfile}" appxml="application.xml">
<fileset dir="${basedir}" includes="${jarfile}, ${warfile}"/>
</ear>
</target>
<!-- copy ear file to the deploy directory under jboss installation-->
<target name="build-all" depends="ear">
<echo message="Copying ear file to the deploy directory...." />
<copy file="${earfile}" todir="${jboss.deploy.dir}"/>
</target>
</project>

To perform the ANT build, you need to change to the working directory where you have saved the build.xml file. Run the ANT tool from the
command line. Figure A-1 shows the output of the ANT tool:

Page 34 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

Figure A-1: The Output of the ANT Tool

Running the Application


To run the Resort Rental application:
1. Open a browser and specify the URL, http://localhost:8080/RentResort. The Home page appears, as shown in Figure A-2:

Figure A-2: The Home Page

2. Click Sign Up to register to the Web site. The new user login page appears.
3. Specify the required information for user registration, as shown in Figure A-3:

Page 35 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

Figure A-3: The New User Login Page

4. Click Submit. The information is sent to the servlet for processing and the result of the database operations is displayed to the end user,
as shown in Figure A-4:

Figure A-4: The Message Page

5. Click Home to return to the home page of the application.


6. Click the Login hyperlink and enter the username and password to log on to the Web site. Figure A-5 shows the output of the login.jsp
file:

Page 36 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

Figure A-5: The Login Page

7. Click Login. The end user is authenticated and a hyperlink to view all resort location appears, as shown in Figure A-6:

Figure A-6: The Resorts Page

8. Click Display Resorts hyperlink to view all resorts. Figure A-7 shows the output of the displayresorts.jsp file:

Page 37 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

Figure A-7: The Resorts – All Page

9. Click East Resort hyperlink to view information about East Resort resort, as shown in Figure A-8:

Figure A-8: The Resort Information Page

10. Specify the information required to book a resort, as shown in Figure A-9:

Page 38 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited
Working with JBOSS Application Server

Figure A-9: The Filled Out Resort Page

11. Click BOOK RESORT. The information is sent to the servlet and the total cost is calculated and returned to the end user, as shown in
Figure A-10:

Figure A-10: The Booking Confirmation Page

Page 39 / 39
Reprinted for OET7P/751897, Accenture SkillSoft, SkillSoft Corporation (c) 2003, Copying Prohibited

You might also like