md254_Tut3_JSPJDBCTasks.doc.doc.doc.doc

cuttlefishblueData Management

Dec 16, 2012 (5 years and 20 days ago)

419 views


1

MD
254
: e
-
Service Operations

Management


Tutorial #
3

Using
Java Server Pages

(JSPs) to Build a

Database
-
Backed e
-
Service



The previous tutorial (Tutorial #
2 on JSPs and JDBC
) provided you with some background on
Java Server Pages, and showed you how to mak
e a connection in JDBC to a database

on
WebAppCabaret
.
This

JSP

tutorial covers several new topics:



First, we’ll look at how to pass information from
one
JSP page to
another
JSP page in an
e
-
Service.



Second, we’ll see how to upload a JSP file

(or other f
ile)

to the WebAppCabaret site.



Next, we’ll look at how to manage our database tables on the WebAppCabaret site, in
order to store information sent by the user of an e
-
Service.



Finally, we’ll build several pages for a JSP application of a simple store.


F
or
these tutorials
, we’ll be using the WebAppCabaret.com account for building and testing our
JSP pages
. Remember that your necessary information in order to log into WebAppCabaret
(http://www.webappcabaret.com/) is as follows:



Our account (the “Context”)
is:
gregheim



The username and password for the WebAppCaberet account were given out in class.
Email me if you didn’t get them.



The database name and database password for the database that you’ll be working with
are
gregheim_2

and
eagles
.

You’ll need these

for the exercises at the end of this tutorial.

If for some reason these don’t seem to work, notify me and tell me and I’ll try to figure it out.


While we won’t be directly using the iSavvix
.com

site from this point on, y
ou may still find the
iSavvix.com
site
to be
helpful, especially in cases where you may need to find something out
about the Java language. While working with the two sites, I have found the iSavvix.com
JavaDoc

section (“JavaDocs Bookmarks” on the left menu of the page)
to be helpful to le
arn
how to use various Java classes.
Thus, if you want to learn something about one of the Java
commands, I would suggest going to iSavvix.com and finding it in the JavaDoc section within
the Community site on iSavvix.


JSP vs. Servlets


Java Server Pages
(JSP) technology is an extension of another type of Java technology called
Servlets.
1

JSPs are basically extensions of servlet technology created to support authoring of
HTML and XML pages, in order to make it easier to combine fixed or static template dat
a with
dynamic content. Java Servlet technology provides Web developers with a simple, consistent
mechanism for extending the functionality of a Web server and for accessing existing business



1

This section was adapted from Sun’s web site on servlet technology
http://java.sun.com/products/servlet/
. For more
information on servlets, visit that site.


2

systems. A servlet can almost be thought of as an applet that ru
ns on the server side


without a
graphical user interface (GUI).


Servlets are the Java platform technology of choice for extending and enhancing Web servers.
Servlets provide a component
-
based, platform
-
independent method for building Web
-
based
applicat
ions, without the performance limitations of CGI programs. And unlike proprietary
server extension mechanisms (such as the Netscape Server API or the Apache web server
modules), servlets are server
-

and platform
-
independent. This leaves you free to select
a "best of
breed" strategy for your servers, platforms, and tools


allowing you to have a more flexible e
-
service infrastructure.


Servlets have access to the entire family of Java APIs, including the JDBC
application
programming interface (
API
)

through w
hich one can

access enterprise databases. Servlets can
also access a library of HTTP
-
specific calls and receive all the benefits of the mature Java
language, including portability, performance, reusability, and crash protection.


Today, servlets are a popu
lar choice for building interactive Web applications. Third
-
party
servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet
containers are usually a component of Web and application servers, such as BEA WebLogic
Application

Server, IBM WebSphere, Sun ONE Web Server, Sun ONE Application Server, and
others.


Allowing Users to Make Requests in a JSP


In order to build a useful application with JSPs, you must be able to process user requests, and to
respond with a page that has
some information that was requested.
In its simplest form, this
usually means that we need to build form fields into a web page, be able to send the data that the
customer inputs into such a form across the Internet, be able to process the data, and then
r
espond to the service request with some sort of HTML based web page.


Java Server Pages have a couple of built
-
in means for sending and processing such requests.
User requests are represented in JSPs by interfaces called
ServletRequest

and
HttpServletReque
st
. (An interface is a special type of Java class. A class is just a template


built from Java code


used to create an object.).


ServletRequest

and
HttpServletRequest

are different but related to each other.
HttpServletRequest

is a child of the
Servlet
Request

interface, and thus inherits the
properties
ServletRequest

interface.
ServletRequest

is a generic interface that models
user requests that do not depend on an underlying protocol used to communicate the request.
Because it is a child,
HttpServletRe
quest

extends
ServletRequest

and is an interface
specific to the HTTP protocol, so it provides additional services that are specific to handling
HTTP requests.
2





2

If yo
u don’t understand what this paragraph means, don’t worry, I won’t test you on it. The main point that you
need to understand is that we will need to use
HttpServletRequest

to catch data that we send across the
internet.

We use it via the
request

and
respo
nse

objects, which you’ll read about on the next page.


3


Table 1: Functionality Provided by
ServletRequest
,
HttpServletRequest
, and the
request

Object

Interface

Functionality

ServletRequest

Provides access to attributes and parameters


Obtains information about remote and local
machines and protocols being used


Obtains information about content of a request

HttpServletRequest

Provides access to HTT
P headers


Provides access to user session information
about cookies, URL encoding


Allows parsing the invoking URL


Allows managing user security


Pr
ogrammers cannot use either
ServletRequest

or
HttpServletRequest

directly.
Instead,
they
have to use a
n implicit Java object named
request
. The JSP
request

object
implements the
HttpServletRequest

interface. Your JSP will use the
request

object to
obtain information sent back and forth between the user’s browser and your web server during a
user session.


The information that you will be interested in processing is contained within the HTTP request
sent to the server by the browser or other device, as well as in the URL that is sent within the
HTTP request.


A URL has the following general structure:

proto
col://host:port/virtualPath?queryString

The information carried by each of the components of the URL is described in Table 2.


Table 2: Components of a URL

URL Component

Description

protocol

Declares mechanisms for transferring information between remote
machines. Protocols include: http, https, ftp, rmi, and corba.

host

Remote machine name (e.g., www.mysite.com) or IP address (e.g.,
127.0.0.1).

port

Machine port number on which the host server will be listening for
requests (e.g., 80, 443, 8080, etc.).

virtualPath

The physical directory path where a JSP file is located.

queryString

A list of name/value pairs passed to the JSP as an argument.


In addition to the components in Table 2, a URL may contain extra information that is not part of
the physical

directory of the JSP file, but can provide information for the JSP to configure its
behavior. For example, a Servlet name may be placed in the URL.


4


An example of a URL that contains each of the components in Table 2 follows:

http://www.mysite.com:8001/d
irectory1/subdirectory2/myjsp.jsp?variable1=value1&variable2=value2

In this URL the components are as follows:




protocol = http



host = “www.mysite.com”



port=8001



virtualPath = “directory1/directory2”



queryString = “variable1=value1&variable2=value2”


Th
e implicit
request

object inside of a JSP page basically catches various variables that are
sent by a form field in a page to the page that will process the variables’ values and respond back
to the browser. The
request

object has several Java methods thro
ugh which it can catch and
process such information. The methods of the request object that you can use to get information
about the URL and the client and server machines being used are presented in Table 3.


Table 3: Methods Provided by the
request

Obje
ct

Method

Description

Path and URL Methods


String getPathInfo()

Returns portion of URL after a Servlet name and before the query
string.

String getPathTranslated()

Returns the physical path location of the JSP.

String getContextPath()

Returns portion

of the URL that indicates the context of the
request.

String getQueryString()

Returns portion of the URL following the question mark (?).

String getRequestURI()

Returns portion of the URL from the protocol name up to the
query string. Behavior depends u
pon whether the request is a
GET or a POST.

Machine Host and Port
Methods


String getRemoteAddr()

Returns IP address of client machine that generated the request

String getRemoteHost()

Returns name of the client machine

String getServerName()

Returns t
he name of the local server that received the request

int getServerPort()

Returns port number of local server

String getScheme()

Returns the name of the scheme used to create the request (i.e.,
HTTP, HTTPS, FTP)

String getProtocol()

Returns the name and

version of the protocol used to generate the
request

String getMethod()

Returns name of HTTP method used in request (i.e., GET, POST,
PUT)

String
getCharacterEncoding()

Returns the character encoding of the body of the request

boolean isSecure()

Return
s whether the request was made through a secure channel
(e.g., HTTPS)

int getContentLength()

Returns the length of the body

String getContentType()

Returns the MIME type of the body



5

How can the pieces of information from a user request be retrieved? Li
sting 1 provides a piece of
JSP code that retrieves all of the information from a JSP request
, using the
request

object
(which is show in
bold
)
. If you cut
-
and
-
paste Listing 1 into a JSP file (information.jsp), or
download it from my directory (heim), and
then upload this file to your WebAppCabaret
directory, you can run it and see its output.


Listing 1: Retri
eving User Request Information [tutorial3listing1
.jsp
]

<HTML>

<HEAD><TITLE>request Object Methods</TITLE>

<BODY>

Click

<A HREF="
tutorial3listing1
.jsp
"> here </A>

to send a request to the JSP <BR>


<BR><U>Path and URL Information</U><BR>


getPathInfo() = <%=
request
.getPathInfo() %><BR>


getPathTranslated() = <%=
request
.getPathTranslated() %><BR>


getContextPath() = <%=
request
.getContextPath() %><
BR>


getQueryString() = <%=
request
.getQueryString() %><BR>


getRequestURI() = <%=
request
.getRequestURI() %><BR>


getServletPath() = <%=
request
.getServletPath() %><BR>


<BR><U>Machine Host and Port Information</U><BR>


getRemoteAddr() = <%=
request
.
getRemoteAddr() %><BR>


getRemoteHost() = <%=
request
.getRemoteHost() %><BR>


getScheme() = <%=
request
.getScheme() %><BR>


getProtocol() = <%=
request
.getProtocol() %><BR>


getMethod() = <%=
request
.getMethod() %><BR>


getCharacterEncoding() = <%=
re
quest
.getCharacterEncoding() %><BR>


isSecure() = <%=
request
.isSecure() %><BR>


getContentLength() = <%=
request
.getContentLength() %><BR>


getContentType() = <%=
request
.getContentType() %><BR>


getServerName() = <%=
request
.getServerName() %><BR>


getServerPort() = <%=
request
.getServerPort() %><BR>

</BODY>

</HTML>


When I run this JSP

from Listing 1

on my home computer under the Jakarta Tomcat Server
3
, I
get the output in Listing 2 inside of my Netscape browser.

You can try this JSP out by testing

the
JSP stored in the Tutorial directory on our WebAppCabaret site.


Listing 2: Retrieving User Request Information

Click

here
to send a request to the JSP


Path and
URL Information

getPathInfo() = null

getPathTranslated() = null

getContextPath() = /examples

getQueryString() = null

getRequestURI() = /examples/jsp/myjsps/requestObjectInformation.jsp

getServletPath() = /jsp/myjsps/requestObjectInformation.jsp


Machine Ho
st and Port Information

getRemoteAddr() = 127.0.0.1




3

If you
are interested in setting up Apache’s

Jakarta
Tomcat Server on your own computer, I can show you how or
direct you to the required resources on the WWW.

Or, you can download it from
http://jakarta.apache.org/

and
install it on your computer by following the directions. It really isn’t too difficult to do.


6

getRemoteHost() = 127.0.0.1

getScheme() = http

getProtocol() = HTTP/1.1

getMethod() = GET

getCharacterEncoding() = null

isSecure() = false

getContentLength() =
-
1

getContentType() = null

getServerName() =

localhost

getServerPort() = 8080


Up until this point, the
request

object methods that you’ve seen (in Listings 1 and 2) have
been used for collecting the behind
-
the
-
scenes information


for example, Listing 2 presents
information about the server enviro
nment

(path, URL, server machine, client machine)
.


The other variables of use to us will be those we can send from a browser via HTML <FORM>
fields. The information that is passed from a form must be caught and processed by the JSP
request

object. The JS
P

request

object

catches and processes form information using the
methods in Table 4.

[Note: We first saw the request object in Listing 10 of Tutorial #
2
, and used
it to process our phone book numbers that we added.]


Table 4: Query String Methods Provided

by the
request

Object

Method

Description

String getParameter(String
paramName)

Returns the value of the parameter named
paramName
.

String getParameterNames()

Returns all of the parameter names as an enumeration
of String objects. You can then work your

way through
the enumeration and remove each string one
-
by
-
one.

String[] getParameterValues(String
paramName)

Returns all of the values of a multi
-
valued paramater
named
paramName
.



7


Listing 3 presents an example of how the above
request

methods are use
d. Listing 3 contains
a form into which a customer would type in credit card information for a purchase. The form
includes several different types of fields, including a TEXT field, and a pull
-
down menu using
the SELECT tag.


Listing 3
: Credit Card Inform
ation Form [creditCardForm.html]

<HTML>

<HEAD><TITLE>Credit Card Information Form</TITLE></HEAD>

<BODY>

<FORM
ACTION="creditCardProcess.jsp" METHOD="POST"
>

Credit Card Information

<P> Name: <INPUT TYPE="TEXT" NAME="
name
" SIZE="25">

<P> Credit Card Number:
<INPUT TYPE="TEXT" NAME="
number
" SIZE="25">

<P> Credit Card Type:


<SELECT NAME="
type
">


<OPTION>Visa</OPTION>


<OPTION>Master Card</OPTION>


<OPTION SELECTED>Amex</OPTION>


</SELECT>

<P> Expiration Date:


<SELECT NAME="
month
">



<OPTION SELECTED>01</OPTION> <OPTION>02</OPTION>


<OPTION>03</OPTION> <OPTION>04</OPTION>


<OPTION>05</OPTION> <OPTION>06</OPTION>


<OPTION>07</OPTION> <OPTION>08</OPTION>


<OPTION>09</OPTION> <OPTION>10</OPTION>


<OPTION>11</OP
TION> <OPTION>12</OPTION>


</SELECT>


<SELECT NAME="
year
">


<OPTION>2000</OPTION> <OPTION SELECTED>2001</OPTION>


<OPTION>2002</OPTION> <OPTION>2003</OPTION>


<OPTION>2004</OPTION> <OPTION>2005</OPTION>


</SELECT>

<P>


<INPUT TYP
E="RESET" NAME="Reset" VALUE="Reset">


<INPUT TYPE="SUBMIT" NAME="Submit" VALUE="Submit"></TD>

</FORM>

</BODY>

</HTML>


When the “Submit” button in the above web page (creditCardForm.html) is clicked, the variables
name
,
number
,
type
,
month
, and
year

(
shown in bold)
are sent via the POST method to the
FORM ACTION activity, which is the JSP page creditCardProcess.jsp, presented in Listing 4.
This JSP page (creditCardProcess.jsp) basically just retrieves the information about the credit
card from the use
r request, and presents it as a simple list.


Of course, if we were building a real e
-
Commerce site, we would want a much nicer presentation
than this JSP provides, and we would also want to protect the information being passed through
some security measu
res, but for demonstration purposes it will suffice.



8


Listing

4: Credit Card Processing JSP [creditCardProcess.jsp]

<HTML>

<HEAD> <TITLE>Credit Card Processing JSP</TITLE>

</HEAD>

<BODY>


Verify Credit Card Information:

<UL>


<LI>Name = <%= request.
getParameter("name") %>


<LI>Number = <%= request.getParameter("number") %>


<LI>Type = <%= request.getParameter("type") %>


<LI>Date = <%= request.getParameter("month") %>/


<%= request.getParameter("year")%>

</UL>

</BODY>

</HTML>



Uploading a File to WebAppCabaret


To upload an HTML or JSP or other file to your directory on WebAppCabaret, you should
perform the following steps:

1.

Log in to your WebAppCabaret account

2.

Click on the
FileMgr

icon … on the page that shows up, you will see a

folder tree

3.

Click on the folder
gregheim

… if you scroll down, you’ll see a folder with your name
on it

4.

Click on the folder
md254
, and then on the folder
with your
last
name on it (in my case,
heim
) … if there is anything in there, you’ll see some file na
mes of files contained within
your directory, if not, you’ll just see your directory highlighted in a gray box.

5.

Once your folder is highlighted in a gray box, you can upload a file into your folder.
Click on the
Upload

button

(See Figure 1).

6.

Click on the
B
rowse

button, and navigate through your computer to the directory that
contains the JSP file you want to upload. Select a file, and click
Open
.

7.

Click on the
Put in Present Folder

button. Your JSP file will be uploaded, and the page
will refresh. You should

see the name of your file within your personal directory.
Sometimes the directory will collapse when a file is uploaded, so you may have to click
on your directory once more to again see its contents.


Note: Downloading a file is pretty similar to the abo
ve, except you need to click the
Download

button and choose a directory on your local computer to save the file to.


Figure 1: FileMgr Buttons

The request object is
used to retrieve the value
associated with each
variable name




9


Setting up a Database Table on WebAppCabaret.com

using TEATIMEJ

In order to build a site that does something i
nteresting (i.e., a database
-
backed site), you’ll need
to create a databa
se table to store your data in. WebAppCabaret allows one to use either the
MySQL database management system or the PostgreSQL database management system. For all
of our examples, we’l
l be using the MySQL DBMS.


Everyone in MD254 will be

sharing a
MySQL
database on the
gregheim
_2

account,
thus
we’ll
need to follow some rules to make sure that each of us can reach the database, and that none of
us destroys another person’s work. So, plea
se follow the following rules


1.

The name of the database for use by MD254 students is
gregheim_2
.

2.

Do not change the database password in the administrative control panel screen that
allows one to do so. If you do accidentally change it, please change it bac
k immediately
to
eagles
.

3.

Please preface the name of each of your tables with your initials. For example, my

initials
are “G.H.”, so my

table name for a list of products should be “ghproducts” instead of
“products”.


Many of you at this point may be sayin
g … “But, I don’t know anything about MySQL! How
can I use it if I don’t know SQL or MySQL?” Lucky for you,
WebAppCabaret has
a simple

web
-
based application for interacting with the MySQL database that is

available to our account. The

application
is

called

TeaTimeJ
.


TeaTimeJ Web SQL Editor (
http://gollum.webappcabaret.net/teatimej/index.jsp
)

TeaTimeJ is
a

web
-
based application for logging into our database and working with the MySQL
database

management system
. This application is quite eas
y

to use, and inv
olves several screens,
which I’ll explain in order.


To use TeaTimeJ, you will first need to log into the
gregheim_2

database. For this, you need to
log in using the username and password for the MySQL database, which are “
gregheim_2
” and

eagles
”, respect
ively. Figure 2 shows what the TeaTimeJ login screen looks like.

(Note: The
pictures that follow are from last year, and show a different password and database name.
Please substitute your

MD254

database name

and password

for those in the picture.)


Figure

2: Login Screen for TeaTimeJ



10


Once you successfully log in, you will see the web page shown in Figure 3, through which you
can send SQL queries to interact with the database. Note that, as it says on the web page in
Figure 3, you should terminate your S
QL queries with a semi
-
colon (although it seemed to work
even without one).


Figure 3: SQL Query Input Window



If you need to create a new table, instead of using a SQL command to create the table, you could
click on the page icon that has a star in its
bottom right corner (next to the home icon in the top
right of each page). Figure 4 shows the menu that opens in order to create a new table.


To create a new table, all you need to do is type a name in the “Table” field, then click on the
Add Columns

ico
n to add fields to your MySQL table. For each column you add to the table,
you’ll need to define the data type of the column, the size, whether it is a key field, and so forth.
Once you’ve made some changes to your new table, you’ll want to click the
Refre
sh Table

icon
to update the structure of your table.


11

Figure 4: Creating a New MySQL Database Table



After creating a new table, you will want to be able to obtain information about the table and to
look at its contents. Figure 5 shows how you can find ou
t which columns are in a table. This
screen is arrived at by clicking on the information icon made up of an “i” inside a circle (in
Figure 3). Figure 5 shows which columns have been defined inside the “phonebook” table, what
their data types are, whether t
hey are key fields, and so forth.


Figure 5: Obtaining Information About a Table



If you need to edit the definitions of the columns within a table, you can click on the icon that
consists of a page with a pencil. Figure 6 shows this screen. As Figure 6
shows, you can add
columns, delete columns, change the name of a column, change the data type of a column, and so
forth.



12

Figure 6: Editing Column Definitions



Finally, after you create a table and store data in it, you might want to look at which data a
re in
your table. You can see this by clicking on the magnifying glass icon (in Figure 3), which will
open up the page in Figure 7. As Figure 7 shows, this page will allow you to see what the
columns are in a table, and what the data are in each column. Es
sentially, clicking on the
magnifying glass icon provides a similar result to using the SQL command (SELECT * FROM
tablename), which would return all of the data in a table to you.


Figure 7: Viewing Data Stored in a Table






13

Task #1: Building a Main Pa
ge


Next, we’ll start building a

simple
application

(a store
front
) that will show you some basics of
assembling together a web page from templates in JSP
. The application I’ll be describing for
class will be a small shopping cart application. If you want,

you can enhance it with additional
pages (or, you could use the example to totally build something else), but what follows will be
sufficient for what we need for class, and for you to learn some useful parts of JSPs.


The first task will be to create a f
ront page for the store. We will assume that everyone will enter
the store through the front page. This front page will not do much other than create an entry point
for the shopping cart, and create a session for the customer to manage the activities that
the
customer performs.


The first thing we’ll do is learn how to build a single page from a set of template files using JSP
include

commands (
<jsp include …>
). The template files allow a designer to modularize
a web page, so that we can easily change one s
mall section of a site without changing other
sections. Listing
5

presents the JSP for a simple home page that builds itself from several
template files that contain HTML. The template files are a header file for the top of the page
(
header.html
), a

naviga
tion bar (
nav.html
), a content frame for the site content (
content.html
),
and a footer file for inserting all of the site information about copyrights and so forth
(
footer.html
). Of course, I’ve just filled them in with the minimal basics that
a site might

have
.


Listing
5
: A Multiple
-
Pane Customizable Page (storeEntryPage.jsp)

<HTML>

<HEAD>

<TITLE>My S
tore</TITLE>

</HEAD>


<% //**********************************************


// Section that processes requests from customer


//***********************
***********************

%>

<%


String change = request.getParameter("change");


String bgColorState = request.getParameter("bgColor");


String navState = request.getParameter("nav");


String footerState = request.getParameter("foot
er");


if(change!=null){


if(change.equals("footer")){


if(footerState.equals("on")) footerState = "off";


else footerState = "on";


}


if(change.equals("nav"))


if(navState.e
quals("left")) navState = "right";


else navState = "left";


if(change.startsWith("color"))


bgColorState = change.substring(5);


} else {


bgColorState="yellow";


navState="left";



footerState="on";


}


String state = "&footer="+footerState+"&nav="+navState+


"&bgColor="+bgColorState;

%>


<% //*****************************************************


// Now, build the page based on the customer's requests


//*****************************************************


14

%>


<BODY BGCOLOR=<%=bgColorState%>>


<% //**************************************


// First, read in Header for top of page


//**************************************

%>

<jsp:include page
="header.html" flush="true"/>



<% //****************************************************


// Second, add in navigation panel and content section


//****************************************************

%>

<TABLE WIDTH=100% CELLSPACING=0 CELLPADDIN
G=0>

<% String leftPercent, rightPercent;


if(navState.equals("left")){


leftPercent="15%"; rightPercent="85%";


} else {


leftPercent="85%"; rightPercent="15%";


}

%>


<TR>


<TD WIDTH=<%=leftPercent%> VALIGN="TOP" HALIG
N="LEFT" BGCOLOR="AAAAFF">


<% if(navState.equals("left")){ %>


<jsp:include page="nav.html" flush="true"/>


<% } else { %>


<jsp:include page="content.html" flush="true"/>


<%

} %>


</TD>



<TD WIDTH=<%=rightPercent%> VALIGN="TOP" HALIGN="LEFT" BGCOLOR="FFAAAA">


<% if(navState.equals("left")){ %>


<jsp:include page="content.html" flush="true"/>


<% }

else { %>


<jsp:include page="nav.html" flush="true"/>


<% } %>


</TD>


</TR>

</TABLE>



<% //**********************************


// Third, read in the Footer page


//**********************************

%>

<%


if(footerState.equals("on")) { %>


<jsp:include page="footer.html" flush="true"/></TD>

<% } %>



<% //*********************************************************


// Finally, add section to

allow customer to customize page


//*********************************************************

%>

<HR>

<B>Customize MD850store Using The Buttons Below</B><BR>

<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=1>


<TR>


<TD><A HREF="storeEntryPage.jsp?change
=footer<%=state%>">


<IMAGE SRC="images/footerToggle.gif"></A><BR></TD>


<TD><A HREF="storeEntryPage.jsp?change=nav<%=state%>">


<IMAGE SRC="images/navToggle.gif"></A><BR></TD>


<TD><A HREF="storeEntryPage.jsp?change=colorblue<%=state%>
">


<IMAGE SRC="images/bgColorBlue.gif"></A><BR></TD>


<TD><A HREF="storeEntryPage.jsp?change=coloryellow<%=state%>">


<IMAGE SRC="images/bgColorYellow.gif"></A><BR></TD>


<TD><A HREF="storeEntryPage.jsp?change=colorgreen<%=state%>">



<IMAGE SRC="images/bgColorGreen.gif"></A><BR></TD>

Include a header file
for the header of the
page



Below the header, we use a
table made up of two cells,
and include the navigation
HTML in one cell, and the
content HTML in another
cell.



Finally, we include a
footer file for the
foot
er of the page




15


<TD><A HREF="storeEntryPage.jsp?change=colororange<%=state%>">


<IMAGE SRC="images/bgColorOrange.gif"></A><BR></TD>


</TR>

</TABLE>



</CENTER>


</BODY>

</HTML>


The store entry page bas
ically builds a JSP by assembling together several HTML pages
(header.html, footer.html, nav.html, and content.html). Even more, this is a customizable page
that the user can change by clicking on the menu at the bottom of the page.


The page works by hav
ing the request object retrieve variables at the top of the JSP code that are
sent to the page via the URL. These variables and their values are sent by the
image
links that are
built at the bottom of the JSP code.


Task #2: Building a Payment Page


Java

Server Page Tasks


We’ll now look at how to build a page to have a customer pay for some items. Listing
6

shows a
simple payment page that sends a set of billing and payment information to


Listing
6
: First Try at a Payment Page (paymentForm.jsp)

<%@ pa
ge import = "java.util.*" %>


<HTML><HEAD><TITLE>Dynamic Form</TITLE></HEAD>

<BODY>



<%


// Generate a table of form fields

%>


<B>Payment and Shipping Information</B><BR>

Please make sure the name you type in below corresponds to the format of the name

on your credit
card.

<FORM ACTION=paymentForm.jsp METHOD=POST>

<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0>


<%


// Generate a number of fields with appropriate widths for the information the customer will
input

%>


<%


String[] textFields = {"Firs
t Name", "Middle Initial", "Last Name", "Street Address",
"Apartment Number", "City", "Zip Code"};


int[] textFieldLength = { 20, 1, 20, 25, 10, 25, 5 };



String[] textFieldsNoSpaces = new String[ textFields.length ];


for (int j=0; j<textFields.
length; j++) {


textFieldsNoSpaces[j] = textFields[j].replace(' ', '_');


}



for(int j=0; j<textFields.length; j++){ %>


<TR> <TD> <%=textFields[j]%>: </TD>


<TD> <INPUT TYPE=TEXT NAME=<%=textFieldsN
oSpaces[j]%> SIZE=<%=textFieldLength[j]%>
MAXLENGTH=<%=textFieldLength[j]%>> </TD>


16


</TR>

<% } %>



<%


// Drop down choice of State abbreviations

%>


<TR> <TD> State: </TD>


<TD> <SELECT NAME=State>

<% String[] states = {"AZ",
"CA", "CT", "NM", "MA", "ME", "MD", "MN", "WI"};


for(int s=0; s<states.length; s++) { %>


<OPTION><%=states[s]%></OPTION>

<% } %>


</SELECT></TD>


</TR>




<%


// Enter credit card number

%>


<TR> <TD
> Credit Card Number: </TD>


<TD> <INPUT TYPE=TEXT NAME=cNumber MAXLENGTH=16></TD>


</TR>



<%


// Drop down choice of credit card type

%>


<TR> <TD> Credit Card Type: </TD>


<TD> <SELECT NAME=CardType>

<% String[] cType
s = {"Amex", "Visa", "Master Card", "Discover", "Diners Club"};


for(int t=0; t<cTypes.length; t++) { %>


<OPTION><%=cTypes[t]%></OPTION>

<% } %>


</SELECT></TD>


</TR>





<%


// Choose credit card expirati
on date


// Automatically creates a list of dates based on the current year

%>




<TR> <TD> Expiration Date (MM/DD/YYYY) </TD>


<TD> <INPUT TYPE=TEXT NAME=cMonth SIZE=2><INPUT TYPE=TEXT NAME=cDay SIZE=2>


<SELECT NAME=cYear>



<%


Calendar rightNow = Calendar.getInstance();


int startYear = rightNow.get(rightNow.YEAR);



for(int y=startYear; y<startYear+11; y++) { %>


<OPTION><%=y%>
</OPTION>


<% } %>


</SELECT></TD>


</TR>

</TABLE>


<INPUT TYPE=SUBMIT VALUE=Submit>

</FORM>





<%


// Process the payment information

%>




17

<HR>

<B>Your Payment and Shipping Information</B><BR>

<TABLE>

<%


Enumera
tion parameters = request.getParameterNames();


while(parameters.hasMoreElements()){


String parameterName = (String)parameters.nextElement();


String parameterValue = request.getParameter(parameterName); %>


<TR>


<TD><%
=parameterName%></TD>


<TD><%=parameterValue%></TD>


</TR>

<% } %>

</TABLE>


</BODY>

</HTML>


The JSP in Listing
6
doesn’t report back the user input in a very nice manner, so let’s make it a
little more clean by substituting the sect
ion that handles user input with the code in Listing
7
.


Listing
7
: Improved Handling of User Input (part of paymentForm2.jsp)

<%


// Process the payment information

%>


<HR>

<B>Your Payment and Shipping Information</B><BR>

<%


// First retrieve a
ll user request parameters



String firstname = request.getParameter( "First_Name" );


String middleinit = request.getParameter( "Middle_Initial" );


String lastname = request.getParameter( "Last_Name" );




String address = request.g
etParameter( "Street_Address" );


String apartment = request.getParameter( "Apartment_Number" );


String city = request.getParameter( "City" );


String stateabbr = request.getParameter( "State" );


String zipcode = request.getParameter( "Zip_Co
de" );



String cardtype = request.getParameter( "CardType" );


String cardnum = request.getParameter( "cNumber" );


String cardmonth = request.getParameter( "cMonth" );


String cardday = request.getParameter( "cDay" );


String cardyear = re
quest.getParameter( "cYear" );



// Now print them out



out.print( "<TABLE>" );


out.print( "<TR><TD>First Name: </TD><TD>" + firstname + "</TD></TR>" );


out.print( "<TR><TD>Middle Initial: </TD><TD>" + middleinit + "</TD></TR>" );


out.p
rint( "<TR><TD>Last Name: </TD><TD>" + lastname + "</TD></TR>" );



out.print( "<TR><TD>Street Address: </TD><TD>" + address + "</TD></TR>" );


out.print( "<TR><TD>Apartment Number: </TD><TD>" + apartment + "</TD></TR>" );


out.print( "<TR><TD>Cit
y: </TD><TD>" + city + "</TD></TR>" );


out.print( "<TR><TD>State: </TD><TD>" + stateabbr + "</TD></TR>" );


out.print( "<TR><TD>Zip Code: </TD><TD>" + zipcode + "</TD></TR>" );



out.print( "<TR><TD>Card Type: </TD><TD>" + cardtype + "</TD></TR>"

);


out.print( "<TR><TD>Card Number: </TD><TD>" + cardnum + "</TD></TR>" );


out.print( "<TR><TD>Card Expiration Month: </TD><TD>" + cardmonth + "</TD></TR>" );


out.print( "<TR><TD>Card Expiration Day: </TD><TD>" + cardday + "</TD></TR>" );


out.print( "<TR><TD>Card Expiration Year: </TD><TD>" + cardyear + "</TD></TR>" );


out.print( "</TABLE>" );

%>



18

Finally, instead of having nowhere to go with our payment information, we might want to send
the customer information

to a checkout page.

Th
e files
paymentForm3.jsp

and
checkoutForm.jsp

contain the enhanced code for doing this


you can download them from my
/gregheim/md254/tutorial/

directory on WebAppCabaret.



Database Tasks


Eventually, we’ll need to create a database table to handle custo
mer information that we’ll want
to store about an order. We’ll assume that customers will register as a site user when they first
purchase something, and so we’ll want to maintain a registration database of user information.
We’ll also need to create a tab
le of orders for the orders that are placed. For now, however, we’ll
leave this page alone.


Task #3: Tracking Customers


Java Server Page Tasks


If we were really building

a shopping cart, we’ll need a way to track our customers from the
point that they e
nter our site, through to the point that they pay for items and exit the site. The
objective of tracking customers is to be able to understand “user state,” or information about
what the user is doing at present. The HTTP protocol does not track user state

(it is a so
-
called
“stateless protocol”), but technologies such as Cookies and User Session IDs have been
developed to be able to track user state



i.e., monitor what the customer is doing on which page
.


Java Server Pages provide you with several tools

for keeping track of what a customer is doing.
These tools include (i) cookies, (ii)
session

objects, and (iii) URL encoding.


Cookies are simple text strings that are sent to the customer’s browser, stored there in a cookie
file, and sent back to the se
rver when requested by the server. Cookies allow us to save
information about what a customer is doing, but using Cookies is cumbersome because we have
to write special code to process them for a page.


The
session

object can also be used to keep track of
temporary data about a user that an e
-
Service is interacting with. Essentially, the
session

object is a Java class that provides a set of
methods and data structures that you can use to manage cookies easily. So, you should think of
the
session

object as s
imply a tool that manages cookies for you


instead of you having to
program some code that will manage cookies directly.


Important Note: As a result, if a customer has their browser or other device set to
not accept cookies, neither Cookies nor the
sessi
on

object will work to manage
their user state.


Listing
8

and

Listing

9

present a simple example of two pages that could be used in a shopping
cart based on cookies. The two different pages contain lists of products (toys in toys.jsp, and
CDs in cds.jsp)
that are presented to a user. By clicking on the links, the customer can either (i)
add items to the shopping cart, or (2) empty the shopping cart.


19


Listing
8
: Shopping Cart Page (toys.jsp) Using
session
Object

<%@ page import = "java.util.*" %>


<HTML>

<
HEAD>

<TITLE>Toy Catalog Page</TITLE>

</HEAD>

<BODY>


[<A HREF=cds.jsp>Shop for CDs</A>]


<H1>Toy Catalog</H1>

<TABLE>

<% String[] titles = {"Toy_1","Toy_2","Toy_3", "Toy_4","Toy_5"};


for(int j=0; j<titles.length; j++){ %>


<TR><TD><%=titles[j]%></T
D>


<TD><A HREF=toys.jsp?itemName=<%=titles[j]%>>


Add to Shopping Cart</A></TD>


</TR>

<% } %>

</TABLE>




<A HREF=toys.jsp?itemName=emptyCart>Empty Shopping Cart</A>




<% String item = request.getParameter("itemName");


if(item

!= null && item.equals("emptyCart")){


Enumeration attributeNames = session.getAttributeNames();


while(attributeNames.hasMoreElements()){


String attributeName = (String)attributeNames.nextElement();


session.removeAttribute(attribute
Name);


}


} else if(item != null){


String attributeName = item + "CD";


session.setAttribute(attributeName,item);


}

%>




<HR>

<H1> Content of Shopping Cart </H1>

<UL>

<% Enumeration attributeNames = session.getAttributeNames();


while
(attributeNames.hasMoreElements())


{


String attributeName = (String)attributeNames.nextElement();


String attributeValue = (String)session.getAttribute(attributeName); %>


<LI><%=attributeValue%>

<% } %>

</BODY>

</HTML>



20


Listing
9
: Shopp
ing Cart Page (cds.jsp) Using
session

Object

<%@ page import = "java.util.*" %>


<HTML>

<HEAD>

<TITLE>CD Catalog Page</TITLE>

</HEAD>

<BODY>


[<A HREF=toys.jsp>Shop for Toys</A>]


<H1> Online CD Catalog </H1>

<TABLE>

<% String[] titles = {"CD_1", "CD_2", "
CD_3", "CD_4", "CD_5"};


for(int j=0; j<titles.length; j++){ %>


<TR><TD><%=titles[j]%></TD>


<TD><A HREF=cds.jsp?itemName=<%=titles[j]%>>


Add to Shopping Cart</A></TD>


</TR>

<% } %>

</TABLE>



<A HREF=cds.jsp?itemName=empt
yCart>Empty Shopping Cart</A>




<% String item = request.getParameter("itemName");


if(item != null && item.equals("emptyCart")){


Enumeration attributeNames = session.getAttributeNames();


while(attributeNames.hasMoreElements()){


String
attributeName = (String)attributeNames.nextElement();


session.removeAttribute(attributeName);


}


} else if(item != null){


String attributeName = item + "CD";


session.setAttribute(attributeName,item);


}

%>




<HR>

<H1> Content of
Shopping Cart </H1>

<UL>

<% Enumeration attributeNames = session.getAttributeNames();


if(attributeNames != null)


while(attributeNames.hasMoreElements())


{


String attributeName = (String)attributeNames.nextElement();


String attributeValue

= (String)session.getAttribute(attributeName); %>


<LI><%=attributeValue%>

<% } %>

</BODY>

</HTML>


Of course, if the customer has cookies turned off, neither toys.jsp or cds.jsp will work. Thus, we
would have to tell the user to turn cookies on, or
to leave the store.


21


URL encoding is a mechanism for managing user state that does not rely on cookies, and can
thus be used when a user has cookies turned off. Instead of using the
session

object to manage
cookies, we can use the
response

object to handl
e URL encoding. The
response

object has
several methods that will be important for you to know about
, shown in Table 5
:


Table
5
: URL Encoding Methods Provided by the
response

Object

Method

Description

String encodeURL(String url)

When encoding is needed
, it encodes the URL by
appending the session ID in the URL’s query string.

String encodeRedirectURL(String
url)

When encoding is needed, it encodes the URL to be
used with the sendRedirect() method, listed below.

void sendRedirect(String url)

Sends a re
direct response to the client using the URL.


By using the
response

object, we can get around problems involved with Cookies and the
session object, and we can also avoid having to write a URL encoding procedure (that might not
work), and instead use one
that already works. What happens when using the
response

object
is that a variable for the session ID will be added to each URL. This variable is often called
“jsessionid”, although other web servers will use different names. Listing
10

gives a very simple

example of how the
response

object can be used to track a customer.


Listing
10
: Using the response Object to Encode URLs (encodingURLs.jsp)

<HTML><HEAD><TITLE>Encoding URLs</TITLE></HEAD>

<BODY>

<B>Example encoded hyperlink: </B>

<% String link =
response.encodeURL("index.jsp");


String button = response.encodeURL("index.jsp");


String sessionID = request.getRequestedSessionId();

%>

<A HREF="<%=link%>">Click here</A>

<HR>

<FORM METHOD=POST ACTION="<%=button%>">

<B>Example encoded button: <
/B><INPUT TYPE=SUBMIT VALUE="Submit">

</FORM>

<HR>

<B>Session ID</B>

<%=sessionID%>

</BODY>

</HTML>


If you upload and run Listing 10,
and you have Cookies enabled,
you will see at the bottom of
the page that the Session ID is printed out for the user’s s
ession.

If you don’t have Cookies
enabled, you will notice that the URL for the page is appended with a “jsessionid”.



22


Homework Activities


ACTIVITY #
5

Create a Database Table on

WebAppCabaret.com

Using
the
TEATIMEJ

application
, create a

new

MySQL databa
se table for an online store, and
name your table “**storeproducts”, where ** is replaced by your initials, in lowercase.

Construct
the table

so that it contains columns

that relate to pieces of information that would be important
in an online store (e.g.,

product
_
id, product
_
name, price, and
other variables).


Make sure to change the data types to appropriate data types for the MySQL database
. The
WebAppCabaret MySQL database has been set up to allow us to use the following data types:
BIGINT, CHAR, DATE,

DATETIME, DECIMAL, INT, LONGTEXT, MEDIUMINT,
SMALLINT, TEXT, TIMESTAMP, TINYINT, and VARCHAR. Information about many of
these is presented in the table below. For
this exercise, it is prob
ably best to just use INT,
DECIMAL
, and CHAR o
r VARCHAR).


MySQL Da
ta Type

MySQL Synonyms

Description

BYTE

TINYINT, BIT, BOOLEAN

1 byte signed integer

INT

INTEGER, SHORT, SMALLINT

4 byte signed integer

LONG


8 byte signed integer

DECIMAL

NUMERIC

Varies with specification

CURRENCY


Descended from LONG

DOUBLE


8 byte
floating point

FLOAT


4 byte floating point

DATE

DATETIME, TIME, TIMESTAMP

Descended from LONG

CHAR

VARCHAR, VARCHAR2

Variable length String

SMALLCHAR


Single type ASCII variable length
string


After you get done constructing the table, populate the t
able with some data. To do so, you can
use either a SQL command inside of the TEATIMEJ, or rewrite Listing 10 from Tutorial 2,
which is the next exercise below


ACTIVITY #
6

Write a JSP the Retrieves Data From Your Table

Rewrite the JSP from Listing 10
(the

phonebook example)
in Tutorial 2 to create a page that can
print out all of the data that is contained in the
store products
table you’ve created, and that
provides a form for putting data into the table. Accomplishing this will entail the following steps
:




You’ll need to modify the form field section to add additional forms for the new data
columns that you have placed in your table.



You’ll need to change the list of names of the columns at the top of the table of data you
print out.



You’ll need to modify

the SQL commands in the JSP that save data

into your table.



You’ll need to change the while loop that prints out the data that has been retrieved from
the table.



23



ACTIVITY #
7

Create a Store Front Page

In this exercise, you will rebuild the store front p
age example under your own directory.
The JSP
files for the
store

entry page

example (Listing 5


storeEntryPage.jsp)

are located in my

/gregheim/md254/tutorial/

directory on the WebAppCabaret site. The
required
activities are to
do the following:


(1)

Modify
the storeEntryPage.jsp file so that it has a different look to it


essentially, turn it into
a storefront for your own store. To do so, you’ll need to do the retrieve the following files
from my directory, put them in your own directory, and then edit the
m:

a.

Download the following files from the folder
/gregheim/md254/tutorial/
. Upload
them to your own directory.

i.

storeEntryPage.jsp

ii.

header.html

iii.

footer.html

iv.

nav.html

v.

content.html

b.

Download all of the image files from the folder
/gregheim/md254/tutorial/
images/
.

Create a folder /images/ inside of your folder, and upload the image files into it.
You
can also just copy them directly, by using the Copy button in the FileMgr menu.

c.

You can check whether you downloaded and installed everything correctly by
comparing yo
ur page against the page in my directory, which is at the URL
http://209.11.145.27/md254/tutorial/storeEntryPage.jsp

d.

As you can tell, the page doesn’t look so good

(I’m more of a progr
ammer than a
content designer or visual designer)
. Modify the look of the page by changing the text
within the header.html, footer.html, nav.html, and content.html files.

Your job is to
make this a beautiful website (within reason, of course). Notice that
when you are
doing this, you are not modifying Java code at all


that is, you as the designer are
kept away from the Java code so you cannot mess anything up.

(2)

Create a simple page called aboutUs.jsp by importing the template files header.html,
footer.html
, nav.html, and a new template you’ll create named aboutUsContent.html

(3)

Create a simple page called contactUs.jsp by importing the template files header.html,
footer.html, nav.html, and a new template you’ll create named contactUsContent.html

Upload aboutUs
.jsp, contactUs.jsp, storeEntryPage.jsp, and the set of templates and graphics
required for storeEntryPage.jsp, to your own directory, and get them to work.


ACTIVITY #
8

Create a Store Front Page

Download the JSPs paymentForm3.jsp and checkoutForm.jsp.
Edi
t them so that they have the

following

changes
:



Change the list of states in the payment form. Add some additional states.



Add another credit card name to the payment form.



Extend the range of years for the credit card expiration date.

Upload them to

your

directory and make sure they run.