Вы находитесь на странице: 1из 440

J2EE Overview

Version 2.0

Copyright © 2008, Wipro Limited, Bangalore

1
J2EE Overview

§ Day 1
– HTML
§ Day 2
– Javascript
§ Day 3
– JDBC
§ Day 4
– Servlets
§ Day 5
– JavaBeans and Java Server Pages
§ Day 6
– J2EE

Version 2.0 2

2
Module 1:
HTML

Copyright © 2008, Wipro Limited, Bangalore

3
HTML

The lessons covered in this module include:


§ Web Architecture
§ Introduction to HTML
§ Features of HTML
§ HTML TAG
§ Types of HTML Tags
– Layout Tags
– Semantic Tags
– Application Tags
– Logical Tags

Version 2.0 4

4
Objectives

At the end of this module you will be able to:


§ Define a web architecture
§ Define HTML
§ Define and use different types of Tags
§ Create simple static web pages
§ Create and work on forms

Version 2.0 5

5
WEB Architecture

WEB SERVER

WEB Page (Home)

WEB SITE

Version 2.0 6

WEB SERVER: A computer, including software package, that provides a


specific kind of service to client software running on other computers. A
system which accepts web page requests from the client machines and
redirect the request to the machine which holds the relevant website
containing the webpage.

WEBSITE: A homogenous collection of Web Pages.

WEB PAGE:A consolidated page designed and developed with an


intention of displaying information.

6
Introduction to HTML

The Problem

§ Universally computer Understandable language to publish


information for global distribution.

The Solution:

§ HTML - Stands for Hyper Text Markup Language.


§ Special text documents used by web browsers to present text and
graphics.

Version 2.0 7

What is HTML?

To publish information for global distribution, one needs a universally


understood language, a kind of publishing mother tongue that all
computers may potentially understand. The publishing language used by
the World Wide Web is HTML (from HyperText Markup Language). It is
a special kind of text document that is used by Web browsers to present
text and graphics. HTML documents are often referred to as "Web
pages". The browser retrieves Web pages from Web servers.

HTML was originally developed by Tim Berners-Lee while at CERN, and


popularized by the Mosaic browser developed at NCSA. During the
course of the 1990s it has blossomed with the explosive growth of the
Web. During this time, HTML has been extended in a number of ways.
The Web depends on Web page authors and vendors sharing the same
conventions for HTML.

7
Features of HTML

HTML helps to:


§ Publish online documents with headings, text, tables, lists, photos,
etc.
§ Retrieve online information via hypertext links, at the click of a
button.
§ Design forms for conducting transactions with remote services, for
use in searching for information, making reservations, ordering
products, etc.
§ Include spread-sheets, video clips, sound clips, and other
applications directly in their documents.

Version 2.0 8

HTML is case insensitive i.e. the case used to open and close the tag is
not strictly monitored.
<HTML></html> will have the same effect.

HTML Provides a pre-defined set of tags that can be used to present any
kind of data and information.

Most of the tags that are used in coding the HTML document are easily
parsed by any kind of browsers (There are certain exceptions such as
Column, Blink tag does not show any effect in the MSIE)

8
HTML Tag

HTML tag is a markup and identifies a page element's type, format, and
appearance.

All HTML tags are enclosed in brackets (i.e. <table>).

Some tags require closing tags.

Version 2.0 9

HTML tag is a markup inserted into an HTML document to provide


information about a unit of content and using a text string identifies a
page element's type, format, and appearance.
The Text string or the Tag is enclosed within lesser-than (<) and greater-
than (>) symbol.
Though all tags must have a closing it is not strictly checked in normal
web page. But for some tags (like Textarea) the Closing tags are
mandatory.

9
Types of HTML Tags

1. Layout Tags 3. Application Tags


– Basic Tags – Forms
– Structural Tags – Tables
– Frames
2. Semantic Tags
– Presentation Tags 4. Logical Tags
– Links & Graphics – Emphasized Tag
– List – Strong Tag
– Dividers – Code Tag
– Backgrounds and Colors
– Special Characters

Version 2.0 10

This segregation is not a hard and fast or concrete division; it is only


made to make the understanding process easier.

LAYOUT TAGS:
Define the appearance of the webpage. It talks about the overall look of
the webpage where which text should appear where and which image
should appear where is decided.

SEMANTIC TAGS:
On contrary to Layout Tags which define where the text/image is to be
displayed the semantic tags define how they should be displayed. They
define the format in which the text/image should be displayed.

APPLICATION TAGS:
These tags are used for creating advanced and complex arrangements of
webpage's (Ex. Frames) and also to provide a base for user interaction.

10
Layout Tags

Layout tags define the layout of the WEB Page and define what text
goes where and is displayed where.

BASIC Tags:
<HTML></HTML> Defines Start and end of Web page
<HEAD></HEAD> Defines the Header section of the Web Page
<TITLE></TITLE> Defines the Title of the web page displayed on
the title bar
<BODY></BODY> Defines the body / content of the page.

STRUCTURAL Tags:
<H?></H?> Heading tags. ‘?’ Ranges from 1 to 6, defines heading
<PRE></PRE>Preformatted Text

Version 2.0 11

11
A Typical HTML page starts and ends with <HTML> tags. The entire page
is divided into two logical sections the Head and the Body. The Head
Section is enclosed by <HEAD>Content</HEAD>, generally contains
information recurring in more than one page e.g. Company Logo. The
Head also includes the Title Section enclosed by <TITLE></TITLE> and
text between this tag is displayed in the title bar of the browser. The Body
section is enclosed by <BODY>Content</BODY>, generally contains
information that is normally not repeated.
<HTML>
<HEAD>
<TITLE>Login Page</TITLE>
</HEAD>
<BODY>
Welcome to the Green Bank
</BODY>
</HTML>

HEADING TAGS: used to display headings; enclosed in


<H>heading</H>. For content enclosed by the Heading tags a default
format is applied which is defined by the tag:
<HTML>
<HEAD>
<H1>This is Heading 1 tag</H1>
<H2>This is Heading 1 tag</H2>
<H3>This is Heading 1 tag</H3>
<H4>This is Heading 1 tag</H4>
<H5>This is Heading 1 tag</H5>
<H6>This is Heading 6 tag</H6>
</HEAD>
</HTML>
PREFORMATED TAGS: used to apply structural exactness to that of the text
in the editor.
<PRE>

the text will be displayed to the right of the browser

at the same distance as it is now in the editor.


</PRE>

12
Semantic Tags

1. Presentation Tags
2. Links & Graphics
3. Lists
4. Dividers
5. Backgrounds and Colors
6. Special Characters

Version 2.0 13

Presentation Tags are used to present text on the web page. E.g., <B> for
bold, <I> for italicizing the text.
Links and Graphics tags are used to link text from one page to another or
on the same page. HyperLinks and Bookmarks are the Links that are
used.
List is used to display items in form of la list of terms (with and without
definition). Examples are Ordered list, Unordered List and Glossary List.
Divider is used to make a clear differentiation between text.
E.g., Paragraph, and Line dividers.
Backgrounds and Color is used to change the Background colors or
images.
Special Characters are used to display special characters. Characters
which are either ignored by the browser (e.g., Blank space) or characters
that are not present on the keyboard (e.g., Copyright symbol).

13
Semantic Tags: Presentation Tags

Bold <B>Text</B> Superscript <SUP></SUP>

Italic <I>Text</I> Subscript <SUB></SUB>

Underline <U>Text</U> Typewriter <TT></TT>

FONT SETTINGS:
<FONT
SIZE=“12 / + / - ”
Attribute set
COLOR=“#FFOO00”
FACE=“Times” >
</FONT>

Version 2.0 14

Example:

<HTML>
<HEAD></HEAD>
<BODY>
This the default text format<BR>
<FONT NAME=“IMPACT” SIZE=“12” COLOR=“Red”>This the from Font Tag
</FONT><Br>
<B>This is a Bold Text, </B><BR>
<I>This is a italicized text</I><BR>
<U>This is underlined text</U><BR>
Text like date requires to be super scripted like this 12<SUP>th</SUP>.<BR>
and when writhing chemical formulas like that of water H<SUB>2</SUB>O<BR>
</BODY>
</HTML>

14
Semantic Tags: Links & Graphics

Anchor: <A>
An anchor can be used to create a link to another document (with
the href attribute) or to create a bookmark inside a document (with
the name attribute).
Syntax:
<A HREF=“URL”>Display Text</A>

Types of Links:
1. Internal Links
2. External Links

Version 2.0 15

The word hyper stands for “Without limits” i.e. there is no boundary. The
Anchor (<A>) tag is used to hook a link in one place which links that
point to a point which can exists any where in the Internet.

INTERNAL LINKS & EXTERNAL LINKS:


Internal links again are of two types one links a point form one page to
another page in the same website and the other links a point from a page
to another point in the same page (Bookmark).

External links are most similar to that of first type of Internal links only
difference is that the link is pointing to an external page (out of the scope
of the current existing page. Ex. A news link in the yahoo website)

15
Links & Graphics (Contd.).

External Links:
<A HREF=“https://webmail.wipro.com”>Webmail</A>

Internal Links:
<A HREF=“\JSP\Register.jsp”>Register</A>

BookMark:
Create bookmark
<A NAME=“Book”>Bookmark</A>
Create a link to bookmark
<A HREF=“#Book”>Go to Bookmark</A>

Version 2.0 16

16
Hyper Link: A Hyperlink can be created with the following:
< A HREF=“URL” TARGET=“FRAME”>Display text</A>
It has major two attributes; “HREf” stands for Hyper reference and target.
A hyper reference take the value of the URL to which the link is to be
created. E.g., if the link is for yahoo domain then the HREF value will be
“http://www.Yahoo.com”.
The Target attribute tells the browser regarding where it has to open the
newly requested page. The developer can ask the page to be opened in the
same browser or a new browser or it can even be a specific frame if the site
uses Frame pages.
The various values that the TARGET attribute can take are:
“_main” to open in the same window
“_blank” to open in a new window
“_parent” to open the same window (regardless of frames in the window)
“Frame name” - in case of Frame pages a custom defined frame name
*NOTE: By default the link will always open the requested page in the
same window or frame where the link exists.

Book Mark:
Create a book mark for whom a link can be created.
<A NAME=“Bookmark_Name”>Display Book Mark Title</A>
Creating a link to already created book mark
<A HREF=“# Bookmark_Name”>Dispay link to book mark</A>
You can see that the only difference between the a hyper link and a
bookmark link is that the Hyper reference start with “#” (HASH) symbol.

17
Links & Graphics (Contd.).

Image:
<IMG SRC=“URL” ALT=“Alternate Text”>

Example:
<IMG SRC=“\images\wipro.jpg” ALT=“Alternate Text”>

Version 2.0 18

INSERTING IMAGES
The syntax for the tag to insert image into the webpage is:
<IMG SRC=“” ALT=“”/>
“SRC” Attribute: used to mention the path where the image file is stored
and the image file name.
“ALT” Attribute: used to display an alternate text in case the image file
could not be loaded.

18
Semantic Tags: List

Semantic tags provide the Author with feature of displaying text in


hierarchical or tree structure format.

Three types of List are available:


§ Glossary List
§ Unordered List
§ Ordered List

Version 2.0 19

List allows the developer to list out the terms and important statements.

Glossary List:
If the terms are displayed in the form of Subtitle followed by a
description then the list is called as a Glossary list. The entire text on this
particular page can be treated as a Glossary list.

Ordered / Unordered List:


If only the terms are listed then they fall under Ordered list or Unordered
list. If the sequence of the terms/ordering is not of much importance
then the terms are listed under Unordered list where the terms are listed
with the help of bullets. In an Ordered list, the sequence of the
terms/ordering is important. Hence they are listed with the help of
numbering sequence.

19
List: Glossary List

Glossary list is used to display a list of alternating term with definition


paragraphs.
DL à Definition List, DT à Term, DD à Data
Example:
<DL>
<DT>Coffee</DT>
<DD>Black hot drink</DD>
</DL>
Output:
Coffee
Black hot drink

Version 2.0 20

Glossary List displays the terms with a brief description of the terms
thus giving it a title and definition form.
Definition List (DL) signifies the beginning and closing of the
Glossary list. The entire Glossary list is enclosed between <DL></DL>
tags.
Definition Term (DT) signifies the term that is to be defined (The
title/term). It is enclosed between <DT></DT> tags.
Definition Data (DD) also called as Definition in short is the definition
or description of the term. It is enclosed between <DD></DD> tags.

Example:
<H2>
Functionalities of a customer login
</H2>
<DL>
<DT><FONT NAME="IMPACT" SIZE="5" COLOR="blue"> Fund
Transfer</font></DT>
<DD><b><h3>Within Same customer </DD></h3></b>
<DD><b><h3>Third Party Transfer</h3></b> </DD>
</DL>

20
List: Ordered List

An ordered list is a list of items. The list items are marked with
numbers.
Example:
<OL TYPE=“A”>
<LI>Country</LI>
<OL TYPE=“1”>
<LI>India</LI>
</OL>
</OL>
Output:
A. Country
1. India

Version 2.0 21

Ordered List is displayed and listed with help of numbers or clearly


identifiable symbols which are of incremental nature.

The Ordered list is defined with the help of the <OL></OL> tags. It has
TYPE attribute which is used to mention what type of sequence will be
used to display the terms. It can take the values such as “1”, “A”, “I”, etc to
display relevant sequence.

The List is generated with the help of <LI>term</LI> tags.


Example:
<u>In a Banking Application, functionalities of the Manager Login is as
follows</u>
<OL TYPE="A">
<LI>Administartor</LI>
<OL TYPE="1">
<LI>Create New Customer</LI>
<LI>Create New Account For Existing Customer</LI>
<LI>Disable Customer</LI>
</OL>
</OL>

21
List: Un-Ordered List

An unordered list is a list of items. The list items are marked with
bullets.

Example:
<UL TYPE=“Square / Circle / Disc”>
<LI>Country</LI>
<UL TYPE=“”>
<LI>India</LI>
</UL>
</UL>

Version 2.0 22

Unordered List:
The Unordered list is defined with the help of the <UL></UL> tags. It has
TYPE attribute which is used to mention what type of bullet will be used
to display the terms. It can take the values such as “Circle”, “Disc”,
“Square” to display relevant bullet.

The List is generated with the help of <LI>term</LI> tags.

Example:
<u>In a Bank Application, functionalities of the Staff Login is as follows<u>
<UL TYPE="circle">
<LI>Staff</LI>
<UL TYPE="square">
<LI>Deposit Amount</LI>
<LI>WithDraw Amount</LI>
</UL>
</UL>

22
Semantic Tags: Dividers

Paragraph:
<p align=“Left/center/right/justify”>Text</p>

LineBreak:

<BR/> gives a single carriage return.

Horizontal Rule:

<HR ALIGN=“left/center/right” SIZE=“” WIDTH=“” color=“”/>

Version 2.0 23

Paragraph:
<P></P> tags are used to divide the entire text into paragraph. This
makes it easier to apply universal formatting styles (Achieved by Style-
Sheets).

Line Break:
In case a line break is to be inserted the <BR> tag is used which works
similar to carriage return, i.e. breaks the line and starts printing from the
next line.

Horizontal Rule:
<HR> is used to include a horizontal line wherever necessary. It has two
attributes Align and size to mention the alignment and the size of the
line. It also has color attribute to mention the color for the line. It is
basically used to mark a clear differentiation between two texts.

23
Semantic Tags: Background and Colors

To change background Image


<BODY BACKGROUND=“URL”>

To change background color


<BODY BGCOLOR= “COLOR” >

Version 2.0 24

The Background plays an important role in the presentation of


information. There is a feature to add colors and images as background.
It can be achieved by two attributes “BACKGROUND” and “BGCOLOR”

The “BACKGROUND” attribute can be used to display an image as


background. The value for this attribute will the path to the file which is
to be displayed as background.

The “BGCOLOR” attribute helps in displaying a color as background.

*NOTE: These two attributes are supported by most of the Tags in


HTML.

<html>
<body bgcolor=“blue” >
<body background=“image.jpg”>
</html>

24
Semantic Tags: Special Characters

Syntax:
&#char code; or &code;

Example:

< &lt;
> &gt;
& &amp;
“ &quot;
Registered Trade mark &#174; or &reg;
Copyright &#169; or &copy;
Non-Breaking space &nbsp;

Version 2.0 25

There are certain characters that cannot be directly displayed on the


screen, For example Copyright, blank space.

To display these kind of characters HTML provides a unique way. i.e. Use
of ampersand symbol and the character code or a specific code Defined
in HTML.

25
Application Tags

1. Table
2. Form
3. Frames

Version 2.0 26

26
Application Tags: Tables

Tags Purpose

<TABLE> Begins the table definition


<TR> Defines a new row
<TD> Defines a single cell

<TH> Defines header cell

Version 2.0 27

Tables are used to display text / Information in tabular format, i.e., in the
from of rows and columns.

27
Tables: Table Attributes

ALIGNMENT Left / center / right

BORDER Defines the border

WIDTH Defines the width of the table

CELLSPACING Space between the cells

CELLPADDING Space between the text and cell border

EXAMPLE:
<TABLE ALIGNMENT=“center” BORDER=“0” WIDTH=“100%”
CELLSPACING=“2” CELLPADDING=“4”>

Version 2.0 28

28
Tables: Merging Cells

1. ROWSPAN
Used to merge cells in rows
<TD ROWSPAN=“2”> two cells in consecutive columns are
merged

2. COLSPAN
Used to merge cells in Columns
<TD ROWSPAN=“2”> two cells in consecutive rows are merged

Version 2.0 29

EXAMPLE for a login Page


<body bgcolor="blue" background="c:\bank-cashier.jpg">
<table align="center" width="20%" >
<tr> <td>User Id</td><td> <input type="text" name="username"
value=""></td></tr>
<tr><td>Password</td><td> <input type="text" name="password"
value=""></td></tr>

<tr><td><input type="submit" name="submit" align="center"


value="Login"></td></tr>
</table>

29
Example for Merging Cells:

<TABLE BORDER="7" CELLPADDING="7" CELLSPACING="10">


<TR BGCOLOR="#00FF00">
<TD>A green row.</TD>
<TD BGCOLOR="#FFFF00">This cell should be yellow, overriding the row
color.</TD> <TD>Back to the row color.</TD>
<TR BGCOLOR="#0000FF">
<TD>A blue row.</TD>
<TD><PRE> </PRE></TD>
<TD ROWSPAN="2">This cell takes the color of the topmost row that it
spans</TD>
</TR>
<TR BGCOLOR=“#FF0000">
<TD colspan=“2” align=“center” >A red row.</TD>
</TR>
</TABLE>

30
Application Tags: Forms

Mode of accepting input from user

Container: Form
<FORM NAME=“” ACTION=“” METHOD=“”></FORM>

Components: Form Elements


§ These are the data fields in the form, such as text fields and
checkboxes.
§ The <INPUT> tag can be used to create:
– Text boxes - Radio buttons
– Check boxes - Submit buttons
– Reset buttons - Password
– Generic buttons
§ There are other tags like TEXTAREA and SELECT for other
purposes.
Version 2.0 31

A form is an area that can contain form elements.

Form elements are elements that allow the user to enter information
(like text fields, textarea fields, drop-down menus, radio buttons,
checkboxes, etc.) in a form.

It has three main attributes:


1) NAME used to identify the form.
2) ACTION points towards which page the data is to be sent.
3) METHOD takes one the two values GET/POST. Defines what kind of
action is to be performed.

31
Forms: Input Tag

Input tag is a single tag option for gathering information

Input tag contains all of the other options for acquiring information,
including simple text fields, password fields, radio buttons, check
boxes, and the buttons to submit and reset the form.
<INPUT TYPE = “ * ” > * can take the following values:

Text TextField

Radio Radio Button

Checkbox Checkbox

Password Password TextField

Version 2.0 32

The most used form tag is the <input> tag.


The type of input is specified with the type attribute.
The most commonly used input types are explained below:

Text Fields are used when you want the user to type letters, numbers,
etc. in a form.
Radio Buttons are used when you want the user to select one of a
limited number of choices.
Checkboxes are used when you want the user to select one or more
options of a limited number of choices.

32
Input Tag: Text Area

<TEXTAREA NAME=“” ROWS=“” COLS=“”>


Text to be displayed in the Text Area
</TEXTAREA>

EXAMPLE:

<TEXTAREA NAME="addressbox" ROWS="5" COLS="20 “align="center">

This is an example for multilined text box (TEXTAREA)

</TEXTAREA>

Version 2.0 33

TEXTAREA:
This component allows to enter a multi-line text, e.g., address.

It has three attributes:


NAME: name of the component
ROWS: Number of rows
COLS: Number of columns

33
Select

Select is used to display list box.


<SELECT NAME=“” MULTIPLE>
<OPTION VALUE=“taken value”>Display text</OPTION>
</SELECT>

EXAMPLE:
<select name="locations" align="center">
<option value="EC1">EC1</option>
<option value="EC2">EC2</option>
<option value="EC3">EC3</option>
<option value="EC4">EC4</option>
</select>

Version 2.0 34

Select option is used to display multiple options to the user in a restricted


amount of space.
It is also enforced to restrict the user in selecting a minimum/maximum
number of options from the available list.

SELECT:
<SELECT> is used to define the List.
It has a NAME attribute which is used to name the component.

OPTION:
<OPTION> tag is used to add items to the list.
The VALUE attribute is used to assign the value to the component.
The text in-between the <OPTION></OPTION> tag is only to display but
actually the value attribute is responsible for assigning the value to the
component.

34
Example

Creating a form to register new Customer is explained in detail.

Version 2.0 35

Example: To register a new customer to a bank


Newcustomerregistration.html

<HTML>
<HEAD>
<H2 ALIGN="center" > Customer Registration</H2>
</HEAD>

<BODY bgcolor="blue">
<FORM NAME="Registration " ACTION="Register.jsp" METHOD="post">
<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> First Name:</TD><TD><INPUT TYPE="text"
name="cust_first_name"/></TD></TR>
<TR><TD> Last Name:</TD><TD><INPUT TYPE="text"
name="cust_sec_name"/></TD></TR>
<TR><TD>Account No:</TD><TD><INPUT TYPE="text" name="Acc_no"
value= "auto Generated" ></TD></TR>

<TR><TD>Account Type:</TD><TD>
<SELECT NAME="acc-type">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="SB">SB</OPTION>
<OPTION VALUE="Current">Current</OPTION>
</SELECT>

35
<TR><TD>Customer ID:</TD><TD><INPUT TYPE="text"
name="cust_ID"/></TD></TR>
<TR><TD>Password:</TD><TD><INPUT TYPE="password"
name="user_password"/></TD></TR>
<TR><TD>Confirm Password:</TD><TD><INPUT TYPE="password"
name="confirm_password"/></TD></TR>

</TD></TR>
<TR><TD>Address:</TD><TD>
<TEXTAREA NAME="addressbox" ROWS="5" COLS="15"
ALIGN="center"></TEXTAREA>
</TD></TR>
<TR><TD> City:</TD><TD><INPUT TYPE="text" name="city"/></TD></TR>
<TR><TD> pin:</TD><TD><INPUT TYPE="text" name="pin"/></TD></TR>

<TR><TD>Profession:</TD><TD>
<SELECT NAME="Profession">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="Studying">Student</OPTION>
<OPTION VALUE="Employed">Employee</OPTION>
<OPTION VALUE="Businessman">SelfEmployed</OPTION>
</SELECT>
<TR><TD>eMail:</TD><TD><INPUT TYPE="text" name=""/></TD></TR>
<TR><TD>Gender:</TD><TD>
Male:&nbsp;<INPUT TYPE="Radio" NAME="R1"
VALUE="Male"/>&nbsp;&nbsp;Female:&nbsp;
<INPUT TYPE="Radio" NAME="R1" VALUE="Female"/>
</TD></TR>
<TR ><TD size ="2">DOB:</TD><TD>Date
<SELECT NAME="dob">
<OPTION VALUE="Select">1</OPTION>
<OPTION VALUE="2">2</OPTION>
<OPTION VALUE="3">3</OPTION>
<OPTION VALUE="4">4</OPTION>
</SELECT>
<TD size ="2" >Month
<SELECT NAME="month">
<OPTION VALUE="Select">1</OPTION>
<OPTION VALUE="2">2</OPTION>
<OPTION VALUE="3">3</OPTION>
<OPTION VALUE="4">4</OPTION>
</SELECT>

<TD size ="2">year


<SELECT NAME="year">

<OPTION VALUE="2">1970</OPTION>
<OPTION VALUE="3">1971</OPTION>
<OPTION VALUE="Select">1973</OPTION>
<OPTION VALUE="4">1973</OPTION>
</SELECT>
<TR><TD align="right"> <INPUT TYPE="submit" name="submit" value="Confirm
Details"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>

36
Application Tags: Frames

<FRAMESET COLS="25%,*">
<FRAME SRC=“left.htm“ NAME=“left”>
<FRAME SRC=“right.htm“ NAME=“right”>
</FRAMESET>

Version 2.0 37

HTML frames allow developers to present documents in multiple views,


which may be independent windows or subwindows. Multiple views offer
designers a way to keep certain information visible, while other views are
scrolled or replaced. E.g., within the same window, one frame might
display a static banner, a second a navigation menu, and a third the main
document that can be scrolled through or replaced by navigating in the
second frame.
FRAMESET: HTML defines a Framepage layout called as FRAMESET
which defines how many Frames are present in the page and how they
are aligned. The FrameSet is defined with the <FRAMESET></FRAMESET>
tags. It has two attributes “ROWS” and “COLS” which define whether the
Frame is divided into rows or columns.
At any point of time a Frameset can divide the page into either
rows or columns, but not both. In case it is to be done then a nested
frameset should be used.
Frame: Once the layout is defined it’s the frames that matter. Frames are
the webpages that will be loaded in the different segments created by the
FrameSet. Each frame should be given a name which will be used by the
Hyper link as target values (Refer slide No. 41)

37
Frames (Contd.).

<FRAMESET COLS="25%,*">
<FRAME SRC=“top.htm“ NAME=“header”>
<FRAME SRC=“body.htm“ NAME=“body”>
</FRAMESET>

Version 2.0 38

38
Example

Creating a transaction form in a Bank application is explained in detail.

Version 2.0 39

Example: To create transaction form in a Bank application:

Transaction.html
<Frameset Rows="70%,*">
<frame src ="Transation-select.html" name="upper">
<frame src = "transcationsecondform.html" name="lower">
</frameset>

39
Transaction-select.html

<CENTER>Customer name: </CENTER>


<body bgcolor ="red"></body>
<form name="login" action="" method="">
<table BORDER="" WIDTH="50%" CELLSPACING="2"
CELLPADDING="2" align="center">
<th><tr><td bgcolor="blue" > Account Number </td>
<td bgcolor="blue"> Account Type </td>
<td bgcolor="blue">Amount Balance </td><td bgcolor="blue">Mini
Statement</td></tr></th>
<br>
<tr><td bgcolor="white">56741234 </td> <td
bgcolor="white">Saving </td> <td bgcolor="white"> 200000
</td><td bgcolor="white"> <a
href=""><b>View</b></a></td></tr>
<br>
</table>

<br>
<br>
<br>
<CENTER>
<b>Transaction Type</b><br>
<input type="button" name="deposit" value="Deposit" '">
<input type="button" name="Withdrawal" value="Withdrawal" >
<br>
<br>
<input type="button" name="previous" value="Back">
</CENTER>
</form>

transactionsecondform.html

<body bgcolor="Blue">Amount Screen </body>

40
Nested Frames

<FRAMESET ROWS="25%,75%">
<FRAME SRC="top.htm" NAME="left"/>
<FRAMESET COLS="25%,75%">
<FRAME SRC="left.htm" NAME="left"/>
<FRAME SRC="right.htm" NAME="right"/>
</FRAMESET>
</FRAMESET>

Version 2.0 41

41
Example: To create main login page in a Bank Application

main-loginpage.html

<FRAMESET ROWS="25%,75%">
<FRAME SRC="background1.html" NAME="left"/>
<FRAMESET COLS="25%,75%">
<FRAME SRC="login.html" NAME="left" />
<FRAME SRC="background2.html" NAME="right" bgcolor="blue"/>
</FRAMESET>
</FRAMESET>

login.html

<form name="login" action="" method="">


<body bgcolor="blue" background="c:\bank-cashier.jpg">
<table align="center" width="20%" >
<tr> <td>User Id</td><td> <input type="text" name="username"
value=""></td></tr>
<tr><td>Password</td><td> <input type="text" name="password"
value=""></td></tr>

<tr><td><input type="submit" name="submit" align="center"


value="Login"></td></tr>
</table>
</form>

background2.html
<body bgcolor="green" >
<h3 align ="center"><a href="">about Us</a></h3>
<h3 align ="center"><a href="">Contact Details</a></h3>

42
Case Study: Bank Application

The examples given in the subsequent slides/pages illustrate the forms


required in a Banking Application.

Creating forms required for Manager login is explained in detail.

Version 2.0 43

main login page in a Bank Application

main-loginpage.html
<FRAMESET ROWS="25%,75%">
<FRAME SRC="background1.html" NAME="left"/>
<FRAMESET COLS="25%,75%">
<FRAME SRC="login.html" NAME="left" />
<FRAME SRC="background2.html" NAME="right" bgcolor="blue"/>
</FRAMESET>
</FRAMESET>
……………………………………………………………………………………………………………
login.html

<form name="login" action="" method="">


<body bgcolor="blue" background="c:\bank-cashier.jpg">
<table align="center" width="20%" >
<tr> <td>User Id</td><td> <input type="text" name="username"
value=""></td></tr>
<tr><td>Password</td><td> <input type="text" name="password"
value=""></td></tr>

<tr><td><input type="submit" name="submit" align="center"


value="Login"></td></tr>
</table>
</form>
……………………………………………………………………………………………..
background2.html
<body bgcolor="green" >
<h3 align ="center"><a href="">about Us</a></h3>
<h3 align ="center"><a href="">Contact Details</a></h3>
………………………………………………………………………………………………………………..

43
Forms for Manager Login Page

Managerscreen.html
<Frameset cols="40%,*">
<frame src ="managerform.html" name="left">
<frame src = "empty.html" name="right">

</frameset>
……………………………………………………………………..
Below form will be the home screen for admin login

managerform.html
<h1 align="center"> Manager</h1>
<body bgcolor="DeepSkyBlue">
<form name="manager" action="" method="post">
<center>
<br>
<br>
<input type="radio" color="red" name="manager" value="new Customer"
<b>Create new Customer</b><br><br>
<input type="radio" name="manager" value="new Account" ><b>Create new
Account</b><br><br>
<input type="radio" name="manager" value="Remove Customer" " ><b>Remove
Customer</b><br><br>
<input type="radio" name="manager" value="customertransaction" '"
><b>Customer Transaction</b>
</center>
…………………………………………………………………………………………………………………………
New Customer Registration Form:
newcustomerregistration.html
<HTML>
<HEAD>
<H2 ALIGN="center" > Customer Registration</H2>
</HEAD>

<BODY bgcolor="blue">
<FORM NAME="Registration " ACTION="Register.jsp" METHOD="post">
<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> First Name:</TD><TD><INPUT TYPE="text"
name="cust_first_name"/></TD></TR>
<TR><TD> Last Name:</TD><TD><INPUT TYPE="text"
name="cust_sec_name"/></TD></TR>
<TR><TD>Account No:</TD><TD><INPUT TYPE="text" name="Acc_no" value=
"auto Generated" ></TD></TR>

<TR><TD>Account Type:</TD><TD>
<SELECT NAME="acc-type">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="SB">SB</OPTION>
<OPTION VALUE="Current">Current</OPTION>
</SELECT>
<TR><TD>Customer ID:</TD><TD><INPUT TYPE="text"
name="cust_ID"/></TD></TR>
<TR><TD>Password:</TD><TD><INPUT TYPE="password"
name="user_password"/></TD></TR>
<TR><TD>Confirm Password:</TD><TD><INPUT TYPE="password"
name="confirm_password"/></TD></TR>
</TD></TR>

44
<TR><TD>Address:</TD><TD>
<TEXTAREA NAME="addressbox" ROWS="5" COLS="15"
ALIGN="center"></TEXTAREA>
</TD></TR>
<TR><TD> City:</TD><TD><INPUT TYPE="text" name="city"/></TD></TR>
<TR><TD> pin:</TD><TD><INPUT TYPE="text" name="pin"/></TD></TR>
<TR><TD>Profession:</TD><TD>
<SELECT NAME="Profession">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="Studying">Student</OPTION>
<OPTION VALUE="Employed">Employee</OPTION>
<OPTION VALUE="Businessman">SelfEmployed</OPTION>
</SELECT>
<TR><TD>eMail:</TD><TD><INPUT TYPE="text" name=""/></TD></TR>
<TR><TD>Gender:</TD><TD>
Male:&nbsp;<INPUT TYPE="Radio" NAME="R1"
VALUE="Male"/>&nbsp;&nbsp;Female:&nbsp;
<INPUT TYPE="Radio" NAME="R1" VALUE="Female"/>
</TD></TR>
<TR ><TD size ="2">DOB:</TD><TD>Date
<SELECT NAME="dob">
<OPTION VALUE="Select">1</OPTION>
<OPTION VALUE="2">2</OPTION>
<OPTION VALUE="3">3</OPTION>
<OPTION VALUE="4">4</OPTION>
</SELECT>
<TD size ="2" >Month
<SELECT NAME="month">
<OPTION VALUE="Select">1</OPTION>
<OPTION VALUE="2">2</OPTION>
<OPTION VALUE="3">3</OPTION>
<OPTION VALUE="4">4</OPTION>
</SELECT>
<TD size ="2">year
<SELECT NAME="year">
<OPTION VALUE="2">1970</OPTION>
<OPTION VALUE="3">1971</OPTION>
<OPTION VALUE="Select">1973</OPTION>
<OPTION VALUE="4">1973</OPTION>
</SELECT>
<TR><TD align="right"> <INPUT TYPE="submit" name="submit" value="Confirm
Details"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>
……………………………………………………………………………………………………….

45
Form to create new Account for existing Customer
newaccount-for-old-customer.html

<HTML>
<HEAD>
<H2 ALIGN="center" > New Account Creation</H2>
</HEAD>

<BODY bgcolor="LightCyan">
<FORM NAME="newaccount" ACTION="" METHOD="post">
<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> Customer Number :</TD><TD><INPUT TYPE="text"
name="cust_no"></TD></TR>
<TR><TD>New Account Type:</TD><TD>
<SELECT NAME="acc_type">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="SB">SB</OPTION>
<OPTION VALUE="Current">Current</OPTION>

</SELECT>

<TR><TD align="right"> <INPUT TYPE="submit" name="submit"


value="Create"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>
…………………………………………………………………………………………………………………………
Delete-account.html
<HTML>
<HEAD>
<H2 ALIGN="center" > Account Deletion</H2>
</HEAD>
<BODY bgcolor="blue">
<FORM NAME="Registration " ACTION="Register.jsp" METHOD="post">
<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> Eneter Account Number :</TD><TD><INPUT TYPE="text" name="exist-
acct-no"/></TD></TR>
</TABLE>
<br><br/>
<center>
<INPUT TYPE="submit" name="delete" value="delete">
</center>
</FORM>
</BODY>
</HTML>

46
Case Study: Bank Application

The examples given in the subsequent slides/pages illustrate the forms


required in a Banking Application.

Creating forms required for Staff login is explained in detail.

Version 2.0 47

Staff.html
<Frameset cols="40%,*">
<frame src ="staffhome.html" name="left">
<frame src = "search-cust-Acc.html" name="right">
</frameset>
………………………………………………………………………………………………………………………
This form will be the home screen for Staff Login

Staffhome.html
<form name="staff" action="" method=post>
<center>
<body bgcolor="LightCyan"><h1> STAFF</h1><br>
<br><b> You have logged in As :1002</b>
<br>
<em>You are authorised to access Valued Customer Account</em><br>
<br><input type ="submit" name="logout" value="LogOut">
</center>
</form>
………………………………………………………………………………………………………………………
search-cust-Acc.html(to search customer Account)

<form name="searchcustAcc" action="" method="post">


<body bgcolor="LightSeaGreen">
<table align="center" >
<Tr><td >Customer Account Number </td> <td><input type="text"
name="AccountNumber" value=""></td>
<td><input type="submit" name="searchId" value="Confirm“ ></td></tr>
</table>
</form>
………………………………………………………………………………………………………………………

47
forms Related to deposit and withdraw Transaction

Transaction.html
<Frameset Rows="70%,*">
<frame src ="Transation-select.html" name="upper">
<frame src = "transcationsecondform.html" name="lower">
</frameset>
………………………………………………………………………………………………………………………

Transation-select.html

<CENTER>Customer name: </CENTER>


<body bgcolor ="red"></body>
<form name="login" action="" method="">
<table BORDER="" WIDTH="50%" CELLSPACING="2" CELLPADDING="2"
align="center">
<th><tr><td bgcolor="blue" > Account Number </td>
<td bgcolor="blue"> Account Type </td>
<td bgcolor="blue">Amount Balance </td><td bgcolor="blue">Mini
Statement</td></tr></th>
<br>
<tr><td bgcolor="white">56741234 </td> <td bgcolor="white">Saving </td> <td
bgcolor="white"> 200000 </td><td bgcolor="white"> <a
href=""><b>View</b></a></td></tr>
<br>
</table>

<br>
<br>
<br>
<CENTER>
<b>Transaction Type</b><br>
<input type="button" name="deposit" value="Deposit" '">
<input type="button" name="Withdrawal" value="Withdrawal" >
<br>
<br>
<input type="button" name="previous" value="Back">
</CENTER>
</form>
………………………………………………………………………………………………………………………

transcationsecondform.html

<body bgcolor="Blue">Amount Screen </body>

………………………………………………………………………………………………………………………
Amount-entry.html(Deposit or withdraw form)
<form name="depositamt" >
<table name="depositscreen" ALIGN="Center" CELLSPACING="2"
CELLPADDING="2">
<body bgcolor="Blue">
<tr><td>Enter Amount</td><td> <input type="text" name="amount" value="0">
</td></tr>
<tr><td> <input type="submit" ALIGN="Center" value="submit"> </td></tr>
</table>
</form>

48
Case Study: Bank Application

The examples given in the subsequent slides/pages illustrate the forms


required in a Banking Application.

Creating forms required for Customer login is explained in detail.

Version 2.0 49

Customerscreen.html
<Frameset cols="40%,*">
<frame src ="customerhome.html" name="left">
<frame src = "customer-account-view.html" name="right">
</frameset>
…………………………………………………………………………………………………………………..
Cusomer HomeScreen
Customerhome.html
<form name="staff" action="" method=post>
<center>
<body bgcolor="SeaGreen"><b> Customer Home</b><br>
</center>

<table>
<tr><td><input type ="radio" name="f" value="accountstatus" ><b>Account
Status <b></td></tr>
<TR><TD><h2><em>Funds Transfer:<em></h2></TD><TD></tr>
<tr><td><input type ="radio" name="f" value="ownaccounts""> <b>Between Own
Accounts</b></td></tr>
<tr><td><input type ="radio" name="f" value="Third Party" "><b>Third
Party</b></td></tr>
<br><em><p>You are authorised to View The Account Status of All accounts along
with Fund Transfer within the Bank</em></p><br>
<br>
<br>
<center>
<tr><td><input type ="submit" name="logout" value="LogOut"></td></tr>
</center>
</table>
</form>
…………………………………………………………………………………………………………………..

49
customer-account-view.html
<b> Customer name</b> : Bhojaraja N S<br>
<b>Login date-time</b> : <br>
<b>Last Login</b> : <br>

<body bgcolor ="green"></body>

<form name="customer_status" action="" method="">

<table WIDTH="50%" CELLSPACING="2" CELLPADDING="2">


<th><tr><td bgcolor="blue" > <b>Account Number</b> </td>
<td bgcolor="blue"><b> Account Type</b></td>
<td bgcolor="blue"><b>Amount Balance</b> </td>
<td bgcolor="blue"><b>Mini Statement</b></td></tr></th>
<br>
<!-- Below values are static and this is just for reference -->

<tr><td bgcolor="white">56741234 </td> <td bgcolor="white">Saving </td> <td


bgcolor="white"> 200000 </td><td bgcolor="white"><a
href=""><b>View</b></a></td></tr>
<tr><td bgcolor="white">56741235 </td> <td bgcolor="white">Current </td> <td
bgcolor="white"> 30000 </td><td bgcolor="white"><a
href=""><b>View</b></a></td></tr>
<br>
</table>

<br>
<br>
<br>
<input type="submit" name="logout" value="LogOut">
</form>

transaction-statement.html
<b> Customer name</b> : Bhojaraja N S<br>
<b>Login date-time</b> : <br>
<b>Last Login</b> : <br>

<body bgcolor ="green"></body>


<form name="login" action="" method="">
<table BORDER="" WIDTH="70%" CELLSPACING="2" CELLPADDING="2">
<th><tr><td bgcolor="blue" > <b>Date</b> </td>
<td bgcolor="blue"><b> Narration</b></td>
<td bgcolor="blue"><b>Withdrawal</b> </td>
<td bgcolor="blue"><b>Deposit</b></td>
<td bgcolor="blue"><b>ClosingBalance</b></td></tr></th>
<br>
<!-- below values are static -->
<tr><td bgcolor="white">01/03/2008 </td> <td bgcolor="white"> Salary
</td><td bgcolor="white">0</td><td bgcolor="white">50000</td><td
bgcolor="white">200000</td></tr>
<tr><td bgcolor="white">01/01/2008 </td> <td bgcolor="white"> </td><td
bgcolor="white">5000</td><td bgcolor="white">0</td ><td
bgcolor="white">150000</td></tr>
<br>
</table>
<br>
<br>
<br>
<input type="button" size="2" name="back" value="Back">
</form>

50
Summary

In this module you have learnt to:


§ Define a web architecture
§ Define HTML
§ Define and use different types of Tags
§ Create simple static web pages
§ Create and work on forms

Version 2.0 51

51
Module 2:
JavaScript

Copyright © 2008, Wipro Limited, Bangalore

52
Objectives

At the end of this module you will be able to:


1. Write JavaScript code using all the basic elements of JavaScript
Programs
2. Create Windows & Dialog Boxes
3. Use the JavaScript’s in-built objects in a web page
4. Write code that does Event Handling in HTML pages
5. Manipulate HTML Forms through JavaScript dynamically
6. Integrate Java and JavaScript through Applets

Version 2.0 53

53
DHTML

DHTML stands for Dynamic Hyper Text Markup Language which


helps to add Dynamic content to static HTML pages.

Version 2.0 54

Dynamic HTML, is a new web technology that enables elements inside


your web page to be, well, dynamic.
Things once considered unchangeable once the page has loaded, such as
text, page styles (font color, size etc), element position, etc., can now all
be changed dynamically.
It brings your web pages one step closer to how things look inside your
television, where images appear and disappear, text flies in and out, and
content moves around freely inside the screen.
DHTML is any combination of Style Sheets, JavaScript, and Layering.

54
Introduction to JavaScript

JavaScript is an easy to use object scripting language. It is designed for


creating live online applications. Code is included as part of a HTML
Document. Scripts are run by the Web browser.

Version 2.0 55

JavaScript is a scripting language that is object-based but not completely


object-oriented.
It helps in creation of very dynamic web applications.
Since it is an interpreted language, it can be directly embedded into
HTML documents and it is executed by the built-in interpreter in the
browsers.

55
Introduction to JavaScript: JavaScript Versus Java

JavaScript can be combined directly with HTML.

The JavaScript language structure is simpler than that of Java.

JavaScript is a purely interpreted language.

The JavaScript interpreter is built into a Web browser.

Version 2.0 56

The process of writing a Java applet can be complicated: writing the


source code, compiling, and making the applet available on the server.
JavaScript provides a much simpler alternative for small projects. The
JavaScript source code is interpreted directly by the browser. The source
can either be included directly within an HTML page or referenced in a
separate file.

Although JavaScript doesn't really have any features that eclipse Java, it
adds some conveniences, simplifies programming, and provides better
integration with the browser.

56
Introduction to JavaScript: Using the SCRIPT Tag

<HTML>
<HEAD>
<TITLE>Login Page </TITLE>
</HEAD>
<BODY>
HTML Text goes here.
<SCRIPT LANGUAGE="JavaScript">
document.write(“WelCome To green Bank")
</SCRIPT>
</BODY>
</HTML>

Version 2.0 57

The <SCRIPT> tag is an extension to HTML that can enclose any number
of JavaScript statements as shown here:
<SCRIPT>
JavaScript statements...
</SCRIPT>
A document can have multiple <SCRIPT> tags, and each can enclose any
number of JavaScript statements.
Unlike HTML, JavaScript is case sensitive.

57
Elements of JavaScript Program

Elements of JavaScript Program can be divided into five categories, as


follows:
1. Variables
2. Expressions
3. Control Structures
4. Functions
5. Objects and Arrays

Version 2.0 58

Variables are named containers that can store data.


Rules for variable names:
• Can include alphabets, digits and the underscore ( _ )
• The first character can be either an alphabet or the underscore
• Must be case-sensitive
There is no official limit on the length of variable names, but they must fit
within one line.
Expressions are a combination of variables, constants and operators
that can be evaluated to a single value.
Control Structures are structures of Java script code used to control
the flow of execution based on the evaluation of certain conditional
expressions.
Function is a group of JavaScript statements that can be referred to,
using a function name and arguments.
Object is a type of variable that can store multiple values, called
properties and functions called methods.
Array is a set of variables that can be referred to with the same name
and a number, called an index.

58
Elements of JavaScript Program: Variables

§ Data Types

§ Rules for variable names

§ Type Casting

§ Variable Declaration and Scope

Version 2.0 59

Data Types and Variables


You can use data in two ways:
• As a literal or constant value
• As a variable
The four fundamental data types used:
• Numbers
• Boolean, or logical values
• Strings
• The null value/ the object

Rules for variable names


• Variable names can include alphabets, digits and the underscore
(_)
• The first character can be either an alphabet or the underscore
• Are case-sensitive
• There is no official limit on the length of variable names, but they
must fit within one line.

59
JavaScript Statements

Conditional statements: if...else and switch

Loop Statements: for, while, do…while, break and continue

Object Manipulation Statements and Operators: for...in, new, this and


with

Comments: single-line (//) and multi-line (/*...*/)

Version 2.0 60

if...else Statement
Use the if statement to perform certain statements if a logical condition
is true; use the optional else clause to perform other statements if the
condition is false. An if statement looks as follows:

if (condition) {
statements1
}
else {
statements2
}

The condition can be any JavaScript expression that evaluates to true or


false. The statements to be executed can be any JavaScript statements,
including further nested if statements. If you want to use more than one
statement after an if or else statement, you must enclose the statements
in curly braces: {}.

60
JavaScript Statements: switch Statement

A switch statement allows a program to evaluate an expression and


attempt to match the expression's value to a case label. If a match is
found, the program executes the associated statement. A ‘switch’
statement looks as follows:

switch (expression){
case label :
statement;
break;
default : statement;
}

Version 2.0 61

The program first looks for a label matching the value of expression and
then executes the associated statement. If no matching label is found, the
program looks for the optional default statement, and if found, executes
the associated statement. If no default statement is found, the program
continues execution at the statement following the end of switch.
The optional break statement associated with each case label ensures that
the program breaks out of switch once the matched statement is executed
and continues execution at the statement following switch. If break is
omitted, the program continues execution at the next statement within
the switch statement itself.
Simple Example to understand switch:
<script language="javascript">
var choice = 3, Login=" "
switch(choice)
{
case 1: login = "Manager"
break;
case 2: login = "Staff"
break;
default: login = "Customer";
}
document.write("you have Logged As "+login)
</script>

61
JavaScript Statements: for Statement

When a for loop executes, the following occurs:


Step 1: The initializing expression ‘initial-expression’, if any, is
executed. This expression usually initializes one or more loop counters,
but the syntax allows an expression of any degree of complexity.
Step 2: The ‘condition’ expression is evaluated. If the value of condition
is true, the loop statements execute. If the value of condition is false,
the for loop terminates.
Step 3: Assuming that the condition is true, the statements execute.
Step 4: Finally, the update expression ‘increment-expression’ executes
and control returns to step 2.
A for loop repeats until a specified condition evaluates to false. A ‘for’
statement looks as follows:
for ([initial-expression]; [condition]; [increment-expression]) {
statements
}

Version 2.0 62

Simple example to understand For Loop and if:

<SCRIPT language="javascript">
var loginstatus;
for(loginstatus=1;loginstatus<=3;loginstatus++)
{
if(loginstatus==1)
{
document.writeln(" Status=1 You can be Login As Manager");
}
if(loginstatus==2)
{
document.writeln(" Status=2 You can be Login As Staff");
}
if(loginstatus==3)
{
document.writeln(" status=3 You can be Login As
Customer");
}
}

</SCRIPT >

62
JavaScript Statements: do…while Statement

The do...while statement repeats until a specified condition evaluates to


false. A ‘do...while’ statement looks as follows:

do {
statement
} while (condition)

Version 2.0 63

Statement executes once before the condition is checked. If condition


returns true, the statement executes again. At the end of every execution,
the condition is checked. When the condition returns false, execution
stops and control passes to the statement following do...while.

Simple Example to understand do while:


var num = 123
var count = 0
do
{
count++;
num /= 10;
} while (num>1);
document.write(“total digits”+count);

63
JavaScript Statements: while Statement

A while statement executes its statements as long as a specified


condition evaluates to true. A ‘while’ statement looks as follows:

while (condition) {
statements
}

Version 2.0 64

If the condition becomes false, the statements within the loop stop
executing and control passes to the statement following the loop. The
condition test occurs before the statements in the loop are executed. If
the condition returns true, the statements are executed and the condition
is tested again. If the condition returns false, execution stops and control
is passed to the statement following while.

64
Functions

Functions are one of the fundamental building blocks in JavaScript. A


function is a JavaScript procedure: a set of statements that performs a
specific task. To use a function, you must first define it, then your script
can call it. A function definition looks as follows:

function gcd(m,n)
{
return n > 0 ? gcd(n,m%n) : m ;
}

Version 2.0 65

Defining Functions:
A function definition consists of the function keyword, followed by the
name of the function, a list of arguments to the function, enclosed in
parentheses and separated by commas. The JavaScript statements that
define the function are enclosed in curly braces: { }. The statements in a
function can include calls to other functions defined in the current
application. It is good practice to define all your functions in the HEAD of
a page so that when a user loads the page, the functions are loaded first.

<script language="javascript">
function interest(amt,per)
{
var m=(per/100)*amt;
return m;
}

var amount=50000;
var per=6;
totalbalance= amount+interest(amount,per) ;
document.write(totalbalance);
</script>

65
Objects

An object is a self-contained unit of code having the following


characteristics:
§ Properties
§ Methods
§ Identity

Version 2.0 66

Like variables, objects can store data - but they can store more pieces of
data at once.

The items of data stored in an object are called the Properties of the
object.
E.g: A person object might include Bob.address and Bob.phone, where
Bob is the object and address & phone are its properties.

Objects have methods or functions which work with the object’s data.
E.g: A person object might include a display() method to display the
person’s information.

66
Objects: The Window Object

At the top of the browser hierarchy is the window object, which


represents a browser window

The properties/methods of this object are:


status
alert()
confirm()
prompt()

Version 2.0 67

The window.status is a property which can be used to change the contents


of the browser’s status line. The window.alert() method can be used to
alert the user in case of closing the window before saving the document.
It appears as a dialog box with a exclamatory sign.
The window.confirm() method can be used to prompt the user to ask for
clarification. It opens a dialog box with a question mark and two buttons
with ok and cancel as options. The window.prompt() method can be used
to prompt the user in case of accessing any data from the user, such as
user name and password. It opens a dialog box with a text box to accept
data from the user.
Simple Example:
<SCRIPT LANGUAGE="JavaScript">
function hello()
{
window.alert("You are about to view the Transaction Details ");
}
</SCRIPT>

<P> Click <A onClick = "hello();" HREF = "transaction-


statement.html">MiniStatement </A>

</P>

67
Objects: The Document Object

The Document Object represents characteristics of the current HTML


page. Some of its properties are:
– title - lastModified
– fgColor - bgColor

Some of its methods are:


– write()
– writeln()

In the browser object hierarchy, the document object is contained in a


window object (for a page without frames).

Version 2.0 68

The properties of the document object represent characteristics of the


current HTML page. Many of these are specified in the <BODY> tag of the
document while some are set by the browser when the document is
loaded.
The title property lists the title of the current page, defined by the HTML
<TITLE> tag.
The last modified property is the date the document was last modified.
Example:
<HEAD>
<TITLE> Test JavaScript </TITLE>
<SCRIPT Language="JavaScript">
document.write(document.title+" <BR>");
document.write(location.toString());
</SCRIPT>
</HEAD>

68
Objects: The Form Object

The Form object represents an HTML Form. It has the same name as
the NAME attribute in the FORM tag.

In the browser object hierarchy, the form object is contained in the


document object.

Version 2.0 69

For example, if the first form in a document has the name form1, you can
refer to it in one of two ways:
document.form1
document.forms[0]

69
Example to validate Amount Deposit form:

<script language="javascript">
function checkamount()
{
var x = parseInt(document.depositamt.amount.value);

/*another way to acces form element


var x = parseInt(document.forms[0].elements[1].value);
*/

if(x<=0)
alert("Please Emter The amount more than Zero");
return true;
}

</script>
<form name="depositamt" >
<table name="depositscreen" ALIGN="Center" CELLSPACING="2"
CELLPADDING="2">
<body bgcolor="Blue">

<tr><td>Enter Amount</td><td> <input type="text" name="amount"


value="0"> </td></tr>
<tr><td> <input type="submit" onClick="checkamount();"
ALIGN="Center" value="submit"> </td></tr>
</table>
</form>

70
Objects: Frame Objects

Each Frame in a frame set is represented as a frame object.

A frame set contains an array of frame objects representing all the


frames in it.

You can refer to a particular frame:


§ By name - if it has one
§ By reference to the parent and the array index of that frame

Version 2.0 71

JavaScript allows you to manipulate frames and contents of frames by


providing objects that represent the frames in the current frameset.

The frames are either available as objects with the same name as the
frame name or as an array of frames.

To access one frame from another frame in the same frameset, you need
to use the ‘parent’ frame as a reference through which the other frames
can be accessed. If there are multiple levels of nested frames, the ‘top’
frame can be used as the reference to access other frames.

71
Objects: The Math Object

The Math object can’t be created, since it exists automatically in all


Java Script Programs.

Its properties represent mathematical constants.

Its methods are mathematical functions.

Version 2.0 72

Three of the most useful methods of the Math object enable you to round
decimal values up and down:
Math.ceil() rounds a number up to the next integer.
Math.floor() rounds a number down to the next integer.
Math.round() rounds a number to the nearest integer.

All these take a single parameter: the number to be rounded. You might
notice one thing missing: the ability to round to a decimal place, such as
for dollar amounts. You can easily simulate this, though.

72
Simple Example:

<script language="javascript">
function checkamount()
{
var x = document.depositamt.amount.value;
var y=Math.round(x)

document.writeln(y);
}

</script>
<form name="depositamt" >
<table name="depositscreen" ALIGN="Center" CELLSPACING="2"
CELLPADDING="2">
<body bgcolor="Blue">

<tr><td>Enter Amount</td><td> <input type="text" name="amount"


value="0"> </td></tr>
<tr><td> <input type="submit" onClick="checkamount();"
ALIGN="Center" value="submit"> </td></tr>
</table>
</form>

73
Objects: The String Object

Any String variable in JavaScript is a String object. String object have a


single property, length.
Concatenating strings (+)
indexOf
lastIndexOf
charAt
length
split
substring
substr
toLowerCase and toUpperCase

Version 2.0 74

You can perform string functions using a variety of methods.


Methods enable you to convert strings, work with pieces of strings,
search for values, control the string's appearance on the HTML page, and
control HTML links and anchors.
String Conversions methods:
toUpperCase() converts all characters in the string to uppercase.
toLowerCase() converts all characters in the string to lowercase.
Examples:
<script language=“javascript”>

document.write(“Wipro” + “EC4”); //Concatenation


var b = 'I am a JavaScript hacker.'
document.write(b.lastIndexOf('a'))
document.write(b.lastIndexOf(‘w'))
document.write(a.substring(4,8)); // extract characters from 4 to 8 location
document.write(a.substr(4,8)); // extract 8 characters from 4 location
</script>

74
Objects: The Date Object

The Date object is a built-in JavaScript object that enables you to


conveniently work with dates and times.
You can create a Date object any time you need to store a date, and use
the Date object's methods to work with the date.
You can create a Date object using the new keyword.
You can use any of the following formats:

birthday = new Date();


birthday = new Date("June 20, 1996 08:00:00");
birthday = new Date(6, 20, 96);
birthday = new Date(6, 20, 96, 8, 0, 0);

Version 2.0 75

Setting Date Values


A variety of set methods enable you to set components of a Date object to
values:
setDate() sets the day of the month.
setMonth() sets the month. JavaScript numbers the months from 0 to 11,
starting with January as 0.
setYear() sets the year.

Getting Date Values


You can use the get methods to get values from a Date object. This is the
only way to obtain these values, because they are not available as
properties:
getDate() gets the day of the month.
getMonth() gets the month.
getYear() gets the year.
getHours(), getMinutes() and getSeconds() get the time.

75
Defining Objects

The object definition is a simple function that accepts parameters to


initialize a new object and assigns those to the corresponding
properties.

Version 2.0 76

function display()
{
document.write("Name : "+ this.name + "< BR>")
document.write("Address : "+ this.address + "< BR>")
}
function Customer(name,address)
{
this.name = name
this.address = address
this.display = display
}

// creating instances
Ravi = new Customer("Ravi","Bangalore");
Mahesh = new Customer("Mahesh","Madras");
// print them
Ravi.display()
Mahesh.display()

76
Some Important Keywords

The this Keyword


It is simply a shorthand for "the current object." This is usually used in
object definitions, where it refers to the object being defined, and in
method definitions, where it refers to the object the method is acting
on. It can also be used in event handlers.

The with Keyword


You can use it to make JavaScript programming easier-or at least easier
to type. The with keyword specifies an object, and it is followed by a set
of statements enclosed in braces. For each statement in the set, any
properties you mention without specifying an object are assumed to be
for that object.

Version 2.0 77

<script language="javascript">
function display()
{
document.write("Name : "+ this.name + "<BR>")
document.write("CustomerID : "+ this.customerID + "<BR>")
document.write("AccountNumber : "+ this.AccountNo + "<BR>")
}
function Customer(custid,Accno,name)
{
this.customerID=custid
this.AccountNo =Accno
this.name=name
this.display = display
}
// creating instances
Bhoj = new Customer("1000","1","Bhoj");
Vasanth = new Customer("1002","5","Vasanth");
//Bhoj.display();
// print
with(Bhoj)
{
display()
}
with(Vasanth)
{
display()
}
</script>

77
Defining Objects: Looping through Object’s Properties

The final statement used for object-oriented work in JavaScript is the


for...in loop.

This loop executes once for each property of an object, assigning the
index variable to the property name.

Version 2.0 78

For example, you could make a simple function to list the properties of an
object and their values.

function list(object) {
for (var i in object) {
document.write("Property: ",i," Value: ",object[i], "<BR>");
}
}

This function uses the variable i to iterate through the object's properties
and uses the document.write() function to display the property name and
the value.

78
Arrays

JavaScript doesn’t support array variables.

Arrays need to be created using array object.

Version 2.0 79

Once you define the array, you can access its elements by using brackets
to indicate the index . As an example, this statement creates an array
called scores with 20 values:
Scores = new Array(20);
Array object methods:
join() quickly joins all the array's elements, resulting in a string. The
elements are separated by commas by default.
reverse() returns a reversed version of the array: the last element becomes
the first, and the first element becomes the last.
sort() returns a sorted version of the array.
Simple Example
<script language="javascript">
var Name=new Array(2);
Name[0]="Raghu";
Name[1]="Kiran"
var s=new Array("Saab","Volvo","BMW");
for( var i=0;i<s.length;i++)
document.writeln(s[i]);
for( var k=0;k<Name.length;k++)
document.writeln(Name[k]);
</script>

79
Events

Events refer to things that happen to the browser and is used to trigger
portions of program.

Events pertain to the web page containing the script.

Version 2.0 80

When the user clicks on a link, selects or enters text, or even moves the
mouse over part of the page, an event occurs.
You can use JavaScript to respond to these events. For example, you can
have custom messages displayed in the status line (or somewhere else on
the page) as the user moves the mouse over links. You can also update
fields in a form whenever another field changes.
onBlur Occurs when an object on the page loses focus
onChange Occurs when a text field is changed by the user
onClick Occurs when the user clicks on an item
onFocus Occurs when an item gains focus
onLoad Occurs when the page (or an image) finishes loading
onMouseOver Occurs when the mouse pointer moves over an item
onMouseOut Occurs when the mouse pointer moves off an item
onSelect Occurs when the user selects text in a text area
onSubmit Occurs when a submit button is pressed
onUnload Occurs when the user leaves the document or exits

80
Events: Event Handlers

Embedded in html tags, typically as part of forms, but are also included
as a part of some anchors and links.

Virtually anything a user can do to interact with a page is covered with


the event handlers, from moving the mouse to leaving the current page.

Version 2.0 81

81
Example to Validate Login Page

login.html

<SCRIPT language="javascript">
function IsEmpty()
{
var x = document.login.username.value;
if(x.length==0)
{
alert("Please Enter User Name\n");
return false;
}
if(isNaN(x))
{
alert("UserName Should Be numeric\n");
document.login.username.value="";
document.login.password.value="";
return false;

if(document.login.password.value==0)
{
alert("Please Enter Password\n");
return false;
}
else
return true;
}
</script>

<form name="login" action="loginsubmit.jsp" method="post">


<body bgcolor="blue" >
<table align="center" width="20%" >
<tr> <td>User Id</td><td> <input type="text" name="username"
value=""></td></tr>
<tr><td>Password</td><td> <input type="password" name="password"
value=""></td></tr>
<tr><td><input type="submit" name="submit" align="center"
onClick="return IsEmpty();" value="Login" ></td></tr>
</table>
</form>

82
Time Outs

Time outs refer to Statements that will be executed after a certain


amount of time elapses.

Handy for periodically updating a Web Page or for delaying the display
of a message or execution of a function.

Version 2.0 83

You begin a timeout with the setTimeout() Method.


Before a timeout has elapsed, you can stop it with the clearTimeout()
method, specifying the identifier of the timeout to stop.
// Update a page every 2 seconds
var counter = 0;
// call Update function in 2 seconds after first load
ID=window.setTimeout("Update();",2000);
function Update(){
counter++;
window.status="The counter is now at "+counter;
document.form1.input1.value="The counter is now at "+counter;
//set another timeout for the next count
ID=window.setTimeout("Update();",2000);}
<FORM NAME="form1">
<INPUT TYPE="text" NAME="input1" SIZE="40"><BR><INPUT
TYPE="button" VALUE="RESET" onClick="counter=0;"><BR>
<INPUT TYPE="button" VALUE="STOP"
onClick="window.clearTimeout(ID);">
</FORM>

83
Integrating JavaScript with Java

Each Java applet you embed in a Web page is made available to


JavaScript as an applet object, with the same name as the applet's class
name.

The applet object resides in the object hierarchy under the document
Object. For example, a Java applet called Scroll would be accessed
through an object called document.Scroll

The objects, properties, and methods of the applet are then available to
JavaScript, provided the Java programmer has made them public.

Version 2.0 84

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Font;
public class ControlJava extends Applet {
Font f = new Font("TimesRoman", Font.BOLD, 60);
String Message;
public void init() {
Message = new String("Java Test");
}
public void SetMessage(String MsgText) {
Message = MsgText;
repaint();
}
public void paint(Graphics g) {
g.setFont(f);
g.drawString(Message, 15, 50);
}
}

84
<HTML>
<HEAD>
<TITLE>Control a Java Applet</TITLE>
</HEAD>
<BODY>
<H1>Control a Java Applet</H1>
<HR>

The Java applet below displays text in a large font. You can enter new text
to display in the form below, and JavaScript will call the Java applet to
change the text.
<HR>
<FORM NAME="form1">
<INPUT TYPE="TEXT" NAME="text1">
<INPUT TYPE="BUTTON" VALUE="Change Text"
onClick="document.ControlJava.SetMessage(document.form1.text1.value);">
</FORM>
<HR>
<APPLET NAME="ControlJava“ CODE="ControlJava.class" WIDTH=450
HEIGHT=125>
</APPLET>
<HR>
End of page.
</BODY>
</HTML>

85
Creating Windows

Opening new browser windows is a great feature of JavaScript.

You can either load a new document (for example a HTML-document)


to the new window or you can create new documents (on-the-fly).

Version 2.0 86

Here is a list of the properties a window can have:

directories yes|no
height number of pixels
location yes|no
menubar yes|no
resizable yes|no
scrollbars yes|no
status yes|no
toolbar yes|no
width number of pixels

86
Example to create New Window

<html>
<head>
<script language="JavaScript">
<!-- hide
function openWin3() {
myWin= open("", "displayWindow",
"width=500,height=400,status=yes,toolbar=yes,menubar=yes");
// open document for further output
myWin.document.open();
// create document
myWin.document.write("<html><head><title>On-the-fly");
myWin.document.write("</title></head><body>");
myWin.document.write("<center><font size=+3>");
myWin.document.write("This HTML-document has been created ");
myWin.document.write("with the help of JavaScript!");
myWin.document.write("</font></center>");
myWin.document.write("</body></html>");

// close the document - (not the window!)


myWin.document.close();
}
// -->
</script>
</head>
<body>
<form>
<input type=button value="On-the-fly" onClick="openWin3()">
</form>
</body>
</html>

87
Case Study: Bank Application

The examples given in the subsequent slides/pages illustrate how to


Validate the Html forms used in a Banking Application.

Validating Login Page used in Banking Application is explained in


detail.

Version 2.0 88

88
<SCRIPT language="javascript">
function IsEmpty()
{
var x = document.login.username.value;
if(x.length==0)
{
alert("Please Enter User Name\n");
return false;
}
if(isNaN(x))
{
alert("UserName Should Be numeric\n");
document.login.username.value="";
document.login.password.value="";
return false;
}
if(document.login.password.value==0)
{
alert("Please Enter Password\n");
return false;
}
else
return true;
}

</script>

<form name="login" action="loginsubmit.jsp" method="post">


<body bgcolor="blue" >
<table align="center" width="20%" >
<tr> <td>User Id</td><td> <input type="text" name="username"
value=""></td></tr>
<tr><td>Password</td><td> <input type="password" name="password"
value=""></td></tr>
<tr><td><input type="submit" name="submit" align="center"
onClick="return IsEmpty();" value="Login" ></td></tr>
</table>
</form>

89
Case Study: Bank Application

Validating Forms Related to Manager Login in Banking Application is


explained in detail.

Version 2.0 90

Validating The Manager’s Home screen


managerform.html
<h1 align="center"> Manager</h1>
<body bgcolor="blue">
<form name="manager" >
<center>
<input type="button" name="newcustomer" value="Create new Customer"
onClick=
"parent.right.location.href='newcustomerregistration.html'"><br><br>
<input type="button" name="newaccount " value="Create new Account"
onClick= "parent.right.location.href='newaccount-for-old-
customer.html'"><br><br>
<input type="button" name="remove" value="Remove Customer"
onClick= "parent.right.location.href='delete-account.html'" >
</center>
</form>
………………………………………………………………………………………………………

90
Validating the new customer registration form
newcustomerregistration.html

<SCRIPT language="javascript">
function checkAcctypeselection()
{
if(document.Registration.acc_type.value=="Select")
{
alert("Please Select Account Type");
document.Registration.user_password.value="";
return false;
}
}
function pinCheck()
{
if(document.Registration.pin.value.length != 6)
{
alert("Pin code should be of Six Digit")
return lsefa;
}
}
function IsEmpty()
{
if(document.Registration.cust_first_name.value.length==0)
{
alert("Please Enter First Name\n");
return false;
}

if(document.Registration.cust_last_name.value.length==0)
{
alert("Please Enter Last Name\n");
return false;
}

if(document.Registration.user_password.value.length==0)
{
alert("Please Enter password \n");
return false;
}
var pass=document.Registration.user_password.value;
if(document.Registration.confirm_password.value!=pass)
{
alert("Confirmed password is not matching \n");
return false;
}
if(document.Registration.city.value.length==0)

{
alert("Please Enter City Name\n");
return false;
}

if(document.Registration.pin.value.length==0)

91
{
alert("Please Enter Email\n");
return false;
}

return true;
}
</script>
<HTML>
<HEAD>
<H2 ALIGN="center" > Customer Registration</H2>
</HEAD>
<BODY bgcolor="blue">
<FORM NAME="Registration" ACTION="Register.jsp" METHOD="post" ;">
<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> First Name:</TD><TD><INPUT TYPE="text" name="cust_first_name"
></TD></TR>
<TR><TD> Last Name:</TD><TD><INPUT TYPE="text" name="cust_last_name"
></TD></TR>
<TR><TD>Account No:</TD><TD><INPUT TYPE="text" name="Acc_no" disabled="true"
value= "auto Generated" ></TD></TR>
<TR><TD>Account Type:</TD><TD>
<SELECT NAME="acc_type">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="SB">SB</OPTION>
<OPTION VALUE="Current">Current</OPTION>
</SELECT>
<TR><TD>Customer ID:</TD><TD><INPUT TYPE="text" name="cust_ID" disabled="true"
value= "auto Generated"></TD></TR>
<TR><TD>Password:</TD><TD><INPUT TYPE="password" name="user_password"
onChange="checkAcctypeselection();"/></TD></TR>
<TR><TD>Confirm Password:</TD><TD><INPUT TYPE="password"
name="confirm_password"/></TD></TR>
</TD></TR>
<TR><TD>Address:</TD><TD>
<TEXTAREA NAME="addressbox" ROWS="5" COLS="15" ALIGN="center"></TEXTAREA>
</TD></TR>
<TR><TD> City:</TD><TD><INPUT TYPE="text" name="city"/></TD></TR>
<TR><TD> pin:</TD><TD><INPUT TYPE="text" name="pin"
onChange="pinCheck();"/></TD></TR>
<TR><TD>Profession:</TD><TD>
<SELECT NAME="Profession">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="Studying">Student</OPTION>
<OPTION VALUE="Employed">Employee</OPTION>
<OPTION VALUE="Businessman">SelfEmployed</OPTION>
</SELECT>

92
<TR><TD>eMail:</TD><TD><INPUT TYPE="text" name="email"/></TD></TR>
<TR><TD>Gender:</TD><TD>
Male:&nbsp;<INPUT TYPE="Radio" NAME="R1" VALUE="Male"/>&nbsp;&nbsp;Female:&nbsp;
<INPUT TYPE="Radio" NAME="R1" VALUE="Female"/>
</TD></TR>
<TR ><TD size ="2">DOB:</TD><TD>Date
<SELECT NAME="dob">
<OPTION VALUE="Select">1</OPTION>
<OPTION VALUE="2">2</OPTION>
<OPTION VALUE="3">3</OPTION>
<OPTION VALUE="4">4</OPTION>
</SELECT>
<TD size ="2" >Month
<SELECT NAME="month">
<OPTION VALUE="Select">1</OPTION>
<OPTION VALUE="2">2</OPTION>
<OPTION VALUE="3">3</OPTION>
<OPTION VALUE="4">4</OPTION>
</SELECT>
<TD size ="2">year
<SELECT NAME="year">
<OPTION VALUE="2">1970</OPTION>
<OPTION VALUE="3">1971</OPTION>
<OPTION VALUE="Select">1973</OPTION>
<OPTION VALUE="4">1973</OPTION>
</SELECT>
<TR><TD align="right"> <INPUT TYPE="submit" name="submit" onClick="return IsEmpty();"
value="Confirm Details"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>
……………………………………………………………………………………………………………………………………………………………

93
Validation for disabling customer screen

delete-account.html

<script language="javascript">
function IsEmpty()
{
var x = document.deleteaccount.cust_no.value;

if(x.length==0)
{
alert("Please Enter Customer Number\n");
return false;
}

if(isNaN(x))

{
alert(" Customer ID Should be numeric");

return false;
}

return true;

}
</script>
<HTML>
<HEAD>
<H2 ALIGN="center" > Customer Deletion</H2>
</HEAD>
<BODY bgcolor="LightCyan">
<FORM NAME="deleteaccount" ACTION="removecustomer-submit.jsp" METHOD="post">
<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> Enter Customer ID :</TD><TD><INPUT TYPE="text"
name="cust_no"/></TD></TR>
</TABLE>
<br><br/>
<center>
<INPUT TYPE="submit" name="delete" onClick="return IsEmpty();" value="delete">
</center>
</FORM>
</BODY>
</HTML>

……………………………………………………………………………………………………………………………………………………………

94
Case Study: Bank Application

Validating Forms Related to Staff Login in Banking Application is


explained in detail.

Version 2.0 95

Customer Id SEARCH Form Validation


search-cust-Acc.html
<script language="javascript">
function IsEmpty()
{
if(document.searchcustAcc.AccountNumber.value.length==0)
{
alert("Please Enter Customer Account Number\n");
return false;
}
if(isNaN(document.searchcustAcc.AccountNumber.value))
{
alert(" Account No should be a Number \n");
return false;
}
else
parent.right.location.href="Transaction.html";
return true;
}
</script>
<form name="searchcustAcc" action="" method="">
<body bgcolor="blue">
<table align="center" >
<Tr><td >Customer Account Number </td> <td><input type="text" name="AccountNumber"
value=""></td>
<td><input type="submit" name="searchId" value=">>>" onClick="IsEmpty();"></td></tr>
</table>
</form>

…………………………………………………………………………………………………………………………………………………..

95
Transaction-select.html
<CENTER>Customer name: </CENTER>
<body bgcolor ="red"></body>
<form name="login" action="" method="">
<table BORDER="" WIDTH="50%" CELLSPACING="2" CELLPADDING="2" align="center">
<th><tr><td bgcolor="blue" > Account Number </td>
<td bgcolor="blue"> Account Type </td>
<td bgcolor="blue">Amount Balance </td><td bgcolor="blue">Mini
Statement</td></tr></th>
<br>
<tr><td bgcolor="white">56741234 </td> <td bgcolor="white">Saving </td> <td
bgcolor="white"> 200000 </td><td bgcolor="white"> <a
href=""><b>View</b></a></td></tr>
<br>
</table>
<br>
<br>
<br>
<CENTER>
<b>Transaction Type</b><br>
<input type="button" name="deposit" value="Deposit"
onClick="parent.lower.location.href='amount-entry.html'">
<input type="button" name="Withdrawal" value="Withdrawal"
onClick="parent.lower.location.href='amount-entry.html'">
<br>
<br>
</CENTER>
</form>
………………………………………………………………………………………………………….
Deposit Amount Screen Validation
Deposit-amount.html

<SCRIPT language="javascript">
function IsEmpty()
{

if(document.depositentry.amount.value.length==0)

{
alert("Please Enter the amount");
return false;
}

if(isNaN(document.depositentry.amount.value))

{
alert(" amount Should be numeric");
document.depositentry.amount.value="";
return false;
}

alert("you Are Depositing The Money ! Are You sure");

return true;
}

</script>

96
<form name="depositentry" action="deposit-submit.jsp" method="post" >
<table name="depositscreen" ALIGN="Center" CELLSPACING="2" CELLPADDING="2">
<body bgcolor="Cyan3">
<tr><td>Enter Description</td><td> <input type="text" name="description" > </td></tr>
<tr><td>Enter Amount</td><td> <input type="text" name="amount" > </td></tr>
<tr><td><input type="submit" ALIGN="Center" value="submit" onClick="return
IsEmpty();"></td></tr>
</table>
</form>

………………………………………………………………………………………………………………………………..
Validation for withdrawal form
<SCRIPT language="javascript">
function IsEmpty()
{
if(document.amountentry.amount.value.length==0)

{
alert("Please Enter the amount");
return false;
}

if(isNaN(document.amountentry.amount.value))

{
alert(" amount Should be numeric");

return false;
}
else

return true;

</script>
<form name="amountentry" action="withdrawal-submit.jsp" method="post" >
<table name="withdrawal" ALIGN="Center" CELLSPACING="2" CELLPADDING="2">
<body bgcolor="Cyan3">
<tr><td>Enter Description</td><td> <input type="text" name="description" > </td></tr>
<tr><td>Enter Amount</td><td> <input type="text" name="amount" > </td></tr>
<tr><td><input type="submit" ALIGN="Center" value="submit" onClick="return
IsEmpty();"></td></tr>

</table>
</form>
………………………………………………………………………………………………………………..

97
Case Study: Bank Application

Validating Forms Related to Customer Login in Banking Application is


explained in detail.

Version 2.0 98

Validating Customer Home Screen


Customerhome.html

<form name="staff" action="logout.jsp" method=post>


<center>
<body bgcolor="SeaGreen"><b> Customer Home</b><br>
</center>

<tr><td><input type ="radio" name="f" value="accountstatus"


onClick="parent.right.location.href='customer-account-view.jsp'"><b>Account Status
<b></td></tr>

<TR><TD><h2><em>Funds Transfer:<em></h2></TD><TD></tr>
<tr><td><input type ="radio" name="f" value="ownaccounts"
onClick="parent.right.location.href='select-own-accounts.jsp?acno=own'"> <b>Between Own
Accounts</b></td></tr>

<tr><td><input type ="radio" name="f" value="Third Party"


onClick="parent.right.location.href='select-thirdparty-accounts.jsp'"><b>Third
Party</b></td></tr>

<br><em><p>You are authorised to View The Account Status of All accounts along with Fund
Transfer within the Bank</em></p><br>
<br>
<br>
<center>
<tr><td><input type ="submit" name="logout" value="LogOut"></td></tr>
</center>
</table>

</form>

98
Validation for the fundtransfer related form
select-own-accounts.html and
select-thirdparty-accounts.html

<script language="javascript">
function IsEmpty()
{
if(document.fundtransfer.from.value==document.fundtransfer.to.value)
{
alert("Selected Account Numbers are Same");
return false;
}
if(document.fundtransfer.amount.value.length==0)
{
alert("Please Enter the amount");
return false;
}
if(isNaN(document.fundtransfer.amount.value))
{
alert(" Wrong Entry");
return false;
}
return true;
}
</script>
<form name="fundtransfer" action="fundtransfer-submit.jsp?type='own'"
method="">
<table>
<TR><TD><b>From Account: </b></TD><TD>
<tr><td><b> Amount</b></td><td><input type="text" name="from"
value=""></td></tr>
<tr><td><b> Amount</b></td><td><input type="text" name="to"
value=""></td></tr>
<tr><td><b> Amount</b></td><td><input type="text" name="amount"
value=""></td></tr>
<tr><td><input type="submit" name="submit" onClick="return IsEmpty();"
value="Accept"></td></tr>
</table>
</form>

………………………………………………………………………………………………

99
Summary

In this module you have learnt to:


§ Write JavaScript code using all the basic elements of JavaScript
Programs
§ Create Windows & Dialog Boxes
§ Use the JavaScript’s in-built objects in a web page
§ Write code that does Event Handling in HTML pages
§ Manipulate HTML Forms through JavaScript dynamically
§ Integrate Java and JavaScript through Applets

Version 2.0 100

100
Module 3:
JDBC

Copyright © 2008, Wipro Limited, Bangalore

101
Objectives

At the end of this module you will be able to:


§ Connect to a database using Java Database Connectivity (JDBC)
§ Create and execute a query using JDBC
§ Invoke prepared statements
§ Commit and roll back transactions
§ Use the Metadata objects to retrieve more information about the
database or the resultset

Version 2.0 102

102
Introduction to JDBC

JDBC is a standard interface for connecting to relational databases


from Java.

The JDBC classes and interfaces are in the java.sql package.

Version 2.0 103

About Java Database Connectivity (JDBC)

The java.sql package contains a set of interfaces that specify the JDBC
API. This package is part of Java 1.1.7 and Java 2. Database vendors
implement these interfaces in different ways, but the JDBC API itself is
standard.
Using JDBC, you can write code that:
•Connects to one or more database servers
•Executes any SQL statement
•Obtains a result set so that you can navigate through query
results
•Obtains metadata from the data server

103
Architecture & Querying with JDBC

Connect

Query

Process
results

Close

Version 2.0 104

The JDBC Architecture:


The JDBC API consists of two major sets of interfaces:
• The first is the JDBC API for applications writers, and
• The second is the lower-level JDBC driver API for driver writers.
As seen from the above diagram, the DriverManager class is the
traditional management layer of JDBC, working between the user and
the drivers. It keeps track of the drivers that are available and handles
establishing a connection between a database and the appropriate driver.
In addition, the DriverManager class attends to things like driver login
time limits and the printing of log and tracing messages.

104
Stage 1: Connect

Connect Register the driver

Query Connect to the database

Process
results

Close

Version 2.0 105

The first thing you need to do is establish a connection with the DBMS
(Database Management System) you want to use. This involves two
steps:
(1) loading the driver and
(2) making the connection.

Now, we shall first see as to what is a JDBC Driver.

105
Connect: A JDBC Driver

A JDBC driver is an interpreter that translates JDBC method calls to


vendor-specific database commands.

Database
JDBC calls commands
Driver
Database

JDBC driver Implements interfaces in java.sql. It can also provide a


vendor’s extensions to the JDBC standard.

Version 2.0 106

The JDBC API defines a set of interfaces that encapsulate major


database functionalities like:
•running queries
•processing results
•determining configuration information

A database vendor or third-party developer writes a JDBC driver, which


is a set of classes that implements these interfaces for a particular
database system.

An application can use a number of drivers interchangeably.


JDBC drivers are available for most database platforms, from a number
of vendors and in a number of different flavors.

There are four types of drivers, which will be covered in subsequent


topics.

106
JDBC – ODBC Bridge Driver (Type 1 Driver)

Type 1 drivers use a bridge technology to


connect a Java client to an ODBC database
system (e.g., The JDBC-ODBC Bridge from
Sun).

Type 1 drivers require some sort of non-Java


software to be installed on the machine
running your code, and are implemented
using native code.

Version 2.0 107

Characteristics of Type 1 drivers:


• Driver type is the JDBC-ODBC bridge
• Limited to running locally
• Must have ODBC installed on computer
• Must have ODBC driver for specific database installed on computer
• Generally can’t run inside an applet because of Native Method calls

When to use?
You can use JDBC-ODBC driver to access any of your existing ODBC
databases/databases that don't have JDBC drivers, (e.g., MS Access). It is
good if you already have a database system with ODBC support for quick
system prototyping.

The disadvantage is that you do not get a pure Java solution and have to
install the native ODBC binaries on every system you want to use. The
driver is provided by JavaSoft as part of the JDK in the sun.jdbc.odbc
package. Other vendors are not required to port this package. The bridge
is not meant for production environments.

107
Native JDBC Driver (Type 2 Driver)

Type 2 drivers use a native


code library to access a
database, wrapping a thin
layer of Java around the
native library. E.g., with
Oracle databases, the native
access might be through the
Oracle Call Interface (OCI)
libraries that were
originally designed for
C/C++ programmers.

Version 2.0 108

Type 2 drivers are implemented with native code, so they may perform
better than all-Java drivers, but they also add an element of risk, as a
defect in the native code can crash the Java Virtual Machine.

Characteristics of Type 2 drives:


• Classifies as a Native Database library driver
• Uses Native Database library on computer to access database
• Generally can’t run inside an applet because of Native Method calls
• Must have database library installed on client (e.g., DB-lib for Sybase,
Oracle, MS-SQL server

When to use?
This driver simply converts the JDBC calls into the native calls for a
database. Like for the JDBC-ODBC bridge you have to install the native
libraries on every system. Another disadvantage is, that you cannot use
this driver with non-verified/doubtful applets.
But this option is faster than the ODBC bridge, because you directly
interact with the database’s client libraries.

108
All Java JDBC Net Drivers (Type 3 Driver)

Type 3 drivers define a generic


network protocol that interfaces
with a piece of custom
middleware. The middleware
component might use any other
type of driver to provide the
actual database access (e.g., BEA's
WebLogic product line (erstwhile
known as WebLogic Tengah /
jdbcKona/T3). These drivers are
especially useful for applet
deployment, since the actual
JDBC classes can be written
entirely in Java and downloaded
by the client on the fly.

Version 2.0 109

Characteristics of Type 3 driver:


• 100% Java Driver, no native methods
• Does NOT require pre-installation on client
• Can be downloaded and configured ‘on-the-fly’ just like any Java class
file
• Uses a proprietary protocol for talking with a middleware server
• Middleware server converts from proprietary calls to DBMS specific
calls

When to use?
Type 3 driver adds security, caching, and connection control. As this does
not require any pre-installation, it can be used in web applications. Here
the JDBC calls are converted into a network protocol and transmitted to
a server which makes the actual database calls. This is the most flexible
solution, because the clients are written in pure Java and you can access
any database from the middle tier without changing the client. The JDBC
drivers are developed by some companies and may be quite costly.

109
Native Protocol All Java Drivers (Type 4 Driver)

Type 4 drivers are written


entirely in Java. They
understand database-
specific networking
protocols and can access
the database directly
without any additional
software. These drivers are
also well suited for applet
programming, provided
that the Java security
manager allows TCP/IP
connections to the
database server.
Version 2.0 110

Characteristics of Type 4 driver:


• 100% Java Driver, no native methods
• Does NOT require pre-installation on client
• Can be downloaded and configured ‘on-the-fly’ just like any Java class
file
• Unlike Type 4 driver, talks DIRECTLY with DBMS server
• Converts JDBC calls directly to database specific calls

When to use?
Type 4 drivers need no pre-installation and are hence, truly portable.

In this case the JDBC calls are directly converted into the network
protocol that is used by a specific database. This is the fastest alternative,
because there are no additional layers included and hence most preferred
in many of the J2EE or web-based applications.

110
Connect: About JDBC URL

JDBC uses a URL to identify the database connection.

jdbc:<subprotocol>:<subname>

Database
Protocol Subprotocol
identifier

jdbc:oracle:<driver>:@<database>

Version 2.0 111

A JDBC driver uses a JDBC URL to identify and connect to a particular


database. These URLs are generally of the form:
Jdbc:<subprotocol>:<subname> or jdbc:driver:databasename
The actual standard is quite fluid, however, as different databases require
different information to connect successfully. For example, the Oracle
JDBC-Thin driver uses a URL of the form:
jdbc:oracle:thin:@site:port:database
while the JDBC-ODBC Bridge uses:
jdbc:odbc:datasource:odbcoptions
The only requirement is that a driver be able to recognize its own URLs.

111
JDBC URLs: Examples

§ JDBC-ODBC driver

jdbc:odbc:jdbcoodbcDriverDsn

§ OCI driver

jdbc:oracle:oci8:@<TNSNAMES entry>

Version 2.0 112

In the above example of a JDBC URL for JDBC-ODBC driver, ‘jdbc’ is the
name of the protocol, ‘odbc’ is the name of the subprotocol and the
‘jdbcodbcDriverDsn’ is the ODBC DSN (Data Source Name) created on the
client machine. While creating the DSN, all the details about the ODBC
database to connect to, its name and its location are provided.
In the second example, we are using the OCI (Oracle Call Interface)
libraries that are already installed on the client machines from where the
JDBC calls are to be made. Hence the sub protocol is ‘oracle’. The rest of
the string gives details required by the Type 2 driver implementation for
the oracle database.

112
How to make the Connection?

1. Register the driver


Class c = Class.forName(
"oracle.jdbc.driver.OracleDriver");

Class c = Class.forName(
”sun.jdbc.odbc.JdbcOdbcDriver");

2. Connect to the database


Connection conn =
DriverManager.getConnection(URL,userid,password);

Connection conn = DriverManager.getConnection


("jdbc:oracle:thin:@myhost:1521:orcl",
"scott", "tiger");

Version 2.0 113

Loading the driver or drivers you want to use is very simple and involves
just one line of code. E.g., if you want to use the JDBC-ODBC Bridge
driver, the following code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give the class name to use. Class.forName
will automatically register the driver with the DriverManager. When you
have loaded a driver, it is available for making a connection with a
DBMS.
The java.sql.Connection object, which encapsulates a single connection
to a particular database, forms the basis of all JDBC data-handling code.
The DriverManager.getConnection( ) method creates a connection:
Connection con = DriverManager.getConnection("url", "user", "password");
You pass 3 arguments to getConnection( ): a JDBC URL, a database
username, and a password. For databases that don't require explicit
logins, the user and password strings should be left blank. When the
method is called, the DriverManager queries each registered driver,
asking if it understands the URL. If a driver recognizes the URL, it
returns a Connection object. Because the getConnection( ) method checks
each driver in turn, you should avoid loading more drivers than are
necessary for your application.

113
Stage 2: Query

Connect

Query Create a statement

Process Query the database


results

Close

Version 2.0 114

Once a connection is established, it is used to pass SQL statements to its


underlying database.
A Statement object is used to send SQL statements to a database. The
Statement interface provides basic methods for executing statements and
retrieving results.
The JDBC API does not put any restrictions on the kinds of SQL
statements that can be sent; this provides a great deal of flexibility,
allowing the use of database-specific statements or even non-SQL
statements. It requires, however, that the user be responsible for making
sure that the underlying database can process the SQL statements being
sent and suffer the consequences if it cannot. For example, an application
that tries to send a stored procedure call to a DBMS that does not support
stored procedures will be unsuccessful and will generate an exception.

114
Query: The Statement Object

A Statement object sends your SQL statement to the database.

You need an active connection to create a JDBC statement.

Statement has three methods to execute a SQL statement:


§ executeQuery() for QUERY statements
§ executeUpdate() for INSERT, UPDATE, DELETE, or DDL
statements
§ execute() for either type of statement

Version 2.0 115

Statement Objects in JDBC

The slide lists the three methods you can call to execute a SQL statement.
The following slides describe how to call each method. execute() is useful
for dynamically executing an unknown SQL string.

JDBC provides two other statement objects:


PreparedStatement, for precompiled SQL statements, is covered later.
CallableStatement, for statements that execute stored procedures, is also
covered later.

Objects and Interfaces


java.sql.Statement is an interface, not an object. When you declare a
Statement object and initialize it using the createStatement() method,
you are creating the implementation of the Statement interface supplied
by the Oracle driver or any other driver that you are using.

115
How to Query the Database?

1. Create an empty statement object

Statement stmt = conn.createStatement();

2. Execute the statement

ResultSet rset = stmt.executeQuery(statement);


int count = stmt.executeUpdate(statement);
boolean isquery = stmt.execute(statement);

Version 2.0 116

Once a connection to a particular database is established, that connection


can be used to send SQL statements. A Statement object is created with
the Connection method createStatement, as in the following code
fragment:
Statement stmt = conn.createStatement();
The SQL statement that will be sent to the database is supplied as the
argument to one of the execute methods on a Statement object.
This is demonstrated in the following example, which uses the method
executeQuery:

ResultSet rset = stmt.executeQuery("SELECT a, b, c FROM Table2");

The variable rset references a result set discussed in the following


sections.

116
Querying the Database: Examples

§ Execute a select statement

Statement stmt = conn.createStatement();


ResultSet rset = stmt.executeQuery
("select NAME, VERTICAL from STUDENT");

§ Execute a delete statement

Statement stmt = conn.createStatement();


int rowcount = stmt.executeUpdate
("delete from STUDENT
where ID = 1000");

Version 2.0 117

As mentioned earlier, the Statement interface provides three different


methods for executing SQL statements: executeQuery, executeUpdate,
and execute. The correct method to use is determined by what the SQL
statement produces.
The method executeQuery is designed for statements that produce a
single result set, such as SELECT statements.
The method executeUpdate is used to execute INSERT, UPDATE, or DELETE
statements and also SQL DDL (Data Definition Language) statements
like CREATE TABLE, DROP TABLE, and ALTER TABLE. The effect of an
INSERT, UPDATE, or DELETE statement is a modification of one or more
columns in zero or more rows in a table. The return value of
executeUpdate is an integer (referred to as the update count) that
indicates the number of rows that were affected. For statements such as
CREATE TABLE or DROP TABLE, which do not operate on rows, the return
value of executeUpdate is always zero.
The method execute is used to execute statements that return more than
one result set, more than one update count, or a combination of the two.

117
Stage 3: Process the Results

Connect

Query
Step through the results

Process Assign results to Java


results variables

Close

Version 2.0 118

Now that we have obtained the results of querying the database in the
ResultSet object, we need to iterate through this object and retrieve its
contents for further processing in the Java program.

118
Process the Results: The ResultSet Object

JDBC returns the results of a query in a ResultSet object.

A ResultSet maintains a cursor pointing to its current row of data.

Use next() to step through the result set row by row.

getString(), getInt(), and so on assign each value to a Java


Variable.

Version 2.0 119

A ResultSet is a Java object that contains the results of executing an SQL


query. In other words, it contains the rows that satisfy the conditions of
the query. The data stored in a ResultSet object is retrieved through a set
of get methods that allows access to the various columns of the current
row. The ResultSet.next method is used to move to the next row of the
ResultSet, making it the current row.
The general form of a result set is a table with column headings and the
corresponding values returned by a query. E.g., if your query is SELECT
a, b, c FROM Table1, your result set will have the following form:
a b c
---------- ------------ -----------
12345 Cupertino 2459723.495
83472 Redmond 1.0
83492 Boston 35069473.43

The ResultSet class has several methods that retrieve column values for
the current row. Each of these getXXX() methods attempts to convert the
column value to the specified Java type and returns a suitable Java value.
E.g., getInt() gets the column value as an int, getString() gets the column
value as a String, and getDate() returns the column value as a Date.

119
Banking Application : A Case Study

The tables used by the Bank Application are listed below:

BankUser – This table contains one row per user

Column Name Column Type Max Size

userid Number 16
password Varchar2 16
user_type Varchar2 1
status Varchar2 1

Version 2.0 120

120
Examples:

1. Creating a table using JDBC

import java.sql.*;

class MakeConnection1
{
Connection con;
Statement stmt;
int i;
MakeConnection1()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","tiger");
stmt = con.createStatement();
i = stmt.executeUpdate("create table BankUser(userid
number(16), password varchar2(16), user_type varchar2(1), status
varchar2(1))");
System.out.println(" User Table Created");
}
catch(Exception e)
{
System.out.println("Table Already
Exists\n\n"+e);
}
}
}

class CreateUserTable
{
public static void main(String args[])
{
new MakeConnection1();
}
}

-------------------------------------------------------------------------------------

121
2. Adding data to the table created above and displaying the
data on the console:

import java.sql.*;

class MakeConnection2
{
Connection con;
Statement stmt;
ResultSet rs;
int i;
MakeConnection2()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","tiger");
stmt = con.createStatement();
i=stmt.executeUpdate("insert into BankUser
values(1, 'admin100', 'A', 'A')");
i=stmt.executeUpdate("insert into BankUser
values(2, 'Wipro2', 'S', 'A')");
i=stmt.executeUpdate("insert into BankUser
values(3, 'Wipro3', 'S', 'A')");
i=stmt.executeUpdate("insert into BankUser
values(4, 'Wipro4', 'S', 'A')");
i=stmt.executeUpdate("insert into BankUser
values(11', 'User11', 'U', 'A')");
rs = stmt.executeQuery("Select * from BankUser");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3)+" "+rs.getString(4));
}
catch(Exception e)
{
System.out.println("Exception caught“+e);
}
}
}

class AddDisplayUser
{
public static void main(String args[])
{
new MakeConnection2();
}
}

122
How to Process the Result?

§ Step through the result set

while (rset.next()) { … }

§ Use getXXX() to get each column value

String val = String val =


rset.getString(colname); rset.getString(colIndex);

while (rset.next()) {
String name = rset.getString(“NAME");
String supervisor = rset.getString(“SUPERVISOR");
… // Process or display the data
}

Version 2.0 123

A ResultSet object maintains a cursor, which points to its current row of


data. The cursor moves down one row each time the method next is
called. When a ResultSet object is first created, the cursor is positioned
before the first row, so the first call to the next method puts the cursor
on the first row, making it the current row. ResultSet rows can be
retrieved in sequence from top to bottom as the cursor moves down one
row with each successive call to the method next.

When a cursor is positioned on a row in a ResultSet object (not before the


first row or after the last row), that row becomes the current row. This
means that any methods called while the cursor is positioned on that row
will operate on values in that row (methods such as getXXX).

A cursor remains valid until the ResultSet object or its parent Statement
object is closed.

123
How to Handle SQL Null Values?

Java primitive types cannot have null values.

Do not use a primitive type when your query might return a SQL null.

Use ResultSet.wasNull() to determine whether a column has a


null value.

while (rset.next()) {
String year = rset.getString("YEAR");
if (rset.wasNull() {
… // Handle null value}
…}

Version 2.0 124

To determine if a given result value is JDBC NULL, one must first read the
column and then use the method ResultSet.wasNull. This is true because a
JDBC NULL retrieved by one of the ResultSet.getXXX methods may be
converted to either null, 0, or false, depending on the type of the value.

Values returned by the various getXXX methods when they have retrieved
a JDBC NULL:

null - for those getXXX methods that return objects in the Java
programming language (getString, getBigDecimal, getBytes, getDate,
getTime, getTimestamp, getAsciiStream, getObject, getCharacterStream,
getUnicodeStream, getBinaryStream, getArray, getBlob, getClob, and
getRef)
0 (zero) - for getByte, getShort, getInt, getLong, getFloat, and getDouble
false - for getBoolean

124
E.g., if the method getInt returns 0 from a column that allows null
values, an application cannot know for sure whether the value in the
database was 0 or NULL until it calls the method wasNull, as shown in
the following code fragment, where rs is a ResultSet object.

int n = rs.getInt(3); boolean b = rs.wasNull();

If b is true, the value stored in the third column of the current row of rs is
JDBC NULL.

The method wasNull checks only the last value retrieved. So to determine
whether n was NULL, wasNull had to be called before another getXXX
method was invoked.

125
Stage 4: Close

Connect

Query
Close the result set

Process
results Close the statement

Close Close the connection

Version 2.0 126

Normally, nothing needs to be done to close a ResultSet object; it is


automatically closed by the Statement object that generated it when that
Statement object is closed, is re-executed, or is used to retrieve the next
result from a sequence of multiple results. The method close is provided
so that a ResultSet object can be closed explicitly, thereby immediately
releasing the resources held by the ResultSet object. This could be
necessary when several statements are being used and the automatic
close does not occur soon enough to prevent database resource conflicts.

126
How to Close the Connection?

1. Close the ResultSet object

rset.close();

2. Close the Statement object

stmt.close();

3. Close the connection (not necessary for server-side


driver)
conn.close();

Version 2.0 127

When a connection is in auto-commit mode, the statements being


executed within it are committed or rolled back when they are completed.
A statement is considered complete when it has been executed and all its
results have been returned. For the method executeQuery, which returns
one result set, the statement is completed when all the rows of the
ResultSet object have been retrieved. For the method executeUpdate, a
statement is completed when it is executed. In the rare cases where the
method execute is called, however, a statement is not complete until all of
the result sets or update counts it generated have been retrieved.
Statement objects will be closed automatically by the Java garbage
collector. Nevertheless, it is recommended as good programming practice
that they be closed explicitly when they are no longer needed. This frees
DBMS resources immediately and helps avoid potential memory
problems.
The same connection object can be used to execute multiple statements
and retrieve many result sets. However, once all the work with the
database is over, it is a good programming practice to close the
connection explicitly. If this is not closed, after a particular timeout
period defined at the database, the connection is automatically closed.
This would mean that till the timeout, this connection is not available to
any other users of the database. Hence, explicit closing of the connection
is recommended.

127
The DatabaseMetaData Object

The Connection object can be used to get a DatabaseMetaData


object.

This object provides more than 100 methods to obtain information


about the database.

Version 2.0 128

MetaData
Metadata is data about data. In JDBC, you use the
Connection.getMetaData()method to return a DatabaseMetaData object.
The DatabaseMetaData class contains more than 100 methods for
obtaining information about a database.
The following are some examples of DatabaseMetaData methods:
getColumnPrivileges(): Get a description of the access rights for a table's
columns.
getColumns(): Get a description of table columns.
getDatabaseProductName(): Get the name of this database product.
getDriverName() : Get the name of this JDBC driver.
storesLowerCaseIdentifiers(): Does the database store mixed-case SQL
identifiers in lower case?
supportsAlterTableWithAddColumn(): Is ALTER TABLE with add column
supported?
supportsFullOuterJoins(): Are full nested outer joins supported?

128
How to obtain Database Metadata?

1. Get the DatabaseMetaData object

DatabaseMetaData dbmd = conn.getMetaData();

2. Use the object’s methods to get the metadata

DatabaseMetaData dbmd = conn.getMetaData();


String s1 = dbmd getURL();
String s2 = dbmd.getSQLKeywords();
boolean b1 = dbmd.supportsTransactions();
boolean b2 = dbmd.supportsSelectForUpdate();

Version 2.0 129

This interface is implemented by driver vendors to let users know the


capabilities of a Database Management System (DBMS) in combination
with the driver based on JDBC technology ("JDBC driver") that is used
with it. Different relational DBMSs often support different features,
implement features in different ways, and use different data types. In
addition, a driver may implement a feature on top of what the DBMS
offers. Information returned by methods in this interface applies to the
capabilities of a particular driver and a particular DBMS working
together. A user for this interface is commonly a tool that needs to
discover how to deal with the underlying DBMS. This is especially true
for applications that are intended to be used with more than one DBMS.
For example:
getURL(): Returns the URL for the DBMS
getSQLKeywords(): Retrieves a comma-separated list of all of this
database's SQL keywords that are NOT also SQL92 keywords.
supportsTransactions(): Retrieves whether this database supports
transactions. If not, invoking the method commit is no use, and the
isolation level is TRANSACTION_NONE.
supportsSelectForUpdate(): Retrieves whether this database supports
SELECT FOR UPDATE statements.

129
The ResultSetMetaData Object

The ResultSet object can be used to get a ResultSetMetaData


Object.

ResultSetMetaData object provides metadata, including:


§ Number of columns in the result set
§ Column type
§ Column name

Version 2.0 130

ResultSetMetaData
In JDBC, you use the ResultSet.getMetaData() method to return a
ResultSetMetaData object, which describes the data coming back from a
database query. This object can be used to find out about the types and
properties of the columns in your ResultSet.

130
How to obtain ResultSetMetadata?

1. Get the ResultSetMetaData object

ResultSetMetaData rsmd = rset.getMetaData();

2. Use the object’s methods to get the metadata

ResultSetMetaData rsmd = rset.getMetaData();


for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String colname = rsmd.getColumnName(i);
int coltype = rsmd.getColumnType(i);

}

Version 2.0 131

Example
The example on the slide shows how to use a ResultSetMetaData object to
determine the following information about the ResultSet:
• The number of columns in the ResultSet
• The name of each column
• The American National Standards Institute (ANSI) SQL type for
each column

java.sql.Types
The java.sql.Types class defines constants that are used to identify ANSI
SQL types. ResultSetMetaData.getColumnType() returns an integer value
that corresponds to one of these constants.

131
Mapping Database Types to Java Types

ResultSet maps database types to Java types.

ResultSet rset = stmt.executeQuery


("select ID, DATE_OF_JOIN, SUPERVISOR
from STUDENT");

int id = rset.getInt(1);
Date rentaldate = rset.getDate(2);
String status = rset.getString(3);

Col Name Type

ID NUMBER

DATE_OF_JOIN DATE

SUPERVISOR VARCHAR2

Version 2.0 132

In many cases, you can get all the columns in your result set using the
getObject() or getString() methods of ResultSet. For performance reasons,
or because you want to perform complex calculations, it is sometimes
important to have your data in a type that exactly matches the database
column.

132
Table of SQL Types and Java Types

ANSI SQL Type Java Type ResultSet Method


CHAR, VARCHAR2 java.lang.String getString()
NUMERIC, DECIMAL java.math.BigDecimal getBigDecimal()
BIT boolean getBoolean()
TINYINT byte getByte()
SMALLINT short getShort()
INTEGER int getInt()
BIGINT long getLong()
REAL float getFloat()
DOUBLE, FLOAT double getDouble()
BINARY, VARBINARY byte[] getBytes()
DATE java.sql.Date getDate()
TIME java.sql.Time getTime()

Version 2.0 133

The table lists the ANSI SQL types, the corresponding data type to use in
Java, and the name of the method to call in ResultSet, to obtain that type
of column value.

133
The PreparedStatement Object

A PreparedStatement object holds precompiled SQL statements.

Use this object for statements you want to execute more than once.

A prepared statement can contain variables that you supply each time
you execute the statement.

Version 2.0 134

Prepared Statements
PreparedStatement is inherited from Statement; the difference is that a
PreparedStatement holds precompiled SQL statements.
If you execute a Statement object many times, its SQL statement is
compiled each time. PreparedStatement is more efficient because its SQL
statement is compiled only once, when you first prepare the
PreparedStatement. After that, each time you execute the SQL statement
in the PreparedStatement, the SQL statement does not have to be
recompiled.
Therefore, if you need to execute the same SQL statement several times
within an application, it is more efficient to use PreparedStatement than
Statement.
PreparedStatement Parameters
A PreparedStatement does not have to execute exactly the same query
each time. You can specify parameters in the PreparedStatement SQL
string and supply the actual values for these parameters when the
statement is executed.
Supplying parameters and executing a PreparedStatement is covered in
the subsequent slide.

134
How to Create a PreparedStatement?

1. Register the driver and create the database connection

2. Create the prepared statement, identifying variables with a question


mark (?)

PreparedStatement pstmt =
conn.prepareStatement("update STUDENT
set SUPERVISOR = ? where ID = ?");

PreparedStatement pstmt =
conn.prepareStatement("select SUPERVISOR from
STUDENT where ID = ?");

Version 2.0 135

Even for creating PreparedStatement object, the initial steps of registering


the driver and creating a connection object remain the same.
Once the connection object is obtained, the preparedStatement method is
called on it to obtain the PreparedStatement object. However, in this case,
while creating it, itself, the SQL statement is provided as a parameter to
the method. The variable portions of the SQL statement are provided as a
question mark (?) so that the values can be supplied dynamically before
execution of the statement.

135
How to execute PreparedStatement?

1. Supply values for the variables

pstmt.setXXX(index, value);

2. Execute the statement

pstmt.executeQuery();
pstmt.executeUpdate();

PreparedStatement pstmt =
conn.prepareStatement("update STUDENT
set SUPERVISOR = ? Where ID = ?");
pstmt.setString(1, "OUT");
pstmt.setInt(2, id);
pstmt.executeUpdate();

Version 2.0 136

Specifying Values for the Bind Variables


You use the PreparedStatement.setXXX() methods to supply values for the
variables in a prepared statement. There is one setXXX() method for each
Java type: setString(), setInt(), and so on.
You must use the setXXX() method that is compatible with the SQL
type of the variable. In the example on the slide, the first variable is
updating a VARCHAR column, so we need to use setString() to supply a
value for the variable. You can use setObject() with any variable type.
Each variable has an index. The index of the first variable in the prepared
statement is 1, the index of the second is 2, and so on. If there is only one
variable, its index is one. The index of a variable is passed to the setXXX()
method.

Closing a Prepared Statement


If you close a prepared statement, you will have to prepare it again.

136
Case Study: Banking Application (Contd.).

Table user_personal_info contains User’s personal details.

Column Name Column Type Max Size

userid Number 16
Fname Varchar2 15
lname Varchar2 15
emailid Varchar2 40
gender Varchar2 1
date_of_birth Date
address Varchar2 50
city Varchar2 15
pin Varchar2 6
profession Varchar2 20

Version 2.0 137

137
Examples (Contd.).

3. Creating User_Personal_Info Table

//In this example, Type 4 driver is used.

import java.sql.*;

class MakeConnection3
{
Connection con;
Statement stmt;
int i;
MakeConnection3()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=
DriverManager.getConnection(“Jdbc:Oracle:thin:@localhost:1521:orcl","scott","ti
ger ");
stmt = con.createStatement();
i = stmt.executeUpdate("create table User_Personal_info(userid
number(16), fname varchar2(15), lname
varchar2(15), emailid varchar2(20), gender varchar2(1), date_of_birth date,
address varchar2(50), city varchar2(15), pin varchar2(8),
profession varchar2(20)) ");
System.out.println(" Account-Info Table Created");
}
catch(Exception e)
{
System.out.println("Table Already Exists\n\n"+e);
}
}
}

class CreatePersonalInfo
{
public static void main(String args[])
{
new MakeConnection3();
}
}

138
Example demonstrating the use of
PreparedStatement Object

4.Adding data to the table created above and displaying


selected columns from each row.

import java.sql.*;

class MakeConnection4
{
Connection con;
PreparedStatement pstmt;
Statement stmt;
ResultSet rs;
int i;
MakeConnection4(String args[])
{
try
{
String ss1=args[0];
int s1 = Integer.parseInt(ss1);
String s2=args[1];
String s3=args[2];
String s4=args[3];
String s5=args[4];
String s6=args[5];
String s7=args[6];
String s8=args[7];
String s9=args[8];
String s10=args[9];
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","tiger");
pstmt = con.prepareStatement("insert into user_personal_info
values(?,?,?,?,?,?,?,?,?,?)");
pstmt.setInt(1, s1);
pstmt.setString(2, s2);
pstmt.setString(3, s3);
pstmt.setString(4, s4);
pstmt.setString(5, s5);
Date d = Date.valueOf(s6);
pstmt.setDate(6, d);
pstmt.setString(7, s7);
pstmt.setString(8, s8);
pstmt.setString(9, s9);
pstmt.setString(10, s10);
i=pstmt.executeUpdate();
stmt=con.createStatement();

139
rs = stmt.executeQuery("Select userid, fname, lname, gender,
date_of_birth, city, profession from user_personal_info ");

while(rs.next())
System.out.println(rs.getInt(1)+“
"+rs.getString(2)+" "+rs.getString(3)+"
"+rs.getString(4)+" "+rs.getDate(5)+"
"+rs.getString(6)+" "+rs.getString(7));

}
catch(NumberFormatException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Please pass 10
arguments at the command prompt..!
The usage : java AddPersonalInfo
userid FirstName LastName
email-id gender date-of-birth
address city pin profession for eg.
java AddPersonalInfo 9999 Uday
Mehta 'uda.meh@abc.com' M '2001-
10-15' Jayanagar bangalore 560060
student ");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class AddPersonalInfo
{
public static void main(String args[])
{
new MakeConnection4(args);
}
}

140
Case Study: Banking Application (Contd.).

Table Account_Info_Table contains information about accounts


held by each user – One row per account:

Column Name Column Type Max Size

userid Number 16
accno Number 16
accc_type Varchar2 1
current_balance Number 15,2

Version 2.0 141

141
Examples (Contd.).

5. Create Account_Info_table :

import java.sql.*;

class MakeConnection5
{
Connection con;
Statement stmt;
int i;
MakeConnection5()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","tiger");
stmt = con.createStatement();
i = stmt.executeUpdate("create table
Account_info_table(userid number(16), accno number(16), acc_type

varchar2(1), current_balance number(15,2))");


System.out.println(" Account-Info Table Created");

}
catch(Exception e)
{
System.out.println("Table Already
Exists\n\n"+e);
}
}
}

class CreateAccountInfoTable
{
public static void main(String args[])
{
new MakeConnection5();
}
}

142
6.Add data to account_info_table and display the data :

import java.sql.*;

class MakeConnection6
{
Connection con;
PreparedStatement pstmt;
Statement stmt;
ResultSet rs;
int i;
MakeConnection6(String args[])
{
try
{
String ss1=args[0];
int s1 = Integer.parseInt(ss1);
String ss2=args[1];
int s2 = Integer.parseInt(ss2);
String s3=args[2];
int s4=Integer.parseInt(args[3]);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","tiger");
pstmt = con.prepareStatement("insert into Account_info_table
values(?,?,?,?)");
pstmt.setInt(1, s1);
pstmt.setInt(2, s2);
pstmt.setString(3, s3);
pstmt.setInt(4, s4);
i=pstmt.executeUpdate();
stmt=con.createStatement();
rs = stmt.executeQuery("Select * from Account_info_table");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getInt(2)+"
"+rs.getString(3)+" "+rs.getInt(4));
}
catch(NumberFormatException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Please pass four arguments at
the command prompt..! The usage : java AddAccountInfo

userid account-no account-type balance. for eg. java AddAccountInfo Har0001 1005
S 20000 ");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

143
Case Study: Banking Application (Contd.).

Bankusertransaction table contains the banking transactions done


by all the users.

Column Name Column Type Max Size

accno Number 16
tran_desc Varchar2 40
tran_type Varchar2 1
tran_date date
amount Number 15,2
closing_balance Number 15,2

Version 2.0 144

144
7. Creating Bankusertransaction table

import java.sql.*;

class MakeConnection7
{
Connection con;
Statement stmt;
int i;
MakeConnection7()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","tiger");
stmt = con.createStatement();
i = stmt.executeUpdate("create table BankUserTransaction(accno
number(16), trans_desc varchar2(40),
tran_type varchar2(1), tran_date date, amount number(15,2), closing_balance
number(15,2))");
System.out.println(" Transaction Table Created");
}
catch(Exception e)
{
System.out.println("Table Already Exists\n\n"+e);
}
}
}

class CreateTransactionTable
{
public static void main(String args[])
{
new MakeConnection7();
}
}

145
8. Updating the Bank Transaction in appropriate tables

import java.sql.*;

class MakeConnection8
{
Connection con, con1;
PreparedStatement pstmt,pacctinfostmt;
Statement stmt, stmtbal;
ResultSet rs, rsbal;
int i, bal;
MakeConnection8(String args[])
{
try
{
String ss1=args[0];
int s1 = Integer.parseInt(ss1);
String s2=args[1];
String s3=args[2];
String s4=args[3];
int s5=Integer.parseInt(args[4]);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","tiger");
con1=
DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","tiger");
pstmt = con.prepareStatement("insert into BankUserTransaction
values(?,?,?,?,?,?)");
pstmt.setString(1, s1);
pstmt.setString(2, s2);
pstmt.setString(3, s3);
Date d=Date.valueOf(s4);
pstmt.setDate(4, d);
pstmt.setInt(5, s5);
//reading current balance from account-info-table
stmtbal=con1.createStatement();
rsbal=stmtbal.executeQuery("Select current_balance
from account_info_table where accno="+s1);

while(rsbal.next())
bal=rsbal.getInt(1);

//depending on whether it is credit or debit calculate


the closing balance and update it
if(s3.equals("D") | s3.equals("d"))
bal=bal-s5;
else
bal=bal+s5;
pstmt.setInt(6, bal);
i=pstmt.executeUpdate();

//update the account info table


pacctinfostmt = con1.prepareStatement("update
account_info_table set current_balance ="+bal+" where accno="+s1);
i=pacctinfostmt.executeUpdate();

146
//print the rows of Transaction table
stmt=con.createStatement();
rs = stmt.executeQuery("Select * from BankUserTransaction");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3)+" "+rs.getDate(4)+" "+rs.getInt(5));
}
catch(NumberFormatException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Please pass five
arguments at the command prompt..!
The usage : java
AddBankTransactions accno
description transaction-type
transaction-date amount. for eg. java
AddBankTransactions 1001
Withdrawal D \“2008-05-21\" 20000
");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

class AddBankTransactions
{
public static void main(String args[])
{
new MakeConnection8(args);
}
}

147
The CallableStatement Object

A CallableStatement object holds parameters for calling stored


procedures.

A callable statement can contain variables that you supply each time
you execute the call.

When the stored procedure returns, computed values (if any) are
retrieved through the CallableStatement object.

Version 2.0 148

The way to access stored procedures using JDBC is through the


CallableStatement class which is inherited from the PreparedStatement
class. CallableStatement is like PreparedStatement in that you can specify
parameters using the question mark (?) notation, but it contains no SQL
statements.
Both functions and procedures take parameters represented by
identifiers. A function executes some procedural logic and it returns a
value that can be any data type supported by the database. The
parameters supplied to the function do not change after the function is
executed.
A procedure executes some procedural logic but does not return any
value. However, some of the parameters supplied to the procedure may
have their values changed after the procedure is executed.
Note: Calling a stored procedure is the same whether the stored
procedure was written originally in Java or in any other language
supported by the database, such as PL/SQL. Indeed, a stored procedure
written in Java appears to the programmer as a PL/SQL stored
procedure.

148
How to Create a CallableStatement?

§ Register the driver and create the database connection

§ Create the callable statement, identifying variables with a question


mark (?)

CallableStatement cstmt =
conn.prepareCall("{call " +
ADDITEM +
"(?,?,?)}");
cstmt.registerOutParameter(2,Types.INTEGER);
cStmt.registerOutParameter(3,Types.DOUBLE);

Version 2.0 149

First you need an active connection to the database in order to obtain a


CallableStatement object. Next, you create a CallableStatement object
using the prepareCall() method of the Connection class. This method
typically takes a string as an argument. The syntax for the string has two
forms. The first form includes a result parameter and the second form
does not:
{? = call proc (…) } // A result is returned into a variable
{call proc (…) } // Does not return a result
In the example in the slide, the second form is used, where the stored
procedure in question is ADDITEM.
Note that the parameters to the stored procedures are specified using the
question mark notation used earlier in PreparedStatement. You must
register the data type of the parameters using the registerOutParameter()
method of CallableStatement if you expect a return value, or if the
procedure is going to modify a variable (also known as an OUT variable).
In the example in the slide, the 2nd and 3rd parameters are going to be
computed by the stored procedure, whereas the 1st parameter is an input
(the input is specified in the next slide). Parameters are referred to
sequentially, by number. The first parameter is 1.
To specify the data type of each OUT variable, you use parameter types
from the Types class. When the stored procedure successfully returns, the
values can be retrieved from the CallableStatement object.

149
How to execute a CallableStatement?

1. Set the input parameters

cstmt.setXXX(index, value);

2. Execute the statement

cstmt.execute(statement);

3. Get the output parameters

var = cstmt.getXXX(index);

Version 2.0 150

There are three steps in executing the stored procedure after you have
registered the types of the OUT variables:

Set the IN parameters - Use the setXXX() methods to supply values for
the IN parameters. There is one setXXX() method for each Java type:
setString(), setInt(), and so on. You must use the setXXX() method that is
compatible with the SQL type of the variable. You can use setObject()
with any variable type. Each variable has an index. The index of the first
variable in the callable statement is 1, the index of the second is 2, and so
on. If there is only one variable, its index is 1.

Execute the call to the stored procedure - Execute the procedure using
the execute() method.

Get the OUT parameters - Once the procedure is completed, you retrieve
OUT variables, if any, using the getXXX() methods. Note that these
methods must match the types you registered in the previous slide.

150
CallableStatement (Contd.).

Example for demonstration of CallableStatement

In this example, we calculate the interest for SB accounts based on the


transactions recorded in the bankusertransaction table. Interest is
calculated for the minimum amount available for this account during a
particular month. Interest is calculated only for the previous month.

Version 2.0 151

151
import java.sql.*;
class CallInterest
{
CallInterest(String arg)
{
Connection conn;
Statement stmt;
CallableStatement cstatement=null;
ResultSet rs;
String query;
int accno;
int interest_rate= Integer.parseInt(arg);
int interest;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","ti
ger");
stmt=conn.createStatement();
rs = stmt.executeQuery("Select accno from account_info_table
where acc_type = ‘S’");
while(rs.next())
{
accno = rs.getInt(1);
query = "{ CALL CalculateInterest
("+accno+","+interest_rate+",?)}";
cstatement = conn.prepareCall(query);
cstatement.registerOutParameter(1,
Types.INTEGER);
cstatement.execute();
interest = cstatement.getInt(1);
System.out.println("The account no : "+accno+" The
Calculated Interest : "+interest);

}
cstatement.close();
conn.close();

}
catch (ClassNotFoundException error)
{
System.out.println("Unable to load the JDBC/ODBC bridge" + error);
}
catch (SQLException error)
{
System.out.println("Cannot connect to database "+ error);
}
}
}

class CallableInterest
{
public static void main (String args[])
{
new CallInterest(args[0]);
}
}

152
The Procedure 'CalculateInterest' stored in oracle:

Procedure CalculateInterest(acc_no in number, x in number, y out number)


is
begin
select (x/12)/100*min(closing_balance)
into y
from bankusertransaction
where (to_char(tran_date,'mm' ) = to_char(sysdate, 'mm')-1) and to_char
(tran_date, 'yyyy') = to_char(sysdate, 'yyyy') and accno=acc_no;
end;

153
Using Transactions

The server-side driver does not support autocommit mode.

With other drivers new connections are in autocommit mode and use
conn.setAutoCommit(false) to turn autocommit off.

To control transactions when you are not in autocommit mode:


conn.commit(): Commit a transaction
conn.rollback(): Roll back a transaction

Version 2.0 154

Transactions with JDBC


With JDBC, database transactions are managed by the Connection object.
When you create a Connection object, it is in autocommit mode, meaning
that each statement is committed after it is executed.
You can change the connection's autocommit mode at any time by calling
setAutoCommit(). Here is a full description of autocommit mode:
If a connection is in autocommit mode, all its SQL statements will be
executed and committed as individual transactions.
If a statement returns a result set, the statement completes when the last
row of the result set has been retrieved, or the result set has been closed.
If autocommit mode has been disabled, its SQL statements are grouped
into transactions, which must be terminated by calling either commit() or
rollback().
commit() makes permanent all changes since the previous commit or
rollback and releases any database locks held by the connection.
rollback() drops all changes since the previous commit or rollback and
releases any database locks. commit() and rollback() should only be called
when in non-autocommit mode.

154
Example demonstrating the use of Transactions:
import java.sql.*;

class MakeConnection9
{
Connection con;
PreparedStatement pstmt,pacctinfostmt;
Statement stmt, stmtbal;
ResultSet rs, rsbal;
int i, bal;
MakeConnection9(String args[])
{
try
{
String ss1=args[0];
int s1 = Integer.parseInt(ss1);
String s2=args[1];
String s3=args[2];
String s4=args[3];
int s5=Integer.parseInt(args[4]);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("Jdbc:Odbc:ORADSN","scott","tiger");
con.setAutoCommit(false);
pstmt =
con.prepareStatement("insert into BankUserTransaction values(?,?,?,?,?,?)");
pstmt.setInt(1, s1);
pstmt.setString(2, s2);
pstmt.setString(3, s3);
Date d=Date.valueOf(s4);
pstmt.setDate(4, d);
pstmt.setInt(5, s5);

155
//reading current balance from
account-info-table
stmtbal=con.createStatement();
rsbal=stmtbal.executeQuery("Select
current_balance from
account_info_table where
accno="+s1);

while(rsbal.next())
bal=rsbal.getInt(1);

//depending on whether it is
credit or debit calculate the
closing balance and update it
if(s3.equals("D") |
s3.equals("d"))
bal=bal-s5;
else
bal=bal+s5;
pstmt.setInt(6, bal);
i=pstmt.executeUpdate();
if(bal <=0)
throw new
SQLException();

//update the account info table


pacctinfostmt =
con.prepareStatement("update
account_info_table set
current_balance ="+bal+" where
accno="+s1);
i=pacctinfostmt.executeUpdate();
con.commit();
con.setAutoCommit(true);

//print the rows of Transaction


table
stmt=con.createStatement();
rs = stmt.executeQuery("Select * from
BankUserTransaction");
while(rs.next())
System.out.println(rs.getInt(1)+"
"+rs.getString(2)+" "+rs.getString(3)+"
"+rs.getDate(4)+" "+rs.getInt(5)+"
"+rs.getInt(6));
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Please pass
five arguments at the command
prompt..! The usage : java
TransactionExample2 accno
description transaction-type
transaction-date amount. for eg. java
TransactionExample2 1001
Withdrawal D \"20/05/2008\"
20000 ");
}

156
catch(Exception e)
{
System.out.println(e);
try
{

System.out.println("Transaction is being rolled back");


con.rollback();

con.setAutoCommit(true);
}
catch(Exception e1)
{

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

class TransactionExample
{
public static void main(String args[])
{
new MakeConnection9(args);
}
}

157
Summary of JDBC Classes

DriverManager

Connection DatabaseMetaData

Statement

ResultSet
ResultSetMetaData

Version 2.0 158

DriverManager - DriverManager provides access to registered JDBC


drivers. DriverManager hands out connections to a specified data source
through its getConnection() method.
Connection - The Connection class is provided by the JDBC driver, as
are all subsequent classes mentioned. A Connection object represents a
session with a database and is used to create a Statement object, using
Connection.createStatement().
Statement - The Statement class executes SQL statements. For
example, queries can be executed using the executeQuery() method and
the results are wrapped up in a ResultSet object.
ResultSet - JDBC returns the results of a query in a ResultSet object. A
ResultSet object maintains a cursor pointing to its current row of data.
The next() method moves the cursor to the next row. The ResultSet class
has getXXX() methods to retrieve the columns in the current row.
DatabaseMetaData and ResultSetMetaData - The DatabaseMetaData
and ResultSetMetaData classes return metadata about the database and
ResultSet, respectively. Call getMetaData() on the Connection object or the
ResultSet object.

158
Summary

In this module you have learnt to:


§ Connect to a database using Java Database Connectivity (JDBC)
§ Create and execute a query using JDBC
§ Invoke prepared statements
§ Commit and roll back transactions
§ Use the Metadata objects to retrieve more information about the
database or the resultset

Version 2.0 159

159
Module 4:
Servlets

Copyright © 2008, Wipro Limited, Bangalore

160
Servlets

The lessons covered in this module include:


§ Introduction to Servlet
§ What is a Servlet?
§ Building a Servlet using the Servlet API
§ Servlet Life Cycle
§ Uses of HTTP Servlets
§ The init() Method
§ The service() Method
§ The destroy() Method

Version 2.0 161

161
Servlets (Contd.).

The lessons covered in this module include:


§ Handling HTTP Get requests
§ The Servlet Interface
§ ServletConfig Interface
§ ServletContext Interface
§ Servlet chaining
§ The Cookie class
§ Session Tracking

Version 2.0 162

162
Objectives

At the end of this module you will be able to:


§ Describe the role of HTTP Servlet in Web Programming
§ Describe and use the Servlet Life Cycle methods appropriately
§ Process parameters from HTML forms
§ Establish Database Connectivity through servlets
§ Maintain Http Sessions in Servlets

Version 2.0 163

The aim of this course is to be able to understand, appreciate and use


Servlets as the basic building blocks of a J2EE web-based application.
The historic role of servlets is discussed followed by the life cycle aspects.
Then the important interfaces and methods required to process data
submitted by HTML forms is also explained. Finally the session
management feature provided by servlets is also explored.

163
Introduction to Servlet

Version 2.0 164

Servlets are modules of java code that run in a server application to


answer client requests. It is often used in lieu of “HTTP Servlet”. Servlets
are to servers what applets are to browsers. Unlike applets however
servlets have no graphical user interface.

Suppose that the author of this document was running an online


bookstore. The reader -- as the client -- visits the author's site and is
presented with an HTML form where the reader can enter the ISBN of a
book, and his or her shipping information. The HTML form, once
submitted to the server, contains the data that the server will use. By
submitting the form, an "order entry" servlet is invoked on the server
using methods that will be discussed shortly. This servlet uses its
database connection (possibly JDBC) to update database tables, and
perhaps decrement the number of books in inventory. As well, it could
obtain information about the shipping date. The Order-Entry servlet then
packages this information into a response to the client, and returns it to
the client.

164
Introduction to Servlet: Static Web Site

HTTP Server
HTML HTTP

<HTML>
Aruba
Bermuda
Bahamas
</HTML>

Source: http://www.myvacation.com/ListDest.htm

Version 2.0 165

Historically, web applications were built out of only static HTML pages.
Then, HTTP servers or web servers were simple programs that could
decipher a request for a static HTML page by analyzing the URL,
searching out the HTML document from its local folders and serving the
same back through HTTP protocol to the requesting client.
In the above case, when the request is received by a server which is
named ‘www.myvacation.com’, the web server searches its folders for a
file by name ‘ListDest.htm’. On finding one such file, the file is streamed
back to the client through the HTTP Protocol.

165
Dynamic Page Generation Using CGI

ODBC / Native
HTTP Server
HTML HTTP CGI
Application

<HTML>
Aruba
Bermuda
Bahamas
</HTML>

Source: http://www.myvacation.com/cgi/ListDest.exe

Version 2.0 166

As the web became more popular, the functionality of Web Servers was
enhanced by CGI applications that were typically written in C or Perl.
Using the power of any traditional language, all the back end processing
like accessing or updating a database was achieved by that CGI program
and a simple HTML response was returned by the HTTP server to the
client.
Thus more dynamism was built into the so far, static Web Applications.

What is CGI?
CGI (Common Gateway Interface) is a standard that specifies how
external programs may be used by web servers. Programs that adhere to
CGI standards are known as CGI programs. The HTTP request
information is passed by the web server to that external program, which
processes the request and passes back the response to the server. The
server then forwards this response to the client browser. CGI programs
can be written in any language, of which Perl is the most popular. In CGI,
each client request makes the server spawn a new process of CGI
program, which is an expensive operation. Hence CGI programs are not
scalable.

166
Dynamic Page Generation Using Servlets

HTTP Server

JDBC
HTML HTTP Servlet
Container

<HTML>
Aruba
Bermuda
Bahamas
</HTML>

Source: http://www.myvacation.com/servlet/ListDest.htm

Version 2.0 167

CGI applications had their own limitations as mentioned earlier. To


overcome these limitations, the J2EE platform introduced the Servlet
technology. The advantages of servlets over CGI is discussed later.

167
What is a Servlet?

Servlet is a Server side Java program that extends the functionality of a


Web Server. It is used to dynamically generate HTML documents and is
comparable to:
§ CGI
§ Netscape NSAPI
§ Microsoft ISAPI
§ Apache Modules

Version 2.0 168

A servlet is a server-side Java replacement for CGI scripts and


programs. Servlets are much faster and more efficient than CGI and
they let you unleash the full power of Java on your web server, including
back-end connections to databases and object repositories through
JDBC, RMI, and CORBA.

168
Servlet: Benefits

Servlet is written in pure Java and is platform independent. It can take


advantage of JDBC, EJB, JMS, JavaMail, JavaIDL, RMI, ...

Servlet is Server independent.

In terms of Scalability, servlet doesn’t start new process for each


request and can run in same server process as HTTP server. It is multi-
Threaded.

Version 2.0 169

Since the servlets are written in pure Java they are portable, i.e. they can
be deployed into any servers with minimal or no modifications.

It’s highly scalable since it doesn’t start a new process for every new
request but will spawn a thread. A thread is light weight when compared
to CGI which starts a new process for every new request (A process is
heavy weight as it consumes many more system resources than a
thread).

169
Servlet: Advantages over CGI

A Servlet does not run in a seperate process.

A Servlet stays in memory between requests.

There is only a single instance which answers all requests concurrently.

Version 2.0 170

The traditional way of adding functionality to a Web Server is the


Common Gateway Interface (CGI), a language-independent interface
that allows a server to start an external process which gets information
about a request through environment variables, the command line and
its standard input stream and writes response data to its standard
output stream. Each request is answered in a separate process by a
separate instance of the CGI program, or CGI script (as it is often called
because CGI programs are usually written in interpreted languages like
Perl). Servlets have several advantages over CGI:
•A Servlet does not run in a separate process, which removes the
overhead of creating a new process for each request.
•A Servlet stays in memory between requests. A CGI program (and
probably also an extensive runtime system or interpreter) needs to be
loaded and started for each CGI request.
•There is only a single instance which answers all requests concurrently.
This saves memory and allows a Servlet to easily manage persistent
data.
•A Servlet can be run by a Servlet Engine in a restrictive sandbox (just
like an Applet runs in a Web Browser's Sandbox) which allows secure
use of less trusted and potentially harmful Servlets.

170
Building a Servlet Using the Servlet API

§ Extend HttpServlet
Servlet
§ Code Servlet's life cycle Methods

GenericServlet

HttpServlet

LogonServlet

Version 2.0 171

The root of the servlet class/interface hierarchy is the servlet interface.


This belongs to the javax.servlet package.
To be qualified as a servlet, any class has to directly or indirectly
implement the servlet interface. This defines all the methods that a
servlet must implement.
In practice, there is an abstract class named as the GenericServlet that
implements the Servlet Interface. This defines a generic, protocol-
independent servlet. GenericServlet makes writing servlets easier. It
provides simple implementation of the lifecycle methods.
To write a generic servlet of your own, you can extend the abstract
GenericServlet, though in practice it is rarely done. The GenericServlet
too belongs to the javax.servlet package
HttpServlet is another abstract class that extends the GenericClass and
belongs to the javax.servlet.http package. This servlet is HTTP protocol
specific. Hence any user-defined servlets that need to receive and
respond to request on the HTTP protocol, need to subclass HttpServlet
class.

171
Web Container

A Web container is a component of the Web server that interacts with


the servlets.
The Web container is responsible for managing the lifecycle of servlets,
mapping a URL to a particular servlet and ensuring that the URL
requester has the correct access rights.
A web container provides basic services which enables a Web
programmer to concentrate on business logic rather than worrying
about writing codes for these services.
Web Container provides the following services :
§ Communications Support
§ Lifecycle Management
§ Multithreading Support
§ Declarative Security
§ JSP Support
Version 2.0 172

Servlets are managed by Web containers. Tomcat is an example of a


container.

A web container(also known as servlet container) is a specialized


component of a web server that supports Servlet execution. It combines
the basic functionality of a web server with certain Servlet specific
services. It provides integrated Java runtime environment and it has the
ability to automatically translate specific URLs into Servlet requests.
Once a developer writes a servlet program, he register them with the
container(deployment), providing the container with information about
what functionality they provide, and what URL or other resource locator
they will use to identify themselves. It is the responsibility of the
container to initialize the Servlet as necessary and deliver requests to the
Servlet as they arrive.

172
The following services are provided by a Web Container :

Communication Support : The container provides an easy way for the


servlets to talk to the web server. Without this support, the programmer
has to write code for creating sockets that provide communication
between the servlet and the web server.

Lifecycle Management : The container is responsible for life and death of


the servlets. It will take care of instantiating the servlets, initializing
them, invoking the appropriate methods and destroying them when not
in use. It is the responsibility of the servlets to make servlet instances
eligible for garbage collection. It will take care of resource management.

Multithreading Support :One major advantage of using Servlets is that


only one instance of a servlet is created for multiple requests. Multiple
threads are created for handling multiple requests. It is the responsibility
of the container to create threads for every servlet request it receives.

Declarative Security : We can use an XML deployment descriptor to


configure or modify security and other configuration parameters related
to servlets, without having to hardcode it within the servlet code.

JSP Support : The container is responsible for converting a JSP into a


Servlet.

173
How an Http Request is handled

1. When the user clicks on a link that requires the services of a servlet,
the request is received by the web server and passed on to the
container.
2. The container receives the request, realizes that the request is for a
servlet. So, it creates two objects, HttpServletRequest and
HttpServletResponse.
3. After locating the servlet based on the URL, the container
creates/allocates a thread for that request. It then passes the two
objects(request and response) to this thread
4. The container then calls this servlet’s service() method. service()
method, in turn, calls the doGet() or doPost() method depending
on the request
5. doGet() or doPost() method is responsible for generating the
response(as requested by the client). The output from this method
is stuffed into the response object. The container converts the
response object to an HTTP response and sends it to the client.
Version 2.0 174

After sending the response to the client, the container deletes the request
and response objects.

174
Servlet Life Cycle

Servlets Container

HTTP Server
Thread
init( )
doGet( )
Thread

Servlet

Thread

Version 2.0 175

Servlets run on the web server platform as part of the same process as
the web server itself. The container communicates with a servlet
through a simple interface, javax.servlet.Servlet.

This interface consists of three main methods:


init()
service()
destroy()
As discussed earlier, when a client sends a request to an HTTP server for
a servlet, the request is passed on to the servlet container that hosts the
servlet. The servlet container checks if an instance of that servlet is
already running in it. If so, a new thread is created which invokes the
service() method of the same servlet.
However, if the servlet is not loaded, then the container first loads the
servlet, invokes its init() method. Only on completion of the init()
method, the appropriate service() method is called on behalf of the
incoming request. All subsequent client requests for the same servlet are
handled by different threads that invoke the same servlet instance
init() is called only once during the life of a servlet.

175
Servlet Life Cycle (Contd.).

Servlets Container

HTTP Server
Thread
init( )
doGet( )

Servlet

Thread

Version 2.0 176

Once the servlet completes the execution of the service method (i.e.
doGet() or doPost()), and the response is sent back to the client, the
thread is destroyed.
However, the servlet instance continues to be in memory catering to the
requests of other clients.

176
Servlet Life Cycle (Contd.).

Servlets Container

HTTP Server
init( )
doGet( )

Servlet

Thread

Version 2.0 177

The servlet instance continues to be in memory as long as it keeps


receiving client requests for some service. As the requests are handled
successfully, the many threads created by the servlet container are
destroyed. However, the servlet instance continues to be in memory
ready to serve any new request, usually till a time out period defined by
the servlet container or till the server itself is up and running.

177
Servlet Life Cycle (Contd.).

Servlets Container

HTTP Server
init( )
doGet( )
destroy( )

Servlet

Version 2.0 178

If the servlet container is configured to maintain servlets in memory for


a particular time out period, the container checks and destroys the
servlet instance if no requests have been received during the prescribed
timeout period.

Destroying a servlet involves the invoking of the destroy() method on


the servlet.

178
Servlet Life Cycle (Contd.).

Servlets Container

HTTP Server

Version 2.0 179

If the servlet container now receives any request for a servlet, the whole
life cycle of a servlet has to be repeated as mentioned earlier.

179
Uses of HTTP Servlets

HTTP Servlets are used for:


§ Processing and/or storing data submitted by an HTML form
§ Providing dynamic content
§ Managing state information

Version 2.0 180

Processing the data submitted by an HTML form and if required,


storing the data in a persistent storage.
Providing dynamic content - sending appropriate response to the client.
e.g. returning the results of a database query to the client.
Managing state information on top of the stateless HTTP, e.g. for an
online shopping cart system which manages shopping carts for many
concurrent customers and maps every request to the right customer.

180
ServletContext and ServletConfig

ServletContext object is created by the container when it initializes.

There is only one ServletContext in every application. This object can


be used by all the servlets to obtain application level information or
container details.

Every servlet, on the other hand, gets its own ServletConfig object.
This object provides initialization parameters for a servlet.
The ServletContext object is contained within the ServletConfig object.
Servlets get the ServletContext object via the getServletContext method
of ServletConfig.
The ServletConfig object is provided to the servlet at initialization and
is accessible via the servlet's getServletConfig method.

Version 2.0 181

181
The init() Method

public void init(ServletConfig) throws ServletException.

This method is for initialization of the servlet.

One can establish database connection in this method which


could be shared by every client.

This method is called only once during the life of a servlet.

Version 2.0 182

When a servlet is first loaded, its init() method is invoked. This allows
the servlet to perform any setup processing such as opening files or
establishing connections to their servers.

init() method is guaranteed to finish before any other calls are made to
the servlet--such as a call to the service() method. Note that init() will
only be called once; it will not be called again unless the servlet has
been unloaded and then reloaded by the server.

init() method takes one argument, a reference to a ServletConfig object


which provides initialization arguments for the servlet. This object has a
method getServletContext() that returns a ServletContext object
containing information about the servlet's environment.

182
In order to initialize a Servlet, the container loads the Servlet class (and
probably other classes which are referenced by the Servlet) and creates
an instance by calling the no-args constructor. Then it calls the Servlet's
init(ServletConfig config) method. The Servlet should perform one-time
setup procedures in this method and store the ServletConfig object so
that it can be retrieved later by calling the Servlet's getServletConfig()
method.

There is only one ServletContext in every application. This object can be


used by all the servlets to obtain application level information or
container details. Every servlet, on the other hand, gets its own
ServletConfig object. This object provides initialization parameters for a
servlet. A developer can obtain the reference to ServletContext using
either the ServletConfig object or ServletRequest object.

183
The service() Method

public void Service(ServletRequest, ServletResponse) throws


ServletException, IOException

This method is called once per client.

Version 2.0 184

The service() method is the heart of the servlet.


Each request message from a client results in a single call to the
servlet's service() method.
service() method reads the request and produces the response message
from its two parameters:
•A ServletRequest object
•A ServletResponse represents the servlet's reply back to
the client
When the Servlet is initialized and ready, its service(ServletRequest req,
ServletResponse res) method is called for every request to the Servlet.
The method is called concurrently (i.e. multiple threads may call this
method at the same time) so it should be implemented in a thread-safe
manner.
As a servlet developer, you are not supposed to override this method.
This method should be used as it is available from HttpServlet class(The
class that your servlet inherits). You are supposed to override either
doGet() or doPost() method, depending on the client request.
service() method is responsible for looking at the request and invoking
the doGet() or doPost() method on the servlet.

184
The destroy() Method

public void destroy() is called to destroy the servlet and release the
resources.

destroy() is called by the Servlet Container and is called once during


the life of a servlet.

Version 2.0 185

The destroy() Method destroys the servlet, cleaning up whatever


resources are being held, and logs the destruction in the servlet log file.
This method is called, once, automatically, by the servlet container each
time it removes the servlet. After destroy is run, it cannot be called again
until the servlet container reloads the servlet.

When the Servlet Container removes a servlet, it calls destroy after all
service calls have been completed, or a service-specific number of
seconds have passed, whichever comes first. In the case of long-running
operations, there could be other threads running service requests when
destroy() is called. The servlet writer is responsible for ensuring that all
the threads have completed their task before destroy() takes over.

All resources which were allocated in init() should be released in


destroy(). This method is guaranteed to be called only once during the
Servlet's lifecycle.

185
Handling HTTP GET requests

HTTP GET request override the doGet method.

Methods in the HttpServlet class that handle client requests take two
arguments:
§ An HttpServletRequest object, which encapsulates the data from the
client
§ An HttpServletResponse object, which encapsulates the response to
the client

Version 2.0 186

To handle HTTP requests in a servlet, extend the HttpServlet class.

The doGet() method is a protocol specific method available only in the


HttpServlet class. Based on the HTTP protocol, whenever an HTML
requests for a servlet through the “GET” method in its form tag, the
service() method of the HttpServlet dispatches the request to the doGet()
method. If the HTTP request is through a POST method, then, the
doPost() method is invoked.

186
Reading Servlet Parameters

The ServletRequest class includes methods that allow you to read the
names and values of parameters that are included in a client request.

Methods used are:


getParameterNames()
getParameter(String pname)
getParameterValues(String pname)

Version 2.0 187

ServletRequest is the main object that provides the client request


information to a servlet. The servlet container creates a ServletRequest
object and passes it as an argument to the servlet’s service method. A
ServletRequest object provides data including parameter name and
values, attributes, and an input stream. Interfaces that extend
ServletRequest can provide additional protocol-specific data, e.g., the
HttpServletRequest object.
The getParameterNames() method returns an Enumeration of String
objects containing the names of parameters contained in the request. If
the request has no parameters, the method returns an empty
Enumeration.
The getParameter(String pname) method returns the value of a request
parameter as a String, or null if the parameter does not exist. Request
parameters are extra information sent with the request. For HTTP
servlets, parameters are contained in the query string or posted form
data. You should only use this method when you are sure the parameter
has only one value. If the parameter might have more than one value,
use getParameterValues(java.lang.String). The getParameterValues(String
pname) method returns an array of String objects containing all of the
values the given request parameter has, or null if the parameter does not
exist. If the parameter has a single value, the array has a length of 1.

187
The servlet Interface

A servlet is Java class that implements the javax.servlet.Servlet


interface.

This interface defines only five methods:


service()
init()
getServletConfig()
destroy()
getServletInfo()

Version 2.0 188

This interface defines methods to initialize a servlet, to service requests,


and to remove a servlet from the server. These are known as life-cycle
methods as discussed earlier. They occur in the following sequence:
The servlet is constructed, then initialized with the init method.
Any calls from clients are handled by the service method.
The servlet is taken out of service, then destroyed with the destroy
method, then garbage collected and finalized.
Since every servlet directly or indirectly implements the servlet interface,
implementation for all these methods has to be provided.
There are two more non-life-cycle methods in this interface:
getServletConfig() returns a ServletConfig object (discussed shortly),
which contains initialization and startup parameters for this servlet. The
ServletConfig object returned is the one that is passed to the init method
discussed earlier.
getServletInfo() returns information about the servlet, such as author,
version and copyright. The string that this method returns should be
plain text and not markup of any kind (HTML, XML etc.)

188
ServletConfig Interface

ServletConfig interface is implemented by Servlet container provider in


order to pass configuration information to a servlet when it is first
loaded.

Interface defines following methods:


getServletContext
getInitParameter
getInitParameterNames
getServletName

Version 2.0 189

A service writer implementing this interface must write methods for the
servlet to use to get its initialization parameters and the context in
which it is running. The ServletConfig interface can also be
implemented by servlets (GenericServlet does this). Here, the methods
in the interface make getting the configuration data more convenient.
E.g., a servlet could implement getServletContext by writing,
public ServletContext getServletContext() {
return getServletConfig().getServletContext();
}
making access to the servlet's context object a single method invocation
(a call to getServletContext()).

189
There is only one ServletConfig object per servlet. This object can be used
to pass deploy-time information to the servlet, some information which
keeps changing and you don’t want to hard-code it into the servlet code.
This object can also be used to access the ServletContext object. The
parameters that you want to pass to a servlet are configured in the
deployment descriptor(web.xml)

getInitParameter(String name): returns a String containing the value of


the named initialization parameter or null if the parameter does not exist.

getInitParameterNames(): returns all the names of servlet’s initialization


parameters as an Enumeration of String objects.
getServletName(): returns the name of this servlet instance.

190
ServletContext Interface

ServletContext Interface gives servlets access to information about their


Environment.

The interface allows them to log significant events. Servlet authors


decide what data to log.

Methods:
getServerInfo()
getAttribute(String name)
getAttributeNames()
setAttribute(String name, Object obj)
log(String)

Version 2.0 191

ServletContext defines a set of methods that a servlet uses to


communicate with its servlet container. There is one context per "web
application" per Java Virtual Machine. In the case of a web application
marked "distributed" in its deployment descriptor, there will be one
context instance for each virtual machine. In this situation, the context
cannot be used as a location to share global information (because the
information won't be truly global). Use an external resource like a
database instead. Use ServletContext to access web application
parameters. It can be used as an application bulletin-board(something
which can be shared by all components of a web application).

The ServletContext object is contained within the ServletConfig object,


which the Web server provides the servlet, when the servlet is
initialized.

getServerInfo(): returns the name and version of the servlet container


on which the servlet is running

getAttributes(String name) returns the servlet container attribute with


the given name.

log(String) writes the specified String to a servlet log file.

191
Servlet Chaining: RequestDispatcher Interface

In order to FORWARD or INCLUDE a request from one servlet to


another Servlet/JSP the RequestDispatcher interface provides two
methods.

1. RequestDispatcher.forward(request,response)
2. RequestDispatcher.include(request,response)

Both these methods takes ServletRequest and ServletResponse object


as an argument.

Version 2.0 192

Servlet chaining means communication between two servlets.

The way the two methods are working are different.


Incase of the forward() method the control goes to the second resource
and responsibility of generating the response to the client is with the
second resource.
Incase of the include() method the control moves to the second resource,
but after processing the request the control comes back to the first
resource and the response generation is the responsibility with the first
resource.

192
Servlet Chaining: forward(request,response)

ServletContext ctx=getServletContext();
RequestDispatcher
dis=ctx.getRequestDispatcher(“/servlet/AnotherServlet”);
dis.forward(request,response);

Version 2.0 193

This method allows a servlet to process a request partially and forward it


to another servlet for generating the final response. It can also be used to
forward a request from one active request to another resource on the
server. This method can be called if the response is not committed;
otherwise it will throw an IllegalStateException.

193
Servlet Chaining: forward (request , response);

Client Request Request passing

Client Servlet1 Servlet2

Response Generation

Version 2.0 194

194
Servlet Chaining: include(request, response)

ServletContext ctx=getServletContext();
RequestDispatcher
dis=ctx.getRequestDispatcher(“/servlet/AnotherServlet”);
dis.include(request,response);

Version 2.0 195

In case of include() method the request is not forwarded permanently. It


is passed to another resource temporarily so that the other resource can
partially process the request, and then the forwarding servlet/JSP can
take over the request again to generate the response. Because the request
is not forwarded permanently, all changes to the headers or status code of
the request made by the other request are ignored.

195
Servlet Chaining: include (request , response);

Client Request Request Passing

Client Servlet1 Servlet2

Response Generation Output back to the


Requester

Version 2.0 196

196
The Cookie class

The Cookie class encapsulates a cookie. It is stored on a client and


contains state information.

A servlet can write a cookie to a user's machine via the addCookie()


method of HttpServletResponse.

Use the getCookies() method of the HttpServletRequest to read any


cookies that are included in the HTTP get request.

Version 2.0 197

Creates a cookie, a small amount of information sent by a servlet to a


Web browser, saved by the browser, and later sent back to the server. A
cookie's value can uniquely identify a client, so cookies are commonly
used for session management.

A cookie has a name, a single value, and optional attributes such as a


comment, path and domain qualifiers, a maximum age and a version
number. Some Web browsers have bugs in how they handle the optional
attributes, so use them sparingly to improve the interoperability of your
servlets.

The servlet sends cookies to the browser by using the


HttpServletResponse.addCookie(javax.servlet.http.Cookie) method, which
adds fields to HTTP response headers to send cookies to the browser,
one at a time. The browser is expected to support 20 cookies for each
Web server, 300 cookies total, and may limit cookie size to 4 KB each.

197
Session Management

Http is a stateless protocol.

In some applications, it is necessary to save state information, so that


information can be collected from several interactions between a
browser and a server.

Sessions provide such a mechanism. An HttpSession object can be used


to hold the conversational state across multiple requests(from the same
client).

A session can be created via the getSession() method of


HttpServletRequest.

Version 2.0 198

The HttpSession interface is implemented by services to provide an


association between an HTTP client and HTTP server. This association,
or session, persists over multiple connections and/or requests during a
given time period. Sessions are used to maintain state and user identity
across multiple page requests.

A session can be maintained either by using cookies or by URL


rewriting. To expose whether the client supports cookies, HttpSession
defines an isCookieSupportDetermined method and an isUsingCookies
method.

198
Session Management (Contd.).

HttpSession Methods:

§ request.getSession() is used for creating a session object. It will


always return a session object. If there is no session object, it will
create a new session. If a Session Object already exists, it will return
the same.
§ request.getSession(false) is used for an existing session object. It
returns only an existing session object. In case it does not exist, it
will return null.
§ request.setAttribute(String, object) is used for setting an attribute.
§ request.getAttribute(String) is used for reading an attribute.

Version 2.0 199

HTTP is a stateless protocol. This provides some degree of anonymity,


since it does not provide web servers with a way to recognize that a
sequence of requests are being sent from the same browser. However,
many web applications, such as shopping carts, are not stateless. The
web server needs to keep track of each user's state, such as the items in a
user's shopping cart. The solution to this problem is for the browser to
identify itself when it makes a request.

199
Some common techniques of doing this are to implement one of the
following techniques:

•user authorization - The web server is configured to require every


user to enter a username and password to access its pages. The
browser remembers this information, and returns it every time the
user visits a page on the site. This requires each user to have an
account, and for the server to maintain a list of usernames and
passwords.

•hidden form fields - Extra information is added to HTML forms


as they are being generated. This value is then returned to the
browser when the user submits the form. Unfortunately, this
approach only works for a sequence of dynamically-generated
forms.

•URL rewriting - Additional path information or extra parameters


are added to every local URL. The information is usually limited to
a unique identifier, and can be tedious to implement.

•persistent cookies - A cookie is a piece of information (usually


limited to 4096 bytes) sent to the browser by the server. The
browser saves it on its machine and sends it back to the server
every time it accesses a page on the server. Cookies can provide an
easy and efficient method of session tracking; unfortunately, many
browsers do not accept them.

All of the above methods of session tracking are supported by servlets.

200
Lab Setup Guide

Software required : JDK 1.5 and above, Tomcat 5 or above


Directory Structure for the Web Application :
Let us name our Web Application root as Green-Bank. All the files and
folders related to our web application will be stored under this folder,
the structure of which is given below :
Green-Bank

WEB-INF HTML and JSP files

web.xml lib classes

jar files java classes

Version 2.0 201

201
Lab Setup Guide (Contd.).

The entire application i.e. the folder Green-Bank along with its files and
sub-folders should be placed within the following directory.

C:\Program File\Apache Software Foundation\


Tomcat 5.0\webapps

Steps for executing the application:


1. Set the classpath variable to point to servlet.api for compiling the
servlet program
2. Ensure all the classes related with servlets are compiled and stored
in the appropriate directory(within classes directory or a package
within it)
3. Store HTML/JavaScript files directly under application root
4. Create the web.xml file and store it within WEB-INF directory

Version 2.0 202

202
Lab Setup Guide (Contd.).

Steps for starting Tomcat Service:

Select
Start Menu -> Programs -> Apache Tomcat 5 -> Monitor Tomcat

You will get an icon in the System tray. Click on the Tomcat icon. You
will get a Dialog box. Click on the Start button

How to run the application:

Open the browser and type the following URL to display the Web App
HTML Page(or whatever is your starting interface for the app)

http://localhost:<port-no.>/<app root folder name>/<html file name>

E.g., http://localhost:8080/Green-Bank/login.html
Version 2.0 203

203
Example 1

The example shows how a servlet processes the inputs from an HTML
page.

Version 2.0 204

204
Example 1: Handling Form data

HTML
-------------------------------------------------------------------------------------
<SCRIPT language="javascript">

function IsEmpty()
{
var x = document.login.username.value;
if(x.length==0)
{
alert("Please Enter User Name\n");
return false;
}
else
return true;
}
</script>
<form name="login" action="Ex1" method="post" >
<body bgcolor="blue" >
<table align="center" width="20%" >
<tr> <td>User Id</td><td> <input type="text" name="username"
value=""></td></tr>
<tr><td><input type="submit" name="submit" align="center"
value=“Submit" onClick=“return IsEmpty();" ></td></tr>
</table>
</form>
-------------------------------------------------------------------------------------

205
Servlet
-------------------------------------------------------------------------------------
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class Ex1 extends HttpServlet


{
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
String username = req.getParameter("username");
try
{
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println("<html>");
writer.println("<head><title>Simple
Servlet Program Demo</title></head>");
writer.println("<body>");
writer.println("<h1>Hello, "+
username + "</h1>");
writer.println("Thank you,
"+username+". You are now logged into the system.");
writer.println("</body></html>");
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

-------------------------------------------------------------------------------------

206
Deployment Descriptor(web.xml)
-------------------------------------------------------------------------------------
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<display-name>Welcome to Hello screen</display-name>
<description>
Welcome to Hello Servlet
</description>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>Ex1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/Ex1</url-pattern>
</servlet-mapping>
</web-app>
-------------------------------------------------------------------------------------

207
Example 2

The example shows how a servlet processes the more than one input
from an HTML page and dispalys them on the screen. The code here
illustrates the use of getParameterNames() method.

Version 2.0 208

208
Example 2: Using getParameterNames()
method
HTML
index.jsp
-------------------------------------------------------------------------------------
<HTML>
<HEAD>
<H2 ALIGN="center" > Customer Registration</H2>
</HEAD>

<BODY bgcolor="blue">

<FORM NAME="Registration" ACTION="RegisterDisplay" METHOD="post" >


<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> First Name:</TD><TD><INPUT TYPE="text" name="cust_first_name"
></TD></TR>
<TR><TD> Last Name:</TD><TD><INPUT TYPE="text" name="cust_last_name"
></TD></TR>
<TR><TD>Address:</TD><TD>
<TEXTAREA NAME="addressbox" ROWS="5" COLS="15"
ALIGN="center"></TEXTAREA>
</TD></TR>

<TR><TD> City:</TD><TD><INPUT TYPE="text" name="city"></TD></TR>


<TR><TD> pin:</TD><TD><INPUT TYPE="text" name="pin" ></TD></TR>

<TR><TD>Profession:</TD><TD>
<SELECT NAME="Profession">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="Studying">Student</OPTION>
<OPTION VALUE="Employed">Employee</OPTION>
<OPTION VALUE="Businessman">SelfEmployed</OPTION>
</SELECT>

<TR><TD>Gender:</TD><TD>
Male:&nbsp;<INPUT TYPE="Radio" NAME="R1"
VALUE="M"/>&nbsp;&nbsp;Female:&nbsp;
<INPUT TYPE="Radio" NAME="R1" VALUE="F"/>

<TR><TD align="right"> <INPUT TYPE="submit" name="submit" value="Confirm


Details"></TD></TR>

</TABLE>

</FORM>
</BODY>
</HTML>

209
Servlet

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;

public class RegisterDisplay extends HttpServlet


{
int bal, amt;
String accnum, tran_type, tran_desc;
int accno;
boolean flag;
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
try
{
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println("<html>");
writer.println("<head><title>Servlet
for Printing HTML Form Entries</title></head>");
writer.println("<body
bgcolor='yellow'>");
writer.println("<font face='times
roman' size='5' color='blue'>");
//Get enumeration of parameter
names
Enumeration e =
req.getParameterNames();
//display parameter names and their
values
while(e.hasMoreElements())
{
String pname =
(String) e.nextElement();
String pvalue =
req.getParameter(pname);

writer.println(pname+" : "+pvalue);

writer.println("<BR>");
}
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

--------------------------------------------------------------------------------------------------------------------------------

210
Deployment Descriptor(web.xml)

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


<web-app>
<display-name>Welcome to Display screen</display-name>
<description>
Welcome to Display Example
</description>
<servlet>
<servlet-name>RegDisp</servlet-name>
<servlet-class>RegisterDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegDisp</servlet-name>
<url-pattern>/RegisterDisplay</url-pattern>
</servlet-mapping>
</web-app>

211
Example 3

The example shows how to store cookies and how to retrieve them.

Version 2.0 212

212
Example 3: Using Cookies
Login.html

<SCRIPT language="javascript">
function IsEmpty()
{
var x = document.login.username.value;
if(x.length==0)
{
alert("Please Enter User Name\n");
return false;
}
else
{
if(document.login.password.value==0)
{
alert("Please Enter
Password\n");
return false;
}
else
return true;
}
}
</script>
<form name="login" action="C1" method="get" >
<body bgcolor="green" >
<h1><center><font color="red">Green Bank</font></center><br><br>
<table align="center" width="20%" >
<tr> <td>User Id</td><td> <input type="text" name="username"
value=""></td></tr>
<tr><td>Password</td><td> <input type="password" name="password"
value=""></td></tr>
<tr><td><input type="submit" name="submit" align="center"
value="Login" onClick="return IsEmpty();" ></td></tr>
</table>
</form>

-------------------------------------------------------------------------------------

213
GeneralForm.html

<html>
<form name="searchcustAcc" action="C2" method="get">
<body bgcolor="blue">
<table align="center" >
<tr><td >Click on the Button Below to view the cookie details </td></tr>
<tr><td align="center"><input type="submit" name="Cookie" value="Display
Cookies"></td></tr>
</table>
</form>
</html>

-------------------------------------------------------------------------------------

214
C1.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class C1 extends HttpServlet


{
Connection con;
Statement st;
ResultSet rs;
int s1;
String s2,s3,s4;
public void init(ServletConfig config) throws ServletException
{
try
{

Class.forName("oracle.jdbc.driver.OracleDriver");

con=DriverManager.getConnection("Jdbc:Oracle:thin:@EC2LC-
17883:1521:orcl","scott","tiger");
}
catch(Exception e)
{
System.out.println("\nError :"+e);
e.printStackTrace();
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
String u = req.getParameter("username");
int uid = Integer.parseInt(u);
String password = req.getParameter("password");
int flag=0;
try
{
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println("<html>");
writer.println("<head><title>Simple
Cookie Demo</title></head>");
writer.println("<body>");
st=con.createStatement();
rs=st.executeQuery("Select * from
bankuser where userid="+uid);
if(!rs.next())

215
{
writer.println("<h1>The
user "+ u + "does not exist</h1>");
flag=1;
}
else
{
s1=rs.getInt(1);
s2=rs.getString(2);
s3=rs.getString(3);
s4=rs.getString(4);
if(s4.equals("A"))
{

if(s2.equals(password))
{

rs=st.executeQuery("Select fname,lname from user_personal_info where


userid="+uid);

if(rs.next())

String fn=rs.getString(1);

String ln=rs.getString(2);

Cookie c = new Cookie("firstname", fn);

res.addCookie(c);

c = new Cookie("lastname", ln);

res.addCookie(c);

res.sendRedirect("GeneralForm.html");

else
{

writer.println("<h1> Authentication failed due to incorrect password</h1>");


}
}
else
{

writer.println("The user account is disabled");


}
}

writer.println("</body></html>");
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

216
C2.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class C2 extends HttpServlet


{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// print out cookies
String title = "Active Cookies";
out.println("<HTML>\n" +"<HEAD><TITLE>" + title
+ "</TITLE></HEAD>\n" +"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n"
+"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +" <TH>Cookie
Name\n" +" <TH>Cookie Value");
Cookie[] cs = req.getCookies();
if (cs == null)
{
out.println("<TR><TH
COLSPAN=2>No cookies");
}
else
{
Cookie cook;
for(int i=0; i<cs.length; i++)
{
cook = cs[i];
out.println("<TR>\n"
+" <TD>" + cook.getName() + "\n" +" <TD>" + cook.getValue());
}
}
}
}

-------------------------------------------------------------------------------------

217
web.xml

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


<web-app>
<display-name>Welcome to the world of cookies</display-name>
<description>
Welcome to Login
</description>

<servlet>
<servlet-name>auth</servlet-name>
<servlet-class>C1</servlet-class>
</servlet>
<servlet>
<servlet-name>cookie</servlet-name>
<servlet-class>C2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>auth</servlet-name>
<url-pattern>/C1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>cookie</servlet-name>
<url-pattern>/C2</url-pattern>
</servlet-mapping>
</web-app>

218
Case Study : Banking Application

A simple example showing how the user is authenticated using a


servlet:

The user logs in using an HTML page. The user is authenticated based
on the input he/she provides (viz: username and password). These
parameters are accepted by the servlet and it uses a JDBC connection
to verify the username and password stored in the database.

Version 2.0 219

219
HTML

<SCRIPT language="javascript">
function IsEmpty()
{
var x = document.login.username.value;
if(x.length==0)
{
alert("Please Enter User Name\n");
return false;
}
else
{
if(document.login.password.value==0)
{
alert("Please Enter Password\n");
return false;
}
else
return true;
}
}
</script>
<form name="login" action="Ex2" method="post" >
<body bgcolor="green" >
<h1><center><font color="red">Green Bank</font></center><br><br>
<table align="center" width="20%" >
<tr> <td>User Id</td><td> <input type="text" name="username"
value=""></td></tr>
<tr><td>Password</td><td> <input type="password" name="password"
value=""></td></tr>
<tr><td><input type="submit" name="submit" align="center" value="Login"
onClick="return IsEmpty();" ></td></tr>
</table>
</form>
--------------------------------------------------------------------------------------------------------------------------------

220
Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class Ex2 extends HttpServlet


{
Connection con;
Statement st;
ResultSet rs;
int s1;
String s2,s3,s4;
ServletConfig config;

public void init(ServletConfig config) throws ServletException


{
this.config=config;
try
{

Class.forName("oracle.jdbc.driver.OracleDriver");

con=DriverManager.getConnection("Jdbc:Oracle:thin:@EC2LC-
17883:1521:orcl","scott","tiger");
}
catch(Exception e)
{
System.out.println("\nError :"+e);
e.printStackTrace();
}
}

public void doPost(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
{
String u = req.getParameter("username");
int uid = Integer.parseInt(u);
String password = req.getParameter("password");
int flag=0;
ServletContext sc = config.getServletContext();
String z = sc.getInitParameter("admin-email");
try
{
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println("<html>");
writer.println("<head><title>Simple
Servlet Program Demo</title></head>");
writer.println("<body>");
writer.println("For any problem with
the application, mail to : "+z);
st=con.createStatement();
rs=st.executeQuery("Select * from
bankuser where userid="+uid);
if(!rs.next())

221
{

writer.println("<h1>The user "+ u + "does not exist</h1>");


flag=1;
}
else
{
s1=rs.getInt(1);
s2=rs.getString(2);
s3=rs.getString(3);
s4=rs.getString(4);
if(s4.equals("A"))
{

if(s2.equals(password))

writer.println("<h1> The user is authenticated </h1>");


else
{

writer.println("<h1> Authentication failed due to incorrect


password</h1>");

flag=1;
}
}
else
{

flag=1;

writer.println("The user account is disabled");


}

}
if(flag==0)
{
HttpSession session=
req.getSession();

session.setAttribute("userid", u);
writer.println("Thank
you, "+u+". You are now logged into the system.");
if(s3.equals("A"))

res.sendRedirect("managerform.html" );
else

222
{

if(s3.equals("S"))

res.sendRedirect("staffform.html");
else

res.sendRedirect("custform.html");
}
}
writer.println("</body></html>");
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

223
web.xml

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


<web-app>
<display-name>Welcome to Banking App</display-name>
<description>
Welcome to Green Bank
</description>
<servlet>
<servlet-name>second</servlet-name>
<servlet-class>Ex2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/Ex2</url-pattern>
</servlet-mapping>
</web-app>

224
Case Study : Banking Application (Contd.).

Once the customer logs in, based on the type(Administrator, Staff or


User), appropriate pages will be displayed.

An administrator can enter new customer details. The code for the
HTML form and the servlet to process and store the new customer
details is explained.

Version 2.0 225

managerform.html

<html>
<h1 align="center">Administrator</h1>
<body bgcolor="blue">
<form name="manager" >
<center>
<input type="button" name="newcustomer" value="Create new
Customer" onClick=
window.open('newcustomerregistration.html')><br><br>
</center>
</form>
</html>

-----------------------------------------------

225
newcustomerregistration.html

<SCRIPT language="javascript">
function checkAcctypeselection()
{
if(document.Registration.acc_type.value=="Select")
{
alert("Please Select Account Type");
document.Registration.user_password.value="";
return false;
}
}

function pinCheck()
{
if(document.Registration.pin.value.length != 6)
{
alert("Pin code should be of Six Digit")
return lsefa;
}
}

function IsEmpty()
{
if(document.Registration.cust_first_name.value.length==0)
{
alert("Please Enter First Name\n");
return false;
}
if(document.Registration.cust_last_name.value.length==0)
{
alert("Please Enter Last Name\n");
return false;
}

if(document.Registration.user_password.value.length==0)
{
alert("Please Enter password \n");
return false;
}

var pass=document.Registration.user_password.value;
if(document.Registration.confirm_password.value!=pass)
{
alert("Confirmed password is not matching \n");
return false;
}

if(document.Registration.city.value.length==0)

226
{
alert("Please Enter City Name\n");
return false;
}

if(document.Registration.pin.value.length==0)
{
alert("Please Enter pin Code\n");
return false;
}

if(document.Registration.email.value.length==0)
{
alert("Please Enter Email\n");
return false;
}
else
return true;
}
</script>

<HTML>
<HEAD>
<H2 ALIGN="center" > Customer Registration</H2>
</HEAD>

<BODY bgcolor="blue">

<FORM NAME="Registration" ACTION="Register" METHOD="post" ;">


<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> First Name:</TD><TD><INPUT TYPE="text" name="cust_first_name"
></TD></TR>
<TR><TD> Last Name:</TD><TD><INPUT TYPE="text" name="cust_last_name"
></TD></TR>
<TR><TD>Account No:</TD><TD><INPUT TYPE="text" name="Acc_no"
disabled="true" value= "auto Generated" ></TD></TR>

<TR><TD>Account Type:</TD><TD>
<SELECT NAME="acc_type">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="S">SB</OPTION>
<OPTION VALUE="C">Current</OPTION>
</SELECT>

<TR><TD>Customer ID:</TD><TD><INPUT TYPE="text" name="cust_ID"


disabled="true" value= "auto Generated"></TD></TR>
<TR><TD>Password:</TD><TD><INPUT TYPE="password"
name="user_password" onChange="return
checkAcctypeselection();"/></TD></TR>
<TR><TD>Confirm Password:</TD><TD><INPUT TYPE="password"
name="confirm_password"/></TD></TR>

</TD></TR>
<TR><TD>Address:</TD><TD>
<TEXTAREA NAME="addressbox" ROWS="5" COLS="15"
ALIGN="center"></TEXTAREA>
</TD></TR>

227
<TR><TD> City:</TD><TD><INPUT TYPE="text" name="city"/></TD></TR>
<TR><TD> pin:</TD><TD><INPUT TYPE="text" name="pin" onChange="return
pinCheck();"/></TD></TR>

<TR><TD>Profession:</TD><TD>
<SELECT NAME="Profession">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="Studying">Student</OPTION>
<OPTION VALUE="Employed">Employee</OPTION>
<OPTION VALUE="Businessman">SelfEmployed</OPTION>
</SELECT>

<TR><TD>eMail:</TD><TD><INPUT TYPE="text" name="email"/></TD></TR>


<TR><TD>Gender:</TD><TD>
Male:&nbsp;<INPUT TYPE="Radio" NAME="R1"
VALUE="M"/>&nbsp;&nbsp;Female:&nbsp;
<INPUT TYPE="Radio" NAME="R1" VALUE="F"/>

</TD></TR>
<TR ><TD size ="2">DOB:</TD><TD>Date
<SELECT NAME="dob">
<OPTION VALUE="01">01</OPTION>
<OPTION VALUE="02">02</OPTION>
<OPTION VALUE="03">03</OPTION>
<OPTION VALUE="04">04</OPTION>
<OPTION VALUE="05">05</OPTION>
<OPTION VALUE="06">06</OPTION>
<OPTION VALUE="07">07</OPTION>
<OPTION VALUE="08">08</OPTION>
<OPTION VALUE="09">09</OPTION>
<OPTION VALUE="10">10</OPTION>
<OPTION VALUE="11">11</OPTION>
<OPTION VALUE="12">12</OPTION>
<OPTION VALUE="13">13</OPTION>
<OPTION VALUE="14">14</OPTION>
<OPTION VALUE="15">15</OPTION>
<OPTION VALUE="16">16</OPTION>
<OPTION VALUE="17">17</OPTION>
<OPTION VALUE="18">18</OPTION>
<OPTION VALUE="19">19</OPTION>
<OPTION VALUE="20">20</OPTION>
<OPTION VALUE="21">21</OPTION>
<OPTION VALUE="22">22</OPTION>
<OPTION VALUE="23">23</OPTION>
<OPTION VALUE="24">24</OPTION>
<OPTION VALUE="25">25</OPTION>
<OPTION VALUE="26">26</OPTION>
<OPTION VALUE="27">27</OPTION>
<OPTION VALUE="28">28</OPTION>
<OPTION VALUE="29">29</OPTION>
<OPTION VALUE="30">30</OPTION>
<OPTION VALUE="31">31</OPTION>

</SELECT>

228
<TD size ="3" >Month
<SELECT NAME="month">
<OPTION VALUE="JAN" SELECTED="SELECTED">1</OPTION>
<OPTION VALUE="FEB">2</OPTION>
<OPTION VALUE="MAR">3</OPTION>
<OPTION VALUE="APR">4</OPTION>
<OPTION VALUE="MAY">5</OPTION>
<OPTION VALUE="JUN">6</OPTION>
<OPTION VALUE="JUL">7</OPTION>
<OPTION VALUE="AUG">8</OPTION>
<OPTION VALUE="SEP">9</OPTION>
<OPTION VALUE="OCT">10</OPTION>
<OPTION VALUE="NOV">11</OPTION>
<OPTION VALUE="DEC">12</OPTION>
</SELECT>

<TD size ="2">year


<SELECT NAME="year">

<OPTION VALUE="1948">1948</OPTION>
<OPTION VALUE="1949">1949</OPTION>
<OPTION VALUE="1950">1950</OPTION>
<OPTION VALUE="1951">1951</OPTION>
<OPTION VALUE="1952">1952</OPTION>
<OPTION VALUE="1953">1953</OPTION>
<OPTION VALUE="1954">1954</OPTION>
<OPTION VALUE="1955">1955</OPTION>
<OPTION VALUE="1956">1956</OPTION>
<OPTION VALUE="1957">1957</OPTION>
<OPTION VALUE="1958">1958</OPTION>
<OPTION VALUE="1959">1959</OPTION>
<OPTION VALUE="1960">1960</OPTION>
<OPTION VALUE="1961">1961</OPTION>
<OPTION VALUE="1962">1962</OPTION>
<OPTION VALUE="1963">1963</OPTION>
<OPTION VALUE="1964">1964</OPTION>
<OPTION VALUE="1965">1965</OPTION>
<OPTION VALUE="1966">1966</OPTION>
<OPTION VALUE="1967">1967</OPTION>
<OPTION VALUE="1968">1968</OPTION>
<OPTION VALUE="1969">1969</OPTION>
<OPTION VALUE="1970">1970</OPTION>
<OPTION VALUE="1971">1971</OPTION>
<OPTION VALUE="1972">1972</OPTION>
<OPTION VALUE="1973">1973</OPTION>
<OPTION VALUE="1974">1974</OPTION>
<OPTION VALUE="1975">1975</OPTION>
<OPTION VALUE="1976">1976</OPTION>
<OPTION VALUE="1977">1977</OPTION>
<OPTION VALUE="1978">1978</OPTION>
<OPTION VALUE="1979">1979</OPTION>
<OPTION VALUE="1980">1980</OPTION>
<OPTION VALUE="1981">1981</OPTION>
<OPTION VALUE="1982">1982</OPTION>
<OPTION VALUE="1983">1983</OPTION>
<OPTION VALUE="1984">1984</OPTION>

229
<OPTION VALUE="1985">1985</OPTION>
<OPTION VALUE="1986">1986</OPTION>
<OPTION VALUE="1987">1987</OPTION>
<OPTION VALUE="1988">1988</OPTION>
<OPTION VALUE="1989">1989</OPTION>
<OPTION VALUE="1990">1990</OPTION>
</SELECT>
<TR><TD align="right"> <INPUT TYPE="submit" name="submit"
onClick="return IsEmpty();" value="Confirm Details"></TD></TR>

</TABLE>
</FORM>
</BODY>
</HTML>

230
Servlet

Register.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;

public class Register extends HttpServlet


{
int i;
Connection con;
Statement st;
ResultSet rs;
int userid, accno, lastuserid, lastaccno;
String query1 = "Select max(userid) from bankuser";
String query2 = "Select max(accno) from account_info_table";
ServletConfig config;

public void init(ServletConfig config) throws ServletException


{
this.config = config;
try
{

Class.forName("oracle.jdbc.driver.OracleDriver");

con=DriverManager.getConnection("Jdbc:Oracle:thin:@EC2LC-
17883:1521:orcl","scott","tiger");
}
catch(Exception e)
{
System.out.println("\nError :"+e);
e.printStackTrace();
}
}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException
{
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
String y = config.getInitParameter("msg");

writer.println("<html>");
writer.println("<head><title>Servlet Program for inserting
user details</title></head>");
writer.println("<body bgcolor='pink'>");
writer.println(y);

try

231
{
st = con.createStatement();
rs = st.executeQuery(query1);
if(rs.next())
lastuserid =
rs.getInt(1);
userid = lastuserid + 1;

st = con.createStatement();
rs = st.executeQuery(query2);
if(rs.next())
lastaccno =
rs.getInt(1);
accno = lastaccno + 1;

String
fname=req.getParameter("cust_first_name");
String
lname=req.getParameter("cust_last_name");
String
acctype=req.getParameter("acc_type");
String password =
req.getParameter("user_password");
String address =
req.getParameter("addressbox");
String city = req.getParameter("city");
String pin = req.getParameter("pin");
String profession =
req.getParameter("Profession");
String emailid =
req.getParameter("email");
String gender = req.getParameter("R1");
String day = req.getParameter("dob");
String month =
req.getParameter("month");
String year = req.getParameter("year");
String date =
(day+"/"+month+"/"+year);

st= con.createStatement();
i = st.executeUpdate("insert into
bankuser values("+userid+",'"+password+"','U','A')");

st = con.createStatement();
i= st.executeUpdate("insert into
account_info_table values("+userid+" , "+accno+" , '"+acctype+"', 0)");

st = con.createStatement();
i = st.executeUpdate("insert into
user_personal_info values("+userid+",'"+fname+"','"+ lname +"','"+emailid+"','"+ gender
+"','"+ date +"','"+address+"','"+city+"','"+pin+"','"+profession+"')");

writer.println("<h1>The details for the


user have been added successfully..!</h1>");
}

232
{
writer.println("<h1>The details have not
been updated due to some operation problem..!</h1>");
System.out.println("\nError :"+e);
e.printStackTrace();
}
}
}

----------------------------------------------------------------------

233
Case Study : Banking Application

A staff member can deposit or withdraw cash on behalf of the customer


based on his/her account number.
Each of these transactions are stored in the table.
bankusertransaction. The account_info_table maintains one
record which always stores the current/latest balance for that particular
account. These details are updated in the appropriate table using the
servlet and the model class(AccountOperation) given below.
Http being a stateless protocol, when multiple interactions happen
between the same customer and the server, the account no which is
entered by the staff member in the first form is not available when the
deposit/withdrawal information is entered. So the account no. is stored
as an attribute in an HttpSession object.

Version 2.0 234

Staffform.html

<script language="javascript">
function IsEmpty()
{
if(document.searchcustAcc.AccountNumber.value.length==0)
{
alert("Please Enter Customer Account Number\n");
return false;
}
if(isNaN(document.searchcustAcc.AccountNumber.value))
{
alert(" Account No should be a Number \n");
return false;
}
else
return true;
}
</script>

<form name="searchcustAcc" action="Ex3" method="get">


<body bgcolor="blue">
<table align="center" >
<tr><td >Customer Account Number </td> <td><input type="text"
name="AccountNumber" value=""></td>
<td><input type="submit" name="searchId" value=">>>" onClick=“return
IsEmpty();"></td></tr>
</table>
</form>

234
Amount-entry-deposit.html

<SCRIPT language="javascript">
function IsEmpty()
{
if(document.amountentry.depositamount.value.length==0)
{
alert("Please Enter the amount");
return false;
}
if(isNaN(document.amountentry.depositamount.value))
{
alert("Invalid Entry \n");
return false;
}
}
</script>
<form name="amountentry" action="Ex4" method="post">
<table name="depositscreen" ALIGN="Center" CELLSPACING="2"
CELLPADDING="2">
<body bgcolor="Blue">
<tr><td>Enter Amount</td><td> <input type="text" name="depositamount" >
</td></tr>
<tr><td> <input type="submit" ALIGN="Center" value="submit" onClick=“return
IsEmpty();" > </td></tr>
</table>
</form>
----------------------------------------------------------------------------------------------------------
Amount-entry-withdraw.html

<SCRIPT language="javascript">
function IsEmpty()
{
if(document.amountentry.withdrawamount.value.length==0)
{
alert("Please Enter the amount");
return false;
}
if(isNaN(document.amountentry.withdrawamount.value))
{
alert("Invalid Entry \n");
return false;
}
}
</script>
<form name="amountentry" action="Ex4" method="post">
<table name="depositscreen" ALIGN="Center" CELLSPACING="2"
CELLPADDING="2">
<body bgcolor="Blue">
<tr><td>Enter Amount</td><td> <input type="text" name="withdrawamount" >
</td></tr>
<tr><td> <input type="submit" ALIGN="Center" value="submit"
onClick="IsEmpty();" > </td></tr>
</table>
</form>
--------------------------------------------------------------------------------------------------------------------------------

235
Servlets

Example 3.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class Ex3 extends HttpServlet


{
Connection con;
Statement st;
ResultSet rs;
int x, bal;
int accnum;
String acc, type, acctype;
ServletConfig config;

public void init(ServletConfig config) throws ServletException


{
this.config=config;
try
{

Class.forName("oracle.jdbc.driver.OracleDriver");

con=DriverManager.getConnection("Jdbc:Oracle:thin:@EC2LC
-17883:1521:orcl","scott","tiger");
}
catch(Exception e)
{System.out.println("\nError :"+e);
e.printStackTrace();}
}

public void doGet(HttpServletRequest req,


HttpServletResponse res) throws ServletException, IOException
{
acc = req.getParameter("AccountNumber");
accnum = Integer.parseInt(acc);
HttpSession session= req.getSession();
session.setAttribute("accountno", acc);
int flag=0;
ServletContext sc = config.getServletContext();
String z = sc.getInitParameter("admin-email");
String y = config.getInitParameter("msg");
try

236
{
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println("<html>");
writer.println("<head><title>Simple
Servlet Program Demo</title></head>");
writer.println("<body>");
writer.println(y);
st=con.createStatement();
rs=st.executeQuery("Select
acc_type, current_balance from account_info_table where accno="+accnum);
if(!rs.next())
{

writer.println("<h1>The account "+ accnum + "does not


exist</h1>");
flag=1;
}
else
{
type=rs.getString(1);
bal=rs.getInt(2);
if(type.equals("S"))

acctype="Savings";
else

acctype="Current";

writer.println("<body
bgcolor ='red'></body>");

writer.println("<table
BORDER=' ' WIDTH='50%' CELLSPACING='2' CELLPADDING='2' align='center'>");

writer.println("<th><tr><td bgcolor='blue'> Account Number


</td>");
writer.println("<td
bgcolor='blue'> Account Type </td>");
writer.println("<td
bgcolor='blue'>Amount Balance </td></tr></th><br>");

writer.println("<tr><td bgcolor='white'>"+accnum+" </td> <td


bgcolor='white'>"+acctype+" </td> <td bgcolor='white'>" +bal+"
</td></tr><br></table><BR><BR><BR><BR>");

writer.println("<CENTER><input type='button' name='Deposit'


value='Deposit' onClick=window.open('amount-entry-deposit.html')>");

writer.println("<input type='button' name='Withdrawal'


value='Withdrawal' onClick=window.open('amount-entry-withdraw.html')><br>");
}
writer.println("</body></html>");
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

237
Example 4.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class Ex4 extends HttpServlet


{
int bal, amt;
String accnum, tran_type, tran_desc;
int accno;
AccountOperation ao;
boolean flag;

public void doPost(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException
{
ao=new AccountOperation();
HttpSession session=req.getSession();
ServletContext sc = getServletConfig().getServletContext();
String z = sc.getInitParameter("admin-email");

String s1=req.getParameter("depositamount");
String s2=req.getParameter("withdrawamount");
accnum=(String)session.getAttribute("accountno");
accno=Integer.parseInt(accnum);
if (s1!=null)
{
tran_type="C";
tran_desc="Deposit";
amt=Integer.parseInt(s1);
}
else
if(s2!=null)
{
tran_type="D";
tran_desc="Withdrawal";
amt=Integer.parseInt(s2);
}

flag=ao.depositWithdraw(accno, tran_type, tran_desc, amt);

res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println("<html>");
writer.println("<head><title>Servlet Program for
Updation</title></head>");
writer.println("<body bgcolor='pink'>");
writer.println("For any problem with the application, mail to :
"+z);
if (flag==true)
writer.println("<h1>The details have been
updated successfully..!</h1>");
else
writer.println("<h1>The details have not
been updated due to some operation problem..!</h1>");
}
}

238
Model class

AccountOperation.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class AccountOperation
{
Connection con;
Statement st;
PreparedStatement pstmt;
ResultSet rs,rs1,rs2;
int x, bal, currbal;
String insertqry="insert into bankusertransaction values(?, ?, ?,
sysdate, ?, ?)";
public AccountOperation()
{
try
{

Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Inside Init after
class.forname");

con=DriverManager.getConnection("Jdbc:Oracle:thin:@EC2LC-
17883:1521:orcl","scott","tiger");
}
catch(Exception e)
{
System.out.println("\nError :"+e);
e.printStackTrace();
}
}
public boolean depositWithdraw(int accnum, String tran_type, String
tran_desc, int amt)
{
int flag=0;
try

239
{

pstmt=con.prepareStatement(insertqry);
pstmt.setInt(1, accnum );
pstmt.setString(2, tran_desc );
pstmt.setString(3, tran_type);
pstmt.setInt(4, amt);
st=con.createStatement();
rs=st.executeQuery("Select
current_balance from account_info_table where accno="+accnum);
if(rs.next())
bal=rs.getInt(1);
if (tran_type=="C")
currbal=bal+amt;
else
currbal=bal-amt;
pstmt.setInt(5, currbal);
pstmt.executeUpdate();
pstmt.close();

pstmt=con.prepareStatement("update account_info_table set


current_balance=? where accno="+accnum);
pstmt.setInt(1, currbal);
pstmt.executeUpdate();
return true;

}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
}

240
web.xml

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


<web-app>
<display-name>Welcome to Banking App</display-name>
<description>
Welcome to Green Bank
</description>

<servlet>
<servlet-name>auth</servlet-name>
<servlet-class>Ex2</servlet-class>
</servlet>
<servlet>
<servlet-name>staff</servlet-name>
<servlet-class>Ex3</servlet-class>
</servlet>
<servlet>
<servlet-name>tran</servlet-name>
<servlet-class>Ex4</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>auth</servlet-name>
<url-pattern>/Ex2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>staff</servlet-name>
<url-pattern>/Ex3</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tran</servlet-name>
<url-pattern>/Ex4</url-pattern>
</servlet-mapping>
</web-app>

241
Case Study : Banking Application

The customer can view his/her account details by providing the account
no.
The customer once logs in using his userid, can only view his/her
account details. If he/she tries to access other accounts, an error
message is displayed and he/she is asked to enter this account no.
again.

Version 2.0 242

Custform.html

<script language="javascript">
function IsEmpty()
{
if(document.searchcustAcc.AccountNumber.value.length==0)
{
alert("Please Enter Customer Account Number\n");
return false;
}
if(isNaN(document.searchcustAcc.AccountNumber.value))
{
alert(" Account No should be a Number \n");
return false;
}
else
return true;
}
</script>

<form name="searchcustAcc" action="Ex5" method="get">


<body bgcolor="blue">
<table align="center" >
<tr><td >Customer Account Number </td> <td><input type="text"
name="AccountNumber" value=""></td>
<td><input type="submit" name="searchId" value=">>>"
onClick="IsEmpty();"></td></tr>
</table>
</form>

242
custinvalid.html

<script language="javascript">
function IsEmpty()
{
if(document.searchcustAcc.AccountNumber.value.length==0)
{
alert("Please Enter Customer Account
Number\n");
return false;
}
if(isNaN(document.searchcustAcc.AccountNumber.value))
{
alert(" Account No should be a Number \n");
return false;
}
else
return true;
}

</script>
<h2>You have no right to access this Account No. Please enter YOUR
Account No....!
<br><br>

<form name="searchcustAcc" action="Ex5" method="get">


<body bgcolor="blue">
<table align="center" >

<Tr><td >Customer Account Number </td> <td><input type="text"


name="AccountNumber" value=""></td>
<td><input type="submit" name="searchId" value=">>>"
onClick="IsEmpty();"></td></tr>
</table>
</form>

243
Servlets

Example 5.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class Ex5 extends HttpServlet


{
Connection con;
Statement st;
ResultSet rs;
int accnum;
String acc, uid;

public void init(ServletConfig config) throws ServletException


{
try
{

Class.forName("oracle.jdbc.driver.OracleDriver");

con=DriverManager.getConnection("Jdbc:Oracle:thin:@EC2LC
-17883:1521:orcl","scott","tiger");
}
catch(Exception e)
{
System.out.println("\nError
:"+e);
e.printStackTrace();
}
}

public void doGet(HttpServletRequest req,


HttpServletResponse res) throws ServletException, IOException
{
acc = req.getParameter("AccountNumber");
accnum = Integer.parseInt(acc);
HttpSession session= req.getSession();
uid = (String)session.getAttribute("userid");
try

244
{
st = con.createStatement();
rs = st.executeQuery("Select *
from account_info_table where userid = "+uid+" and accno="+accnum);
if(!rs.next())

res.sendRedirect("custinvalid.html");
else
{
RequestDispatcher
view = req.getRequestDispatcher("Ex6");
view.forward(req,
res);
}
}
catch(SQLException e)
{
System.out.println(e);
}
}
}

----------------------------------------------------------------------------------------

245
Example 6.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class Ex6 extends HttpServlet


{
Connection con;
Statement st;
ResultSet rs;
int x, bal;
int accnum;
String acc, type, acctype;
ServletConfig config;

public void init(ServletConfig config) throws ServletException


{
this.config=config;
try
{

Class.forName("oracle.jdbc.driver.OracleDriver");

con=DriverManager.getConnection("Jdbc:Oracle:thin:@EC2LC
-17883:1521:orcl","scott","tiger");
}
catch(Exception e)
{
System.out.println("\nError
:"+e);
e.printStackTrace();
}
}

public void doGet(HttpServletRequest req,


HttpServletResponse res) throws ServletException, IOException
{
acc = req.getParameter("AccountNumber");
accnum = Integer.parseInt(acc);
ServletContext sc = config.getServletContext();
String z = sc.getInitParameter("admin-email");
String y = config.getInitParameter("msg");
int flag=0;
try

246
{
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println("<html>");
writer.println("<head><title>Simple
Servlet Program Demo</title></head>");
writer.println("<body>");
writer.println("For any problem with
the application, mail to : "+z);
writer.println("<BR>"+y);
st=con.createStatement();
rs=st.executeQuery("Select
acc_type, current_balance from account_info_table where accno="+accnum);
if(!rs.next())
{

writer.println("<h1>The account "+ accnum + "does not


exist</h1>");
flag=1;
}
else
{
type=rs.getString(1);
bal=rs.getInt(2);
if(type.equals("S"))

acctype="Savings";
else

acctype="Current";

writer.println("<body
bgcolor ='red'></body>");

writer.println("<table
BORDER=' ' WIDTH='50%' CELLSPACING='2' CELLPADDING='2' align='center'>");

writer.println("<th><tr><td bgcolor='blue'> Account Number


</td>");
writer.println("<td
bgcolor='blue'> Account Type </td>");
writer.println("<td
bgcolor='blue'>Amount Balance </td></tr></th><br>");

writer.println("<tr><td bgcolor='white'>"+accnum+" </td> <td


bgcolor='white'>"+acctype+" </td> <td bgcolor='white'>" +bal+"
</td></tr><br></table><BR><BR><BR><BR>");
}

writer.println("</body></html>");
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

247
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<display-name>Welcome to Hello screen</display-name>
<description>
Welcome to Login
</description>
<servlet>
<servlet-name>auth</servlet-name>
<servlet-class>Ex2</servlet-class>
</servlet>
<servlet>
<servlet-name>staff</servlet-name>
<servlet-class>Ex3</servlet-class>
</servlet>
<servlet>
<servlet-name>tran</servlet-name>
<servlet-class>Ex4</servlet-class>
</servlet>
<servlet>
<servlet-name>RegDisp</servlet-name>
<servlet-class>RegisterDisplay</servlet-class>
</servlet>
<servlet>
<servlet-name>Reg</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet>
<servlet-name>cust</servlet-name>
<servlet-class>Ex5</servlet-class>
</servlet>
<servlet>
<servlet-name>custcheck</servlet-name>
<servlet-class>Ex6</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>auth</servlet-name>
<url-pattern>/Ex2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>staff</servlet-name>
<url-pattern>/Ex3</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tran</servlet-name>
<url-pattern>/Ex4</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Reg</servlet-name>
<url-pattern>/Register</url-pattern>

248
</servlet-mapping>
<servlet-mapping>
<servlet-name>RegDisp</servlet-name>
<url-pattern>/RegisterDisplay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>cust</servlet-name>
<url-pattern>/Ex5</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>custcheck</servlet-name>
<url-pattern>/Ex6</url-pattern>
</servlet-mapping>
</web-app>

249
Summary

In this module you have learnt to:


§ Describe the role of HTTP Servlet in Web Programming
§ Describe and use the Servlet Life Cycle methods appropriately
§ Process parameters from HTML forms
§ Establish Database Connectivity through servlets
§ Maintain Http Sessions in Servlets

Version 2.0 250

250
Module 5:
Java Beans

Copyright © 2008, Wipro Limited, Bangalore

251
Java Beans

The lessons covered in this module include:


§ Software Component Assembly Model
§ Java’s Approach to developing Software Components
§ Difference between a bean and a normal class

Version 2.0 252

252
Objectives

At the end of this module you will be able to:


§ Describe the Software Component Assembly Model
§ Explain Java’s approach to developing software components
§ Describe the essential prerequisites for developing Java Beans
§ Create an application using the Bean Box
§ Develop a simple Bean

Version 2.0 253

253
The Software Component Assembly Model

Monolithic Application

Module1

Module2 Module3

Version 2.0 254

Until some years ago programs for various application systems were
written in languages like ‘COBOL’, ‘C’ and ‘C++’. Software programs
using the aforesaid languages had to be written from scratch. Sometimes
you may want to use a piece of code from one program into another
program. However, you cannot do this using the aforesaid languages, as
the code in one program may not blend with the code in another
program. It led to inconsistency between two programs. Moreover,
various modules (code snippets) in an application are tightly integrated
with each other. A change in one module could cause a ripple effect on
other modules as well. The programmer had to make several changes in
order to make code from one application compatible with another
application. All this led to longer development time. Also, there was no
reusability and interoperability between different programs.
Such applications are called ‘Monolithic Applications’. Any change or
enhancement to the modules without affecting other modules is very
difficult.

254
The Software Component Assembly Model (Contd.).

An Application based on the software component


assembly model

Module1

Module2
Module5

Module3
Module4

Version 2.0 255

There was not a single application development model where software


programs or modules, each representing a specific functionality could be
readily assembled into applications. Consider the hardware assembly
model where different components are assembled and made into a
product. Various components are already available in the market. All that
the manufacturer has to do is to pick up the components of his
specifications, assemble them, make some changes or enhancements if
necessary and the product is ready. For example when a PC is
manufactured, different components like the monitor, the keyboard, the
mouse, the CPU, the motherboard, the cables, and the drives are
assembled and integrated. However, the PC manufacturer may not
manufacture every component, as the components are readily available
in the market. All that one has to do is to select these components
according to one’s requirement and assemble them. He/she need not
bother about how the other parts are manufactured.

255
Using readymade components not only speeds up the manufacturing
process but also simplifies it. Unfortunately, in the software industry
there was no concept of software components that could be purchased
off-the-shelf and assembled into custom applications.
Therefore, keeping in mind the hardware component assembly model,
the programming community decided to develop software components
that could be readily assembled and integrated into applications. The
emphasis was on software components that could be assembled and
tailored according to the specific requirement of the applications. This
not only ensured reusability but also led to faster application
development.

256
Components and Containers

Container 1

Container 2

Container
Container 3

Component 1 Component 3
Component 4

Component 2
Component 5

Version 2.0 257

The software component assembly model is based on components and


containers.
Software components are designed with the intention of maximum
reusability. Software components can be visible GUI components like
buttons or labels, or invisible algorithmic components as well. An
example of invisible component could be an algorithm to calculate your
income tax. You have to supply the information about your income and
the deductibles, and your tax will be calculated. Another example of
invisible Bean would be to establish a connection to the database. You
can develop a connection component that takes user name, password and
data source name, and automatically establishes a connection to the
database.
Containers are components that contain other components. A container
is used as a framework for visually organizing components. Visual
development tools enable you to drag and drop components into a
container and tailor them according to their requirement.

257
Java’s Approach to Developing Software
Components

Java Beans are reusable software Component that can be integrated to


create software applications.

A Bean can be visual or Non Visual.

Components written in other languages can be integrated with Java


components using a special interface.

Version 2.0 258

The Java Bean Technology is the software component architecture in


Java. It is an exciting technology that enables a programmer to efficiently
construct applications by configuring and integrating software
components called ‘Beans’.
Java Beans are reusable software components that can be integrated to
create software applications.
Any type of Java object can be implemented as a Java Bean. Java Bean
components are not restricted to the Visual components.
Components written in other languages can be integrated with Java
components using a special interface.
The Java Beans component model supports the hierarchical software
development approach. Simple components can be assembled to produce
complex components. This allows you to make maximum reuse of the
existing software components.

258
The Difference between a Bean and a Normal Class

public class Circle {


private float radius;

// the getter method


public float getRadius() {
return radius;
}
// the setter method
public void setRadius(float r) {
radius = r;
}

Version 2.0 259

A Bean class is like any other class in Java. Then what is it that makes a
class a Bean? Beans must exhibit certain features, which a normal class
may avoid. Some of the features that distinguish a Bean from a normal
class are:
Beans must supply a zero-argument constructor that a normal class may
avoid
Beans must provide accessor methods to properties, which a normal
class may not.
Beans must supply a zero-argument constructor
Upon creation, how the Bean will look like is specified in the default
constructor. That is, the initial properties of the Bean are specified in the
default constructor. Therefore, the Bean class must provide a default
constructor. Later, the user can change these properties.
Beans Must Provide Accessor Methods to Properties
Beans do not have public member variables. The Bean properties are
specified as private member variables. Therefore, a Bean class must
provide accessor methods to read and write the Bean properties.

259
Module 6:
Java Server Pages

Copyright © 2008, Wipro Limited, Bangalore

260
Java Server Pages

The lessons covered in this module include:


§ What is JSP?
§ The Architecture
§ Elements of JSP
§ Cookies
§ Session Management

Version 2.0 261

261
Objectives

At the end of this module you will be able to:


§ Distinguish JSP architecture vis-à-vis servlets
§ Define and use the basic JSP Elements
§ Create and use Java Beans
§ Work with Cookies
§ Define Session Tracking and use the same in JSPs

Version 2.0 262

262
What is JSP?

JSP stands for Java Server Pages, a technology invented by Sun, which
allows easy creation and maintenance of server side HTML pages.

JSP can be used as both a kind of Dynamic HTML and CGI


Replacement.

Version 2.0 263

263
JSP: JSP Request Model

Version 2.0 264

The above picture brings a perspective on where JSP fits in the 3-tier web
application architecture.

JSP lies in the presentation tier on the web server, with the main
responsibility of generating HTML content that needs to be served to the
browser. It also has the additional responsibility of pass on the requests
to the backend through the JavaBeans, as and when required.

264
JSP: What makes JSP so attractive?

JSP offers higher performance than CGI.

JSP’s feautres make it convenient to code and maintain as against


servlets; allowing the user to create their own utility, or business logic
classes.

JSP can make a complete separation of presentation (HTML) from


code (content – Java)

JSP is powered by Java and has access to all Java APIs and J2EE APIs
and has inherent Platform independence.

Version 2.0 265

265
JSP: JSP compared to ASP

Similarities:
§ Both provide built in session tracking
§ Designed to create interactive pages in a Web application
§ Separate presentation logic from programming logic

Differences:
§ JSPs are designed for Platform independence and server
independence
§ Open development process has come through the JCP (Java
Community Process) and hence has broader acceptance
§ JSP enables developers to extend the tags
§ JSP uses a full fledged language like Java for scripting while ASP
uses VBScript or Jscript, which are limited

Version 2.0 266

Both provide built in session tracking and management, and


sophisticated database interactions.
JSPs are built on Java, which is a much more advanced language than
VB.
JSP pages run on all platforms, not just IIS. ASP is inherently non
portable.
JSP goes for easier maintenance as it uses Java and not scripting which is
tough to maintain as the code grows
JSP technology emphasizes on components over scripting. It is easier to
revise content without affecting logic or change logic without changing
content.
Because JSP technology is an open, cross-platform architecture, Web
servers, platforms, and other components can be easily upgraded or
switched without affecting JSP-based applications. This makes JSP
suitable for real-world Web applications, where constant change and
growth is the norm

266
The Architecture

Version 2.0 267

Typically HTTP requests are sent to the web server from a browser
client. If the request if for a static HTML page, the web server itself
responds. However, if the request is for a JSP or a servlet, the add-ons to
a web server viz. servlet engine or JSP engine respond. These engines
require a JVM as, they are themselves Java-based.

267
The Architecture: The flow of JSP request

Version 2.0 268

The flow of a JSP request:


1. The HTTP request comes to a web server.
2. The server extension receives the request (as it is not a request for
static HTML but for a JSP) and passes it on to the JSP engine.
3. The JSP engine invokes the JSP parser to parse the JSP and check
for any syntax errors.
4. On successful parsing, the JSP engine invokes the Java compiler to
compile the JSP into an equivalent servlet class.
5. Once the class is generated, the control is passed on to a servlet
engine.
6. The servlet engine loads the servlet into memory using its class
loader.
7. The appropriate methods in the servlet are invoked and the response
is routed back to the browser via the server extension and web
server.

268
Methods of Generated Servlet Class

Generated Servlet equivalent Class has following Methods:


jspInit() :
The container calls the jspInit() to initialize the servlet instance. It is
called before any other method, and is called only once for a servlet
instance.

_jspservice():
The container calls this method for each request, passing it the request
and response object.

jspDestroy() :
The container calls this when it decides and take the instance out of
service. It is the last method called in the servlet instance.

Version 2.0 269

The generated servlet class for a JSP page implements the HttpJspPage
interface of the javax.servlet.jsp package. HttpJspPage interface
extends the JspPage interface which in turn extends the Servlet interface
of the javax.servlet package. The generated servlet class thus
implements all the methods of these three interfaces. The jspPage
interface declares only two mehtods - jspInit() and jspDestroy().
However the JSP specification has provided the HttpJspPage interface
specifically for the JSP pages serving HTTP requests. This interface
declares one method _jspService().

269
The Architecture: JSP Architecture Models

Sun specifies two different architectural models for building


applications using Servlet and JSP.

1. JSP Model 1 Architecture


2. JSP Model 2 Architecture

The difference between these two lies in the way they handle the
request.

Version 2.0 270

270
The Architecture: JSP Model 1 Architecture

Application Server
Client

1. Request

Browser JSP
4. Response

2. Creates
JavaBeans

3. Retrieves Data
JavaBeans

DB

Version 2.0 271

In the model1 architecture the target of every request is a JSP page. This
page is completely responsible for doing all the task required [to fulfill
the request. This includes authenticating the client, using Java Bean to
assess data, managing the state of the user, and so forth.

271
The Architecture: JSP Model 2 Architecture

Version 2.0 272

This architecture follows the Model-View-Controller design pattern. In


this architecture, the target of all requests is Servlet that acts as a
controller for the application. They analyze the request and collect all the
data required to generate a response into JavaBeans object, which act as
a model for the application. Finally the controller servlet dispatches the
request to the JSP page. This page uses the data stored in the JavaBeans
object to generate a presentable response. Thus the JSP page form a view
for the application.

272
Elements of JSP

There are three main types of JSP constructs that you embed in a page:
1. Scripting elements
2. Directives
3. Actions

Version 2.0 273

To simplify the scripting elements, you have access to a number of


predefined variables, discussed later.

273
Elements of JSP: Scripting Elements

Scripting elements lets you insert Java code into the servlet that will be
generated from the current JSP page.

There are three forms:


§ Expressions
§ Scriptlets
§ Declarations

Version 2.0 274

Expressions
Useful shorthand for printing out strings and contents of variables.

Scriptlets
Lets you insert any valid Java code into the JSP.

Declarations
Useful for declaring page wide variables and methods(Java) or functions.

274
Scripting Elements: Expressions

A JSP expression is used to insert Java values directly into the output.

It has the following form:

<%= Java Expression %>

Version 2.0 275

Expressions are used to insert Java values directly into the output.

It has the following form:


<%= Java Expression %>

The Java expression is evaluated, converted to a string, and inserted in


the page. This evaluation is performed at run-time (when the page is
requested), and thus has full access to information about the request.
For example, the following shows the date/time that the page was
requested: Current time: <%= new java.util.Date() %>
This evaluation is performed at run-time. To simplify these expressions,
there are a number of predefined variables that you can use. Some of the
important variables are discussed next.
Finally, note that XML authors can use an alternative syntax for JSP
expressions:
<jsp:expression>
Java Expression
</jsp:expression>

275
Example:

<HTML> <HEAD> <TITLE> Expressions </TITLE> </HEAD>


<BODY>
<TABLE BORDER=2>
<TR> <TH>Message</TH> <TH>Result</TH> </TR>
<TR> <TD>SQRT of 4</TD>
<TD> <%= Math.sqrt(2) %></TD> </TR>
<TR> <TD>Current time</TD>
<TD> <%= new java.util.Date() %></TD> </TR>
<TR> <TD>Your hostname</TD>
<TD> <%= request.getRemoteHost() %></TD> </TR>
<TR> <TD>Port :</TD>
<TD> <%= request.getServerPort() %></TD> </TR>
<TR> <TD>Scheme </TD>
<TD> <%= request.getScheme() %></TD> </TR>
<TR> <TD> Address</TD>
<TD> <%= request.getServerName() %></TD> </TR>
</TABLE>
</BODY>
</HTML>

276
Expressions: Pre-defined Variables

To simplify the expressions, there are a number of predefined variables


that you can use.

The most important ones are:


§ request
§ response
§ session
§ out

Version 2.0 277

Request: This is the HttpServletRequest associated with the request, and


lets you look at the request parameters (via getParameter), the request
type (GET, POST, HEAD, etc.), and the incoming HTTP headers (cookies,
Referrer, etc.). Strictly speaking, request is allowed to be a subclass of
ServletRequest other than HttpServletRequest, if the protocol in the
request is something other than HTTP. This is almost never done in
practice.

Response: This is the HttpServletResponse associated with the response


to the client. Note that, since the output stream is buffered, it is legal to
set HTTP status codes and response headers, even though this is not
permitted in regular servlets once any output has been sent to the client.

277
Session: This is the HttpSession object associated with the request. In
JSPs, sessions are created automatically, so this variable is bound even if
there was no incoming session reference. The one exception is if you use
the session attribute of the page directive to turn sessions off, in which
case, attempts to reference the session variable causes errors at the time
the JSP page is translated into a servlet.

Out: This is the PrintWriter used to send output to the client. However, in
order to make the response object useful, this is a buffered version of
PrintWriter called JspWriter. Note that you can adjust the buffer size, or
even turn buffering off, through use of the buffer attribute of the page
directive. Also note that out is used almost exclusively in scriptlets, since
JSP expressions automatically get placed in the output stream, and thus
rarely need to refer to out explicitly.

278
Scripting Elements: Scriptlets

Scriptlets are defined as any block of valid Java code that resides
between <% and %> tags.

Code that is defined within a scriptlet can access any variable and any
beans that have been declared.

Version 2.0 279

Scriptlets have access to the same automatically defined variables as


expressions. So, for example, if you want output to appear in the
resultant page, you would use the out variable.
Example: How to process form using Jsp:
<html>
<form name=“login action=“logintest.jsp” method=“post”>
<input type=“text” name=“username” >
<input type=“text” name=“password” >
<input type=“submit” name=“submit” value=“submit” >
</form>
</html>

logintest.jsp

<%
String user=request.getParameter(“username”);
String pass=request.getParameter(“password”);
out.println(user+” ”+pass);
%>

279
Scriptlets are like declarations in that they always use semicolons to end
statements and expressions. They can have multiple expressions and
statements as long as each is ended with a semicolon.
Scriptlets code goes into the service method of the JSP’s compiled servlet
which means it is executed only once when a request is actually serviced
by the JSP.
If you want to use the characters "%>" inside a scriptlet, enter "%\>"
instead.

Finally, note that the XML equivalent of <% Code %> is


<jsp:scriptlet>
Code
</jsp:scriptlet>

NOTE: Declarations are executed at initialization time; Expressions and


Scriptlets at request Time.

280
Scripting Elements: Declaration

A JSP declaration lets you define methods or fields that get inserted
into the main body of the servlet class (outside of the service method
processing the request). It has the following form:

<%! Java Code %>

The scope of a declaration is usually a JSP file, but if the JSP file
includes other files with the include directive, the scope expands to
cover the included files as well.

Version 2.0 281

Since declarations do not generate any output, they are normally used in
conjunction with JSP expressions or scriptlets. For example, here is a
JSP fragment that prints out the number of times the current page has
been requested since the server booted (or the servlet class was changed
and reloaded):
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= ++accessCount %>
As with scriptlets, if you want to use the characters "%>", enter "%\>"
instead. Finally, note that the XML equivalent of <%! Code %> is
<jsp:declaration>
Code
</jsp:declaration>

281
Example for declaration:

<%! ResultSet rs;


Connection con;
Statement stmt;
String pwd1,user,pwd2,passwordtype;
public void MakeConnection()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =
DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}
catch(Exception e)
{
System.out.println(e);
}
}
%>

282
Directives

A JSP directive affects the overall structure of the servlet class. It


usually has the following form:

<%@ directive attribute="value" %>

There are two main types of directive: page, which lets you do things
like import classes, customize the servlet superclass, and the like; and
include, which lets you insert a file into the servlet class at the time the
JSP file is translated into a servlet. The specification also mentions the
taglib directive, which is not supported in JSP version 1.0, but is
intended to let JSP authors define their own tags. Tags are supported
from JSP 1.1.

Version 2.0 283

However, you can also combine multiple attribute settings for a single
directive, as follows:
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>

EXAMPLE TO PROCESS New Customer Registration form in a


Banking Application:

(Reference: front end form newcustomerregistration.html)

registerconfirmation.jsp

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


<%@ page import ="accountgeneration.*"%>
<%!
ResultSet rs;
Connection con;
Statement stmt;
String userpassword,firstname,lastname,address,passwordtype;
String city,pin,profession,acctype,email,gender,day,month,year,dob;
int accno,custno;
public void MakeConnection()

283
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}
catch(Exception e)
{
System.out.println(e);
}
}
%>
<%
MakeConnection();
try
{
userpassword=request.getParameter("user_password");
firstname=request.getParameter("cust_first_name");
lastname=request.getParameter("cust_last_name");
acctype=request.getParameter("acc_type");
city=request.getParameter("city");
pin=request.getParameter("pin");
email=request.getParameter("email");
gender=request.getParameter("gender");
address=request.getParameter("addressbox");
accno=AccountAutogeneration.GenerateAcc();
custno=AccountAutogeneration.GenerateCustomerID();
String day=request.getParameter("day");
String month=request.getParameter("month");
String year=request.getParameter("year");
dob=(day+"-"+month+"-"+year);
stmt.executeUpdate("insert into cust_account_info
values("+custno+","+accno+",'"+acctype+"',"+0+")");
con.close();
stmt.close();
}

catch(Exception e)
{
out.println(e);
}
try
{
stmt = con.createStatement();
stmt.executeUpdate("insert into login
values("+custno+",'"+userpassword+"','c',"+1+")");
con.close();
stmt.close();
}

catch(Exception e)

284
{
out.println(e);
}
%>
<html>
<body bgcolor="lightGreen">
<center>
<h1><b> Sucessfully Created </b> <br></h1>
<h2><b> Customer Id <%=custno %></b> <br>
<b>Password <%=userpassword%><em></b></em><br>
<b>New Account Number<%=accno%></b>
</h2>
</center>

285
Directives: Page Directives

The page directive lets you define one or more of the following case-
sensitive attributes:
import="package.class" or
import="package.class1,...,package.classN". This lets you specify
what packages should be imported. For example:
<%@ page import="java.util.*" %>

Page Directives lets you do things like:


§ Import classes
§ Handle error messages
§ Define if the JSP is thread-safe
§ Define is session object is available
§ Set the page content type

Version 2.0 286

The import attribute is the only one that is allowed to appear multiple
times.
contentType="MIME-Type" or
contentType="MIME-Type; charset=Character-Set"
This specifies the MIME type of the output. The default is text/html. E.g.,
the directive <%@ page contentType="text/plain" %> has the same effect
as the scriptlet <% response.setContentType("text/plain"); %>
isThreadSafe="true|false". A value of true (the default) indicates normal
servlet processing, where multiple requests can be processed
simultaneously with a single servlet instance, under the assumption that
the author synchronized access to instance variables. A value of false
indicates that the servlet should implement SingleThreadModel, with
requests either delivered serially or with simultaneous requests being
given separate servlet instances.
session="true|false". A value of true (the default) indicates that the
predefined variable session (of type HttpSession) should be bound to the
existing session if one exists, otherwise a new session should be created
and bound to it. A value of false indicates that no sessions will be used,
and attempts to access the variable session will result in errors at the time
the JSP page is translated into a servlet.

286
Directives: The Include Directive

The Include directive inserts the contents of another file in the main
JSP file, where the directive is located.

It is useful for including copyright information, scripting language files,


or anything you might want to reuse in other applications

The included file can be an HTML file, a JSP file, a text file, or a code
file written in the Java programming language.

Version 2.0 287

This directive lets you include files at the time the JSP page is translated
into a servlet. The directive looks like this:
<%@ include file="relative url" %>
The URL specified is normally interpreted relative to the JSP page that
refers to it, but, as with relative URLs in general, you can tell the system
to interpret the URL relative to the home directory of the Web server by
starting the URL with a forward slash. The contents of the included file
are parsed as regular JSP text, and thus can include static HTML,
scripting elements, directives, and actions.

For example, many sites include a small navigation bar on each page.
Due to problems with HTML frames, this is usually implemented by way
of a small table across the top of the page or down the left-hand side, with
the HTML repeated for each page in the site. The include directive is a
natural way of doing this, saving the developers from the maintenance
nightmare of actually copying the HTML into each separate file.

287
Example:

Header.jsp
<center>
<img src="wipro.jpg" width=200 >
</center>

Footer.jsp
<center>
<img src="wipro2.jpg" width=200 >
</center>

login.jsp
<%@ include file=Header.jsp%>
<input type= “text” name =“user”>
<input type= “text” name =“password”>
<input type= “Submit” name =“sub” value=“submit”>
<%@ include file=Footer.jsp%>

288
Actions

JSP actions use constructs in XML syntax to control the behavior of the
servlet engine. You can dynamically insert a file, reuse JavaBeans
components, forward the user to another page, or generate HTML for
the Java plug-in. Available actions include:
§ jsp:include - Include a file at the time the page is requested
§ jsp:useBean - Find or instantiate a JavaBean
§ jsp:setProperty - Set the property of a JavaBean
§ jsp:getProperty - Insert the property of a JavaBean into the output
§ jsp:forward - Forward the requester to a new page
§ jsp:plugin - Generate browser-specific code that makes an OBJECT
or EMBED tag for the Java plug-in

Version 2.0 289

Remember that, as with XML in general, the element and attribute


names are case sensitive.

289
Actions: The jsp:include Action

This action lets you insert files into the page being generated.
The syntax looks like this:

<jsp:include page="relative URL"/>

Unlike the include directive, which inserts the file at the time the JSP
page is translated into a servlet, this action inserts the file at the time
the page is requested. This pays a small penalty in efficiency, and
precludes the included page from containing general JSP code (it
cannot set HTTP headers, for example), but it gains significantly in
flexibility.

Version 2.0 290

290
Actions: The jsp:forward Action

The jsp.forward action forwards a client request to an HTML file, JSP


file, or servlet for processing.

Syntax
<jsp:forward page= “relativeURL" />

It has a single attribute, page, which should consist of a relative URL.


This could be a static value, or could be computed at request time, as in
the two examples below.

<jsp:forward page="/utils/errorReporter.jsp" />

<jsp:forward page="<%= someJavaExpression %>" />

Version 2.0 291

Example: login Processing in a Banking Application

Dbconnection.jsp

<%!
ResultSet rs;
Connection con;
Statement stmt;
String pwd1,user,pwd2,passwordtype;
public void MakeConnection()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}
catch(Exception e)
{
System.out.println(e);
}
}
%>

291
Loginsubmit.jsp

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


<@ include file=“Dbconnection.jsp”>
<%
MakeConnection();
try
{
user=request.getParameter("username");
pwd1=request.getParameter("password");
rs = stmt.executeQuery("Select * from login WHERE user_id= "+ user);
if(rs.next()==false)
{
%>
<Center><h2>Invalid User</h2></center>
<jsp:include page="login.html"/>
<%
}
else
{
pwd2=rs.getString(2);
passwordtype=rs.getString(3);
int st=rs.getInt(4);

if(st==0)
{
%>
<Center><h2>Access is denied for this User</h2></center>
<jsp:include page="login.html"/>
<%
}
else
{
if(pwd2.equals(pwd1) )
{
session.setAttribute("username",(String)user);
if(passwordtype.equals("s"))
{
%>
<script language="javascript">
parent.top.location.href="staff.html";
</script>
<%
}

if(passwordtype.equals("m"))
{
%>
<script language="javascript">
parent.top.location.href="managerscreen.html";
</script>
<%
}

292
if(passwordtype.equals("c"))
{
%>
<script language="javascript">
parent.top.location.href="customerscreen.jsp";
</script>
<%
}
}
else
{
out.println(" <b>Wrong Password</b> "); %>
<jsp:include page="login.html"/>
<%
}
}
}
}
catch(SQLException e)
{
out.println(e+"aaa");
}
%>

293
Actions: The jsp:useBean Action

This action lets you load in a JavaBean to be used in the JSP page. This
is a very useful capability because it lets you exploit the reusability of
Java classes without sacrificing the convenience that JSP adds over
servlets. The simplest syntax for specifying that a bean should be used
is:
<jsp:useBean id="name" class="package.class" />

This usually means "instantiate an object of the class specified by


class, and bind it to a variable with the name specified by id.

Version 2.0 294

However, you can specify a scope attribute that makes the bean
associated with more than just the current page. In that case, it is useful
to obtain references to existing beans, and the jsp:useBean action
specifies that a new object is instantiated only if there is no existing one
with the same id and scope. Now, once you have a bean, you can modify
its properties via jsp:setProperty, or by using a scriptlet and calling a
method explicitly on the object with the variable name specified earlier
via the id attribute. Recall that with beans, when you say "this bean has a
property of typeX called foo", you really mean "this class has a method
called getFoo that returns something of type X, and another method
called setFoo that takes an X as an argument." The jsp:setProperty action
is discussed in more detail in the next section, but for now note that you
can either supply an explicit value, give a param attribute to say that the
value is derived from the named request parameter, or just list the
property to indicate that the value should be derived from the request
parameter with the same name as the property. You read existing
properties in a JSP expression or scriptlet by calling the appropriate
getXxx method, or more commonly, by using the jsp:getProperty action.

294
MVC example:
Below example checks the Customer Account Status in a bank
Application
customernumber-entry-form.html

<script language="javascript">
function IsEmpty()
{
var acno=document.searchcust.customerno.value;
if(acno==0)
{
alert("Please Enter Customer Account Number\n");
return false;
}

if(isNaN(acno))
{
alert("Customer Number Should Be numeric\n");
document.searchcust.customernor.value="";
return false;
}
return true;
}
</script>

<form name="searchcust" action="customerrecord" method="post">


<body bgcolor="LightSeaGreen">
<table align="center" >
<Tr><td > EnterCustomer Number</td> <td><input type="text"
name="customerno" value=""></td>
<td><input type="submit" name="searchId" value="Confirm"
onClick="return IsEmpty();"></td></tr>
</table>

</form>

295
//Controler

SearchCustomerNo.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import model.*;
public class SearchCustomerNo extends HttpServlet
{
String custno;
PrintWriter writer;
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException
{
try
{
res.setContentType("text/html");
writer = res.getWriter();
custno = req.getParameter("customerno");

ModelDB m=new ModelDB();

ResultSet rs= m.getRecordSet(custno);


req.setAttribute("record", rs);
RequestDispatcher view =
req.getRequestDispatcher("customer-account-view.jsp");
view.forward(req, res);

writer.close();
}
catch(Exception e)
{
writer.println(e);
}
}
}

296
//Model class

ModelDB.java

package model;

import java.sql.*;
public class ModelDB
{
Connection con;
Statement stmt;
ResultSet rs;
public ModelDB()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=
DriverManager.getConnection("Jdbc:Odbc:green","scott","tiger");
stmt = con.createStatement();
}
catch(Exception e)
{
System.out.println(e);
}
}
public ResultSet getRecordSet(String custno)
{
try
{
rs=stmt.executeQuery("Select * from cust_account_info
where user_id="+custno);
}

catch(Exception e)
{
System.out.println(e);
}
return rs;
}
}

297
customer-account-view.jsp

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


<%!
ResultSet rs1,rs2;
String UserName,FirstName,LastName;
String Accno;
%>
<%
try
{
rs1=(ResultSet)request.getAttribute("record");

%>

<body bgcolor ="DarkSalmon"></body>


<form name="transaction" action="" method="post">
<table BORDER="" WIDTH="50%" CELLSPACING="2" CELLPADDING="2"
align="center">
<th><tr><td bgcolor="blue"> Account Number </td>
<td bgcolor="blue"> Account Type </td>
<td bgcolor="blue">Amount Balance </td><td bgcolor="blue">Mini
Statement</td></tr></th>
<br>
<%
while(rs1.next())
{
Accno=rs1.getString("account_no");
%>
<tr><td bgcolor="white"><%=Accno%> </td> <td
bgcolor="white"><%=rs1.getString("account_type")%> </td><td
bgcolor="white"> <%=rs1.getInt("current_balance")%> </td><td
bgcolor="white"> <a target="_blank" href="customer-
accountwisedetail.jsp?acno=<%=Accno%>">
<b>View</b></a></td></tr>
<br>
<%
}
rs1.close();
}//try close

catch(Exception e)
{
out.println(e);
}
%>
</table>
</form>

298
// databse connectivity
dbconnection.jsp

<%!
ResultSet rs1,rs2,rs3;
Connection con;
Statement stmt;
int acno, balance;
String userid;
String Accno;

public void MakeConnection()


{

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");

stmt = con.createStatement();

}
catch(Exception e)
{

System.out.println(e);
}
}
%>

299
customer-accountwisedetail.jsp
<%@ page import ="java.sql.*"%>
<%@ include file="dbconnection.jsp"%>
<%
MakeConnection();
try
{

String Accno=request.getParameter("acno");

acno=Integer.parseInt(Accno);

rs1=stmt.executeQuery("select * from cust_account_info where


account_no="+acno);
rs1.next();
userid=rs1.getString("user_id");
balance=rs1.getInt("current_balance");
rs1.close();
stmt.close();
}
catch(Exception e)
{
out.println(e);
}
try
{
stmt = con.createStatement();
rs2=stmt.executeQuery("select * from cust_personal_info where user_id="+userid);
rs2.next();
String FirstName=rs2.getString("firstname");
String LastName=rs2.getString("lastname");
rs2.close();
stmt.close();
%>
<CENTER><b>Customer name: <%=FirstName%> <%=LastName%><br>
Customer ID:<%=userid%><br>
Balance : <%=balance%><br></b>
</CENTER>
<body bgcolor ="DarkSalmon"></body>
<form name="transaction" action="" method="post">
<table BORDER="" WIDTH="50%" CELLSPACING="2" CELLPADDING="2"
align="center">
<th><tr><td bgcolor="blue"> Account Number </td>
<td bgcolor="blue"> Description </td>
<td bgcolor="blue">Amount </td><td bgcolor="blue">Transaction Type</td> <td
bgcolor="blue">Transaction Date</td> <td bgcolor="blue">Closing balanace</td>
</tr></th>
<br>
<%
stmt = con.createStatement();
rs3=stmt.executeQuery("select * from transaction where account_no="+acno);

while(rs3.next())

300
{
%>
<tr><td bgcolor="white"><%=acno%> </td> <td
bgcolor="white"><%=rs3.getString("description")%> </td> <td
bgcolor="white"><%=rs3.getInt("amount")%><td
bgcolor="white"><%=rs3.getString("transaction_type")%> </td><td
bgcolor="white"><%=rs3.getString("transaction_date")%> </td>
</td><td bgcolor="white"> <%=rs3.getInt("closing_balance")%>
</td></tr>
<%
}
rs3.close();

}//try close
catch(Exception e)
{
out.println(e);
}
%>
</table>
<input type="button" name="close" value="Close"
onClick="window.close();">
</form>

301
<jsp:getProperty>

This element retrieves the value of a bean property, converts it to a


string, and inserts it into the output.
The two required attributes are name (the name of a bean previously
referenced via jsp:useBean), and property (the property whose value
should be inserted).

name="beanInstanceName"
The name of the Bean instance as declared in a <jsp:useBean> tag

property="propertyName"
The name of the Bean property whose value you want to display

Version 2.0 302

<jsp:useBean id="itemBean" ... />


...
<UL>
<LI>Number of items:
<jsp:getProperty name="itemBean" property="numItems" />
<LI>Cost of each:
<jsp:getProperty name="itemBean" property="unitCost" />
</UL>

302
<jsp:setProperty>

You use jsp:setProperty to give values to properties of beans that have


been referenced earlier.

Syntax:
<jsp:setProperty name="beanInstanceName"
property= "*" |
property="propertyName" [param=parameterName" ] |
property= "propertyName"
value="{ string | <%= expression %> }" } />

Version 2.0 303

You can do this in two contexts. First, you can use jsp:setProperty after,
but outside of, a jsp:useBean element, as below:
<jsp:useBean id="myName" ... />
...
<jsp:setProperty name="myName"
property="someProperty" ... />
In this case, the jsp:setProperty is executed regardless of whether a new
bean was instantiated or an existing bean was found. A second context in
which jsp:setProperty can appear is inside the body of a jsp:useBean
element, as below:
<jsp:useBean id="myName" ... >
...
<jsp:setProperty name="myName"
property="someProperty" ... />
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated,
not if an existing one was found.

303
Properties of JSP:setProperty

1. name
2. property
3. value
4. param

Version 2.0 304

name: This required attribute designates the bean whose property will
be set. The jsp:useBean element must appear before the jsp:setProperty
element.

property: This required attribute indicates the property you want to set.
However, there is one special case: a value of "*" means that all request
parameters whose names match bean property names will be passed to
the appropriate setter methods.

value: This optional attribute specifies the value for the property. String
values are automatically converted to numbers, boolean to Boolean, byte
to Byte, char to Character via the standard valueOf method in the target
or wrapper class. For example, a value of "true" for a boolean or Boolean
property will be converted via Boolean.valueOf, and a value of "42" for an
int or Integer property will be converted via Integer.valueOf. You can't use
both value and param, but it is permissible to use neither.

param: This optional attribute designates the request parameter from


which the property should be derived. If the current request has no such
parameter, nothing is done: the system does not pass null to the setter
method of the property. Thus, you can let the bean itself supply default
values, overriding them only when the request parameters say to do so.

304
Example:
Below Code Shows how to Deposit a amount in a Banking
Application

Deposit-set.html

(Deposit Form )

<SCRIPT language="javascript">
function IsEmpty()
{ if(document.depositentry.amount.value.length==0)
{
alert("Please Enter the amount");
return false;
}
if(isNaN(document.depositentry.amount.value))
{
alert(" amount Should be numeric");
document.depositentry.amount.value="";
return false;
}
alert("you Are Depositing The Money ! Are You sure");
return true;
}
</script>
<form name="depositentry" action="deposit-set-submit.jsp"
method="post" >
<table name="depositscreen" ALIGN="Center" CELLSPACING="2"
CELLPADDING="2">
<body bgcolor="Cyan3">
<tr><td>Enter Description</td><td> <input type="text"
name="description" > </td></tr>
<tr><td>Enter Account No</td><td> <input type="text"
name="accountno" > </td></tr>
<tr><td>Enter Amount</td><td> <input type="text" name="amount" >
</td></tr>
<tr><td><input type="submit" ALIGN="Center" value="submit"
onClick="return IsEmpty();"></td></tr>
</table>
</form>

305
deposit-set-submit.jsp

<jsp:useBean id="Bean" class="deposit.updateamount"


scope="application"/>
<jsp:setProperty name="Bean" property="*"/>

<! –
Bean Elements can be read as follows
<jsp:getProperty name="Bean" property="accountno"/>
<jsp:getProperty name="Bean" property="amount"/>
-->
<%
request.setAttribute("Beanname",(deposit.updateamount)Bean);
%>
<jsp:forward page="updatetable.jsp"/>
…………………………………………………………………………………………………………
………………
File name: updatetable.jsp

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


<%@ page import ="java.util.*"%>
<%@ page import="deposit2.*"%>
<%@ page import="deposit.*"%>
<%
try
{
deposit.updateamount bean2 =
(deposit.updateamount)request.getAttribute("Beanname");
UpdateAccount u = new UpdateAccount();
int p= u.UpdateRecord(bean2);
out.println("Successfully Updated: Current balance is -Rs”+p);
}
catch(Exception e)
{
out.println(e +"err");
}

%>

306
store it in a Package deposit

File name: Updateamount.java

package deposit;
public class updateamount
{
private String accountno;
private String amount;
public updateamount()
{
accountno="1";
amount="1000";
}
public void setaccountno(String acno)
{
accountno=acno;
}
public void setamount(String amt)
{
amount=amt;
}
public String getaccountno()
{
return accountno;
}
public String getamount()
{
return amount;
}
}

307
Store it in a package called deposit2

updateAccount.java

package deposit2;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import deposit.*;
public class UpdateAccount extends HttpServlet
{
ResultSet rs;
Connection con;
Statement stmt;
String acctype;
PreparedStatement stmt2;

int customerno,bal;
int acno;

public UpdateAccount()
{

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}

catch(Exception e)
{
System.out.println("e");
}

}
public int UpdateRecord(updateamount amt)
{
try
{
String accno= amt.getaccountno();
acno=Integer.parseInt(accno);
rs = stmt.executeQuery("Select * from cust_account_info WHERE
account_no="+acno);
rs.next();
bal=rs.getInt("current_balance");

308
System.out.println(bal);
String depamt= amt.getamount();
int depositamount =Integer.parseInt(depamt);
bal=bal + depositamount;
rs.close();
stmt.close();
}
catch(Exception e)
{
System.out.println(e);
}

try
{
stmt2 = con.prepareStatement("update cust_account_info set
current_balance=? where account_no like?");
stmt2.setInt(1,bal);
stmt2.setInt(2,acno);
stmt2.executeUpdate();
}
catch(Exception e)
{
System.out.println(e);
}
return bal;
}
}

Note: Package must be store in a webapps/WEB-INF/classes folder

309
Cookies

Cookies are small bits of textual information that a Web server sends to
a browser and that the browser returns unchanged when visiting the
same Web site or domain later. Cookies allow the web server to store
small pieces of data on the client that can be sent back to the server on
subsequent page requests. By having the server read information it sent
the client previously, the site can provide visitors with a number of
conveniences.
Cookies are often used to store user IDs or basic configuration
Information.
To read cookies from the browser, use the request.getCookies()
Function.

Version 2.0 310

Identifying a user during an e-commerce session. Many on-line


stores use a "shopping cart" metaphor in which the user selects an item,
adds it to his shopping cart, then continues shopping. Since the HTTP
connection is closed after each page is sent, when the user selects a new
item for his cart, how does the store know that he is the same user that
put the previous item in his cart? Cookies are a good way of
accomplishing this. In fact, this is so useful that servlets have an API
specifically for this, and servlet authors don't need to manipulate cookies
directly to make use of it.

Avoiding username and password. Many large sites require you to


register in order to use their services, but it is inconvenient to remember
the username and password. Cookies are a good alternative for low-
security sites. When a user registers, a cookie is sent with a unique user
ID. When the client reconnects at a later date, the user ID is returned, the
server looks it up, determines it belongs to a registered user, and doesn't
require an explicit username and password.

Customizing a site. Many "portal" sites let you customize the look of
the main page. They use cookies to remember what you wanted, so that
you get that result initially next time.

310
Example to check last login date and time
when you login as staff in a Bank application
(Refer login.html and loginsubmit.jsp for login process)

Staffhome.jsp

<form name="staff" action="logout.jsp" method=post>


<center>
<body bgcolor="LightCyan"><h1> STAFF</h1><br>
<%
Cookie[] k=null;
java.util.Date dt=new java.util.Date();//current Date and time
String lastdate=dt.toString();
try
{
k=request.getCookies(); //get All the existing cookies
for(int i=0;i<k.length;i++)
{
if((k[i].getName()).equals("staffCookie")) //search for cookie name
staffCookie
{
String value = k[i].getValue();
out.println("<br><b> Last Login : </b>"+value);
}
}
}

catch(Exception e)
{
out.println(e);
}

out.println("<br><b>Curent Time: </b>"+lastdate);


Cookie ck = new Cookie("staffCookie",lastdate); // setting a new Value
to a cookie
ck.setMaxAge(36000);
response.addCookie(ck);
%>
<br><b> You have logged in As
:<%=(String)session.getAttribute("username")%></b><br>
<br>
<em>You are authorised to access Valued Customer Account</em><br>
<br><input type ="submit" name="logout" value="LogOut">
</center>
</form>

311
Session Management

JSP maintains session through the HttpSession object.

Session information is stored on the server, and a session ID number is


stored in a cookie on the client machine.

Sessions are usually set by server default to expire after 30 minutes of


user inactivity.

Version 2.0 312

There are a number of problems that arise from the fact that HTTP is a
"stateless" protocol. As discussed previously, cookies are one way of
maintaining connectivity between the requests from the same browser.

A more robust mechanism is provided by the HttpSession object that is


part of the servlet API and is available to JSPs as a predefined ‘session’
object.

The HttpSession interface is implemented by services to provide an


association between an HTTP client and HTTP server. This association,
or session, persists over multiple connections and/or requests during a
given time period. Sessions are used to maintain state and user identity
across multiple page requests.

Recall from the page directive that the session object is created by default
and is available to the JSP unless explicitly turned off.

312
Example to Understand Session
bankname.jsp
<HTML>
<HEAD> <TITLE> First Page </TITLE> </HEAD>
<BODY>
<FORM METHOD=POST ACTION=“custid.jsp">

What is your Bank Name?


<INPUT TYPE=TEXT NAME="bank">
<P>
<INPUT TYPE=SUBMIT VALUE="SUBMIT">
</FORM>
</BODY> </HTML>

custid.jsp

<HTML> <HEAD> <TITLE> Page 2 </TITLE> </HEAD>


<BODY>
<%! String name=""; %>
<%
name = request.getParameter("bank");
session.putValue("bankname", name);
%>

The name is <%= name %>


<p>

<FORM METHOD=POST ACTION=“bank.jsp">

What is your Customer ID


<INPUT TYPE=TEXT NAME="custid">
<P>
<INPUT TYPE=SUBMIT VALUE="SUBMIT">
</FORM>
</BODY>
</HTML>

313
bank.jsp

<HTML> <HEAD> <TITLE> Page 3 </TITLE> </HEAD>


<BODY>

<%! String name="";


String CustId="";
%>
<%
CustId = request.getParameter("custid");
name = (String) session.getValue("bankname");
%>
Your Bank name is <b><%= name %></b>
<P>
Your Customer ID is <b><%= CustId %></b>

</BODY> </HTML>

314
Summary

In this module you have learnt to:


1. Distinguish JSP architecture vis-à-vis servlets
2. Define and use the basic JSP Elements
3. Create and use Java Beans
4. Work with Cookies
5. Define Session Tracking and use the same in JSPs

Version 2.0 315

315
Case Study : Banking Application

The examples given in the subsequent slides/pages illustrate how JSP


can be used in a Banking Application.

The example given below shows how a JSP processes the inputs from
an HTML page.

Version 2.0 316

316
Case Study : Banking Application

Example showing how the user is authenticated using a JSP.

The user logs in using an HTML page. The user is authenticated based
on the input he provides (viz: username and password). These
parameters are accepted by the JSP and it uses a JDBC connection to
verify the username and password stored in the database.

Version 2.0 317

main-loginpage.html
(this is a mail login page uses the frame, which comprise login
page and general information html pages)
<FRAMESET ROWS="25%,75%">
<FRAME SRC="background1.html" NAME="left"/>
<FRAMESET COLS="25%,75%">
<FRAME SRC="login.html" NAME="left" />
<FRAME SRC="background2.html" NAME="right"
bgcolor="blue"/>
</FRAMESET>
</FRAMESET>

317
Login.html

<SCRIPT language="javascript">
function IsEmpty()
{
var x = document.login.username.value;
if(x.length==0)
{
alert("Please Enter User Name\n");
return false;
}
if(isNaN(x))
{
alert("UserName Should Be numeric\n");
document.login.username.value="";
document.login.password.value="";
return false;
}
if(document.login.password.value==0)
{
alert("Please Enter Password\n");
return false;
}
else
return true;
}
</script>

<form name="login" action="loginsubmit.jsp" method="post">


<body bgcolor="blue" >
<table align="center" width="20%" >
<tr> <td>User Id</td><td> <input type="text" name="username"
value=""></td></tr>
<tr><td>Password</td><td> <input type="password" name="password"
value=""></td></tr>
<tr><td><input type="submit" name="submit" align="center" onClick="return
IsEmpty();" value="Login" ></td></tr>
</table>
</form>

318
Loginsubmit.jsp
(this jsp page authenticating the login)

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


<%! ResultSet rs;
Connection con;
Statement stmt;
String pwd1,user,pwd2,passwordtype;
public void MakeConnection()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}
catch(Exception e)
{
System.out.println(e);
}
}
%>
<%
MakeConnection();
try
{
user=request.getParameter("username");
pwd1=request.getParameter("password");
rs = stmt.executeQuery("Select * from login WHERE user_id= "+ user);
if(rs.next()==false)
{
%>
<Center><h2>Invalid User</h2></center>
<jsp:include page="login.html"/>
<%
}
else
{
pwd2=rs.getString(2);
passwordtype=rs.getString(3);
int st=rs.getInt(4);

if(st==0)

319
{
%>
<Center><h2>Access is denied for this User</h2></center>
<jsp:include page="login.html"/>
<%
}

else
{
if(pwd2.equals(pwd1) )
{
session.setAttribute("username",(String)user);
if(passwordtype.equals("s"))
{
%>
<script language="javascript">
parent.top.location.href="staff3.html";
</script>
<%
}

if(passwordtype.equals("m"))
{
%>
<script language="javascript">
parent.top.location.href="managerscreen.html";
</script>
<%
}
if(passwordtype.equals("c"))

320
{
%>
<script language="javascript">
parent.top.location.href="customerscreen.jsp";
</script>
<%
}
}
else
{
out.println(" <b>Wrong Password</b> "); %>
<jsp:include page="login.html"/>
<%
}
}
}
}

catch(SQLException e)
{
out.println(e);
}
%>

321
Case Study : Banking Application

Once the customer logs in, based on the type(manager, Staff or


Customer), appropriate pages will be displayed.
Manager can:
§ Create new customer along with necessary details
§ Create New Account For Existing Customer
§ Disable the Customer

Code for the Creation of New Customer Details is as follows:

Version 2.0 322

Managerscreen.html
(when user logs as manager he will get this screen at the
beginning)

<Frameset cols="40%,*">
<frame src ="managerhome.jsp" name="left">
<frame src = "empty.html" name="right">
</frameset>

322
managerhome.jsp

<h1 align="center"> Manager</h1>


<body bgcolor="DeepSkyBlue">
<form name="manager" action="logout.jsp" method="post">
<center>
<br><b> You have logged in As
:<%=(String)session.getAttribute("username")%></b><br>
<br>

<!– Below code is get existing Cookie and to create new cookie to set
login time for the existing User so that user can see when he logged last
time -->
<%
Cookie[] k=null;
java.util.Date dt=new java.util.Date();

String lastdate=dt.toString();
try
{
k=request.getCookies();
for(int i=0;i<k.length;i++)
{
if((k[i].getName()).equals("managerCookie"))
{
String value = k[i].getValue();
out.println("<br><b> Last Login : </b>"+value);
}
}
}
catch(Exception e)
{
out.println(e);
}

out.println("<br><b>Curent Time: </b>"+lastdate);

Cookie ck = new Cookie("managerCookie",lastdate);


ck.setMaxAge(36000);
response.addCookie(ck);
%>
<! – End of cookie code -- >

323
<br>
<br>
<input type="radio" color="red" name="manager" value="new
Customer" onClick=
"parent.right.location.href='newcustomerregistration.jsp'"><b>Create
new Customer</b><br><br>
<input type="radio" name="manager" value="new Account" onClick=
"parent.right.location.href='newaccount-for-old-
customer.html'"><b>Create new Account</b><br><br>
<input type="radio" name="manager" value="Remove Customer"
onClick= "parent.right.location.href='delete-account.html'"
><b>Remove Customer</b><br><br>
<input type="radio" name="manager" value="customertransaction"
onClick= "parent.right.location.href='search-cust-Acc.html'"
><b>Customer Transaction</b>
</center>
<br>
<br><input type ="submit" name="logout" value="LogOut">
</form>

324
This class will generate the AccountNumber and CustomerNumber
based on request
Create the package “accountgeneration” and store in WEB-INF/classes

AccountAutogeneration.java

package accountgeneration;
import java.sql.*;
public class AccountAutogeneration
{
public static int GenerateAcc()
{
int accno=0;
Connection con;
ResultSet rs;
Statement stmt;

try
{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
rs = stmt.executeQuery("Select max(account_no) from
CUST_ACCOUNT_INFO");
if(rs.next()==false)
accno=5000;
else
{
accno=rs.getInt(1);
}

rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
return (++accno);
}
public static int GenerateCustomerID()

325
{
int custno=0;
Connection con;
ResultSet rs;
Statement stmt;

try
{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
rs = stmt.executeQuery("Select max(user_id) from login");
if(rs.next()==false)
custno=1;
else
custno=rs.getInt(1);
rs.close();
stmt.close();
con.close();

}
catch(Exception e)
{
System.out.println("errrrrr");
}
return (++custno);
}
}

326
newcustomerregistration.jsp

<%@ page import = "accountgeneration.*"%>


<SCRIPT language="javascript">
function checkAcctypeselection()
{
if(document.Registration.acc_type.value=="Select")
{
alert("Please Select Account Type");
document.Registration.user_password.value="";
document.Registration.confirm_password.value="";
return false;
}
}

function pinCheck()
{
if(document.Registration.pin.value.length != 6)
{
alert("Pin code should be of Six Digit")
return false;
}
}
function IsEmpty()
{
if(document.Registration.cust_first_name.value.length==0)

{
alert("Please Enter First Name\n");
return false;
}

if(document.Registration.cust_last_name.value.length==0)
{
alert("Please Enter Last Name\n");
return false;
}

if(document.Registration.acc_type.value=="Select")
{
alert("Please Select Account Type");
document.Registration.user_password.value="";
document.Registration.confirm_password.value="";
return false;
}

327
if(document.Registration.user_password.value.length==0)
{
alert("Please Enter password \n");
return false;
}
var pass=document.Registration.user_password.value;
if(document.Registration.confirm_password.value!=pass)
{
alert("Confirmed password is not matching \n");
return false;
}

if(document.Registration.city.value.length==0)
{
alert("Please Enter City Name\n");
return false;
}
if(document.Registration.pin.value.length==0)
{
alert("Please Enter pin Code\n");
return false;
}
if(document.Registration.email.value.length==0)

{
alert("Please Enter Email\n");
return false;
}

return true;
}

function alertmsg()
{
alert("it is mandatory to enter the Data whereever * appears");
}

328
</script>
<HTML>
<HEAD>
<H2 ALIGN="center" > Customer Registration</H2>
</HEAD>
<BODY bgcolor="Turquoise" onLoad="alertmsg();">
<FORM NAME="Registration" ACTION="registerconfirmation.jsp"
METHOD="post" ;">
<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2"
CELLPADDING="4">
<TR><TD> First Name:</TD><TD><INPUT TYPE="text"
name="cust_first_name" >*</TD></TR>
<TR><TD> Last Name:</TD><TD><INPUT TYPE="text"
name="cust_last_name" >*</TD></TR>

<TR><TD>Account Type:</TD><TD>
<SELECT NAME="acc_type" >
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="SB">SB</OPTION>
<OPTION VALUE="Current">Current</OPTION>
</SELECT>*

<TR><TD>Password:</TD><TD><INPUT TYPE="password"
name="user_password"
onChange="checkAcctypeselection();"/>*</TD></TR>
<TR><TD>Confirm Password:</TD><TD><INPUT TYPE="password"
name="confirm_password"/>*</TD></TR>

</TD></TR>
<TR><TD>Address:</TD><TD>
<TEXTAREA NAME="addressbox" ROWS="5" COLS="15"
ALIGN="center"></TEXTAREA>*
</TD></TR>

<TR><TD> City:</TD><TD><INPUT TYPE="text"


name="city"/>*</TD></TR>
<TR><TD> pin:</TD><TD><INPUT TYPE="text" name="pin"
onChange="pinCheck();"/>*</TD></TR>

<TR><TD>Profession:</TD><TD>
<SELECT NAME="Profession">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="Studying">Student</OPTION>
<OPTION VALUE="Employed">Employee</OPTION>
<OPTION VALUE="Businessman">SelfEmployed</OPTION>
</SELECT>
<TR><TD>eMail:</TD><TD><INPUT TYPE="text"
name="email"/></TD></TR>

329
<TR><TD>Gender:</TD><TD>
Male:&nbsp;<INPUT TYPE="Radio" NAME="R1"
VALUE="Male"/>&nbsp;&nbsp;Female:&nbsp;
<INPUT TYPE="Radio" NAME="R1" VALUE="Female"/>*
</TD></TR>
<TR ><TD>DOB:</TD>
<TD >Day<br>
<SELECT NAME="day" >
<% int i;
for(i=1;i<=31;i++)
{
%>
<OPTION VALUE=<%=i%>><%=i%></OPTION>
<%};
%>
</SELECT>
</td>
<%
String mon[]={new String("jan"),new String("feb"),new String("mar"),new
String("apr"),new String("may"),new String("jun"),new String("jul"),new
String("aug"),new String("sep"),new String("oct"),new String("nov"),new
String("dec")};
%>
<TD >Month
<SELECT NAME="month">
<% int j;
for(j=0;j<12;j++)
{
%>
<OPTION VALUE=<%=mon[j]%>><%=mon[j]%></OPTION>
<%};
%>
</SELECT>
</td>

330
<TR><TD align="right"> <INPUT TYPE="submit" name="submit"
onClick="return IsEmpty();" value="Confirm Details"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>

331
registerconfirmation1.jsp

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


<!--<%@ page import ="java.util.*"%>-->
<%@ page import ="accountgeneration.*"%>
<%!
ResultSet rs;
Connection con;
Statement stmt;
String userpassword,firstname,lastname,address,passwordtype;
String city,pin,profession,acctype,email,gender,day,month,year,dob;
int accno,custno;
public void MakeConnection()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}
catch(Exception e)
{
System.out.println("errrrrr");
}
}
%>

<%
MakeConnection();
try
{
userpassword=request.getParameter("user_password");
firstname=request.getParameter("cust_first_name");
lastname=request.getParameter("cust_last_name");
acctype=request.getParameter("acc_type");

332
city=request.getParameter("city");
pin=request.getParameter("pin");
email=request.getParameter("email");
gender=request.getParameter("gender");
address=request.getParameter("addressbox");
accno=AccountAutogeneration.GenerateAcc();
custno=AccountAutogeneration.GenerateCustomerID();
String day=request.getParameter("day");
String month=request.getParameter("month");
String year=request.getParameter("year");
dob=(day+"-"+month+"-"+year);
stmt.executeUpdate("insert into cust_account_info
values("+custno+","+accno+",'"+acctype+"',"+0+")");
con.close();
stmt.close();
}

catch(Exception e)
{
out.println(e);
}
try
{
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
stmt.executeUpdate("insert into login
values("+custno+",'"+userpassword+"','c',"+1+")");
con.close();
stmt.close();
}
catch(Exception e)
{
out.println(e);
}
try
{
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
stmt.executeUpdate("insert into cust_personal_info
values("+custno+",'"+firstname+"','"+lastname+"','"+gender+"','"+dob+"','"+
address+"','"+city+"',"+pin+",'"+profession+"','"+email+"')");
con.close();
stmt.close();
}

333
catch(Exception e)
{
out.println(e);
}
%>
<html>
<body bgcolor="lightGreen">
<center>
<h1><b> Sucessfully Created </b> <br></h1>
<h2><b> Customer Id <%=custno %></b> <br>
<b>Password <%=userpassword%><em></b></em><br>
<b>New Account Number<%=accno%></b>
</h2>
</center>

334
Case Study : Banking Application

Manager Login :

Html and jsp Code for creation of ‘New Account for Existing Customer’
is given in detail:

Version 2.0 335

File name: newaccount-for-old-customer.html

<script language="javascript">
function IsEmpty()
{
if(document.newaccount.cust_no.value.length==0)
{
alert("Please Enter Customer No\n");
return false;
}

if(isNaN(document.newaccount.cust_no.value))
{
alert(" Customer Number Should be numeric");
return false;
}
if(document.newaccount.acc_type.value=="Select")
{
alert("Please Select Account Type \n");
return false;
}
return true;
}
</script>

335
<HTML>
<HEAD>
<H2 ALIGN="center" > New Account Creation</H2>
</HEAD>
<BODY bgcolor="LightCyan">
<FORM NAME="newaccount" ACTION="newaccountconfirmation.jsp"
METHOD="post">
<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> Customer Number :</TD><TD><INPUT TYPE="text"
name="cust_no"></TD></TR>
<TR><TD>New Account Type:</TD><TD>
<SELECT NAME="acc_type">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="SB">SB</OPTION>
<OPTION VALUE="Current">Current</OPTION>
</SELECT>
<TR><TD align="right"> <INPUT TYPE="submit" name="submit"
onClick="return IsEmpty();" value="Create"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>

newaccount-for-oldcustomer-submit.jsp

<script language="javascript">
function IsEmpty()
{

if(document.newaccount.exist_acc_no.value.length==0)
{
alert("Please Enter Existing Account No\n");
return false;
}
}

336
<HTML>
<HEAD>
<H2 ALIGN="center" > New Account Creation</H2>
</HEAD>

<BODY bgcolor="blue">

<FORM NAME="newaccount" ACTION="" METHOD="post">


<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">
<TR><TD> Customer Number :</TD><TD><INPUT TYPE="text"
name="cust_no"></TD></TR>
<TR><TD>New Account Type:</TD><TD>
<SELECT NAME="acc_type">
<OPTION VALUE="Select">Select one</OPTION>
<OPTION VALUE="SB">SB</OPTION>
<OPTION VALUE="Current">Current</OPTION>

</SELECT>

<TR><TD align="right"> <INPUT TYPE="submit" name="submit"


onClick="IsEmpty();" value="Create"></TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>

337
Case Study : Banking Application

Manager Login:

Code for disabling Customer is given in detail:

Version 2.0 338

File name: delete-account.html

<script language="javascript">
function IsEmpty()
{
var x = document.deleteaccount.cust_no.value;

if(x.length==0)
{
alert("Please Enter Customer Number\n");
return false;
}

if(isNaN(x))

{
alert(" Customer ID Should be numeric");

return false;
}

return true;

338
</script>

<HTML>
<HEAD>
<H2 ALIGN="center" > Customer Deletion</H2>
</HEAD>

<BODY bgcolor="LightCyan">

<FORM NAME="deleteaccount" ACTION="removecustomer-submit.jsp"


METHOD="post">
<TABLE ALIGN="Center" WIDTH="50%" CELLSPACING="2">

<TR><TD> Enter Customer ID :</TD><TD><INPUT TYPE="text"


name="cust_no"/></TD></TR>
</TABLE>

<br><br/>
<center>

<INPUT TYPE="submit" name="delete" onClick="return IsEmpty();"


value="delete">

</center>

</FORM>
</BODY>
</HTML>

339
removecustomer-submit.jsp

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


<%@ page import ="accountgeneration.*"%>

<%!
ResultSet rs;
Connection con;
Statement stmt;
String acctype;
int accno,customerno;

public void MakeConnection()


{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}

catch(Exception e)
{
System.out.println("e");
}
}
%>
<%
MakeConnection();
String custno=request.getParameter("cust_no");
customerno=Integer.parseInt(custno);
int row=stmt.executeUpdate(" update login set status=0 where
user_id="+customerno);

340
if(row==0)
//if(rs.next()==false)
{
%>
<Center><h2>Invalid Customer Id</h2></center>
<jsp:include page="delete-account.html"/>
<%

}
else
{
%>
<center>
<body bgcolor="blue">
<h1><b>Customer <%=customerno %> is Disabled</b></h1>
</center>

<%}

%>

341
Case Study : Banking Application

Staff Login:
§ A staff member can deposit or withdraw cash on behalf of the
customer based on his/her account number.
§ Each of these transactions are stored in the appropriate table.

Below code shows the Customer Account Status(mini statement) and


processing of deposit and withdrawing the money.

Version 2.0 342

Note:
Http being a stateless protocol, when multiple interactions happen
between the same customer and the server, the account no which is
entered by the staff member in the first form is not available when the
deposit/withdrawal information is entered. So the account no. is stored
as an attribute in an Session object.

Once you login as Staff, it asks for Account number. For a valued account
number it shows the Account status and prompt for deposit/withdraw

Staff.html

<Frameset cols="40%,*">
<frame src ="staffhome.jsp" name="left">
<frame src = "search-cust-Acc.html" name="right">
</frameset>

342
Home Screen for Staff Login:

Staffhome.jsp

<form name="staff" action="logout.jsp" method=post>


<center>
<body bgcolor="LightCyan"><h1> STAFF</h1><br>

<%
Cookie[] k=null;
java.util.Date dt=new java.util.Date();

String lastdate=dt.toString();
try
{
k=request.getCookies();
for(int i=0;i<k.length;i++)
{
if((k[i].getName()).equals("staffCookie"))
{
String value = k[i].getValue();
out.println("<br><b> Last Login : </b>"+value);
}
}
}
catch(Exception e)
{
out.println(e);
}
out.println("<br><b>Curent Time: </b>"+lastdate);
Cookie ck = new Cookie("staffCookie",lastdate);
ck.setMaxAge(36000);
response.addCookie(ck);
%>
<br><b> You have logged in As
:<%=(String)session.getAttribute("username")%></b><br>
<br>
<em>You are authorised to access Valued Customer Account</em><br>
<br><input type ="submit" name="logout" value="LogOut">
</center>
</form>

343
Account number Entry Screen to deposit/withdraw

Search-cust-Acc.html

<script language="javascript">
function IsEmpty()
{
var acno=document.searchcustAcc.AccountNumber.value;
if(acno==0)
{
alert("Please Enter Customer Account Number\n");
return false;
}
if(isNaN(acno))
{
alert("Account Number Should Be numeric\n");
document.searchcustAcc.AccountNumber.value="";
return false;
}
parent.right.location.href="Transaction.html";
return true;
}
</script>
<form name="searchcustAcc" action="customersearch-submit.jsp" method="post">
<body bgcolor="LightSeaGreen">
<table align="center" >
<Tr><td >Customer Account Number </td> <td><input type="text"
name="AccountNumber" value=""></td>
<td><input type="submit" name="searchId" value="Confirm" onClick="return
IsEmpty();"></td></tr>
</table>
</form>

344
Transaction.html

<Frameset Rows="70%,*">
<frame src ="Transation-select.jsp" name="upper">
<frame src = "transcationsecondform.html" name="lower">

</frameset>

……………………………………………………………………………………………………………………….

This Form will display once you entered valued Account Number. It shows customer
account balance and prompt for deposit and withdraw the amount.

Tansaction-select.jsp

<script language="javascript">
function Deposit()
{
document.transaction.target.value="Deposit";
document.transaction.submit();
}

function withdraw()
{
document.transaction.target.value="withdraw";
document.transaction.submit();
}

345
</script>

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


<%!
ResultSet rs1,rs2;
Connection con;
Statement stmt;

public void MakeConnection()


{

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}
catch(Exception e)
{
System.out.println(e);

%>

<%
MakeConnection();
try
{

String Accno=(String)session.getAttribute("accountnumber");

rs1=stmt.executeQuery("select * from cust_account_info where account_no="+Accno);


rs1.next();
String userid=rs1.getString("user_id");
String acctype=rs1.getString("account_type");
int balance=rs1.getInt("current_balance");
rs1.close();
stmt.close();

stmt = con.createStatement();
rs2=stmt.executeQuery("select * from cust_personal_info where user_id="+userid);
rs2.next();
String FirstName=rs2.getString("firstname");
String LastName=rs2.getString("lastname");
rs2.close();
%>
<CENTER><b>Customer name: <%=FirstName%> <%=LastName%></b>
</CENTER>

346
<body bgcolor ="LightSeaGreen"></body>
<form name="transaction" action="" method="post">
<table BORDER="" WIDTH="50%" CELLSPACING="2" CELLPADDING="2"
align="center">
<th><tr><td bgcolor="blue"> Account Number </td>
<td bgcolor="blue"> Account Type </td>
<td bgcolor="blue">Amount Balance </td><td bgcolor="blue">Mini
Statement</td></tr></th>
<br>

<tr><td bgcolor="white"><%=Accno%> </td> <td bgcolor="white"><%=acctype%>


</td><td bgcolor="white"> <%=balance%> </td><td bgcolor="white"> <a
href="Transaction-statement-test.jsp"><b>View</b></a></td></tr>

<br>
<%

}//try close

catch(Exception e)
{
out.println(e);
}
%>
</table>
<br>
<br>
<br>

<CENTER>

<b>Transaction Type</b><br>
<input type="button" name="deposit" value="Deposit"
onClick="parent.lower.location.href='deposit-amount.html'">
<input type="button" name="Withdrawal" value="Withdrawal"
onClick="parent.lower.location.href='withdrawal-amount.html'">

<br>
<br>
</CENTER>
</form>
<input type="button" name="Back" value=" Back to new customer Transaction"
onClick="parent.top.location.href='staff.html'">

347
Transactionsecondform.html
<body bgcolor="lightBlue"> </body>
………………………………………………………………………………………………………………………..

Withdrawal-amount.html

<SCRIPT language="javascript">
function IsEmpty()
{
if(document.amountentry.amount.value.length==0)

{
alert("Please Enter the amount");
return false;
}
if(isNaN(document.amountentry.amount.value))
{
alert(" amount Should be numeric");
return false;
}
else
return true;
}

</script>
<form name="amountentry" action="withdrawal-submit.jsp" method="post" >
<table name="withdrawal" ALIGN="Center" CELLSPACING="2" CELLPADDING="2">
<body bgcolor="Cyan3">
<tr><td>Enter Description</td><td> <input type="text" name="description" >
</td></tr>
<tr><td>Enter Amount</td><td> <input type="text" name="amount" > </td></tr>
<tr><td><input type="submit" ALIGN="Center" value="submit" onClick="return
IsEmpty();"></td></tr>
</table>
</form>
………………………………………………………………………………………………………………………………

This jsp file will process the deposited amount.

withdrawal-submit.jsp

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


<%@ page import ="java.util.*"%>
<%!
ResultSet rs;
Connection con;
Statement stmt;
PreparedStatement stmt2;
int withdrawalamount,acno,bal;
String amt;
String Accno;
String description;

%>

348
<%

try
{
Accno=(String)session.getAttribute("accountnumber");

amt=request.getParameter("amount");
withdrawalamount=Integer.parseInt(amt);

acno=Integer.parseInt(Accno);

catch(Exception e)
{
System.out.println(e);
}

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt=con.createStatement();

rs = stmt.executeQuery("Select * from cust_account_info WHERE account_no="+acno);

rs.next();
bal=rs.getInt("current_balance");

}
catch(Exception e)
{
System.out.println(e);
}

if(withdrawalamount>bal)
{
%>
<html>
<body bgcolor="green">
<center>
<h2>You have only <%=bal%>Rs </h2>
</center>

<%
}
else

349
{
bal=bal - withdrawalamount;

rs.close();
stmt.close();

try
{
stmt2 = con.prepareStatement("update cust_account_info set current_balance=? where
account_no like?");

stmt2.setInt(1,bal);
stmt2.setInt(2,acno);

stmt2.executeUpdate();
//out.println(" succesfully executed");

}
catch(Exception e)
{
System.out.println(e);
}

try
{
description=request.getParameter("description");

stmt=con.createStatement();

stmt.executeUpdate("insert into transaction values


("+acno+",'"+description+"',"+withdrawalamount+",'WithDrawal',sysdate,"+bal+")");
%>

<html>
<body bgcolor="lightgreen">
<center>
<h1>Amount Succesfuly Withdrawn</h1>
</center>

<%

catch(Exception e)
{
out.println(e);
}
}//closing else
%>

350
deposit-amount.html

<SCRIPT language="javascript">
function IsEmpty()
{

if(document.depositentry.amount.value.length==0)

{
alert("Please Enter the amount");
return false;
}

if(isNaN(document.depositentry.amount.value))

{
alert(" amount Should be numeric");
document.depositentry.amount.value="";
return false;
}

alert("you Are Depositing The Money ! Are You sure");

return true;
}

</script>

<form name="depositentry" action="deposit-submit.jsp" method="post" >


<table name="depositscreen" ALIGN="Center" CELLSPACING="2" CELLPADDING="2">
<body bgcolor="Cyan3">
<tr><td>Enter Description</td><td> <input type="text" name="description" >
</td></tr>

<tr><td>Enter Amount</td><td> <input type="text" name="amount" > </td></tr>


<tr><td><input type="submit" ALIGN="Center" value="submit" onClick="return
IsEmpty();"></td></tr>
</table>
</form>

351
Deposit-submit.jsp

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


<%@ page import ="java.util.*"%>
<%!
ResultSet rs;
Connection con;
Statement stmt;
PreparedStatement stmt2;
int depositamount,acno,bal;
String amt;
String Accno;
String description;

%>

<%

java.util.Date dt=new java.util.Date();


try
{
Accno=(String)session.getAttribute("accountnumber");

amt=request.getParameter("amount");
depositamount=Integer.parseInt(amt);

acno=Integer.parseInt(Accno);
}

catch(Exception e)
{
System.out.println(e);
}

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt=con.createStatement();

rs = stmt.executeQuery("Select * from cust_account_info WHERE account_no="+Accno);

rs.next();
bal=rs.getInt("current_balance");

}
catch(Exception e)
{
System.out.println(e);
}

352
bal=bal + depositamount;
rs.close();
stmt.close();

try
{
stmt2 = con.prepareStatement("update cust_account_info set current_balance=? where
account_no like?");

stmt2.setInt(1,bal);
stmt2.setInt(2,acno);

stmt2.executeUpdate();

}
catch(Exception e)
{
System.out.println(e);
}

try
{
description=request.getParameter("description");

stmt=con.createStatement();
stmt.executeUpdate("insert into transaction values
("+acno+",'"+description+"',"+depositamount+",'Deposit',sysdate,"+bal+")");
%>

<html>
<body bgcolor="lightgreen">
<center>
<h1>Amount Succesfuly deposited</h1>
</center>
<%
}

catch(Exception e)
{
out.println(e);
}

%>

353
When user click on “View” customer account transaction (Mini
Statement) details will be displayed:

Transaction-statement.jsp

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


<%!
ResultSet rs1,rs2,rs3;
Connection con;
Statement stmt;
int acno, balance;
String userid;
String Accno;

public void MakeConnection()


{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");

stmt = con.createStatement();

catch(Exception e)
{

System.out.println(e+"gggg");

%>

<%
MakeConnection();
try
{

Accno=(String)session.getAttribute("accountnumber");
acno=Integer.parseInt(Accno);

354
//acno=2;
rs1=stmt.executeQuery("select * from cust_account_info where account_no="+acno);
rs1.next();

userid=rs1.getString("user_id");
balance=rs1.getInt("current_balance");

rs1.close();
stmt.close();

}
catch(Exception e)
{
out.println(e);
}
try
{
stmt = con.createStatement();
rs2=stmt.executeQuery("select * from cust_personal_info where user_id="+userid);
rs2.next();
String FirstName=rs2.getString("firstname");
String LastName=rs2.getString("lastname");
rs2.close();
stmt.close();
%>

<CENTER><b>Customer name: <%=FirstName%> <%=LastName%><br>


Customer ID:<%=userid%><br>
Balance : <%=balance%><br></b>
</CENTER>

<body bgcolor ="LightSeaGreen"></body>


<form name="transaction" action="http://localhost:8086/greenprp2/process.jsp"
method="post">
<table BORDER="" WIDTH="50%" CELLSPACING="2" CELLPADDING="2"
align="center">
<th><tr><td bgcolor="blue"> Account Number </td>
<td bgcolor="blue"> Description </td>
<td bgcolor="blue">Amount </td><td bgcolor="blue">Transaction Type</td> <td
bgcolor="blue">Transaction Date</td> <td bgcolor="blue">Closing balanace</td>
</tr></th>
<br>
<%
stmt = con.createStatement();
rs3=stmt.executeQuery("select * from transaction where account_no="+acno);

while(rs3.next())
{
%>

355
<tr><td bgcolor="white"><%=Accno%> </td> <td
bgcolor="white"><%=rs3.getString("description")%> </td> <td
bgcolor="white"><%=rs3.getInt("amount")%><td
bgcolor="white"><%=rs3.getString("transaction_type")%> </td><td
bgcolor="white"><%=rs3.getString("transaction_date")%> </td> </td><td
bgcolor="white"> <%=rs3.getInt("closing_balance")%> </td></tr>

<%

rs3.close();

}//try close

catch(Exception e)
{
out.println(e+"execute err");
}

%>

</table>
</form>
<a href="Transation-select.jsp" > <b>Back</b></a>

356
<tr><td bgcolor="white"><%=Accno%> </td> <td
bgcolor="white"><%=rs3.getString("description")%> </td> <td
bgcolor="white"><%=rs3.getInt("amount")%><td
bgcolor="white"><%=rs3.getString("transaction_type")%> </td><td
bgcolor="white"><%=rs3.getString("transaction_date")%> </td> </td><td
bgcolor="white"> <%=rs3.getInt("closing_balance")%> </td></tr>

<%

rs3.close();

}//try close

catch(Exception e)
{
out.println(e+"execute err");
}

%>

</table>
</form>
<a href="Transation-select.jsp" > <b>Back</b></a>

357
Case Study : Banking Application

Customer Login:

The customer can view his account details by providing the account
Number and do FundTransfer within the Bank.

Code for html and jsp to process Customer Login is detailed below.

Version 2.0 358

When user login as Customer. It shows the Customer’s all accounts


details. One can view the Statement By clicking the “mini statement”
hyperlink. Customer can also transfer money a) within his/her accounts
and b) Third party transfer within the same Bank

CustomerScreen.jsp
<Frameset cols="40%,*">
<frame src ="customerhome.jsp" name="left">
<frame src = "customer-account-view.jsp" name="right">
</frameset>

358
Customerhome.jsp

<script language="javascript">
function f()
{
parent.right.location.href="select-own-accounts.jsp">

}
</script>

<form name="staff" action="logout.jsp" method=post>


<center>
<body bgcolor="SeaGreen"><b> Customer Home</b><br>
</center>

<%

Cookie[] k=null;

java.util.Date dt=new java.util.Date();

String lastdate=dt.toString();

try
{
k=request.getCookies();
if(k!=null)
{
String value = k[0].getValue();
out.println("<br><b> Last Login : </b>"+value);
}
}

catch(Exception e)
{
out.println(e);
}

out.println("<br><b>Curent Time: </b>"+lastdate);

Cookie ck = new Cookie("customerCookie",lastdate);


ck.setMaxAge(36000);
response.addCookie(ck);

%>

359
<br><b> You have logged in As
:<%=(String)session.getAttribute("username")%></b><br>

<table>

<tr><td><input type ="radio" name="f" value="accountstatus"


onClick="parent.right.location.href='customer-account-view.jsp'"><b>Account Status
<b></td></tr>

<TR><TD><h2><em>Funds Transfer:<em></h2></TD><TD></tr>
<tr><td><input type ="radio" name="f" value="ownaccounts"
onClick="parent.right.location.href='select-own-accounts.jsp?acno=own'"> <b>Between
Own Accounts</b></td></tr>

<tr><td><input type ="radio" name="f" value="Third Party"


onClick="parent.right.location.href='select-thirdparty-accounts.jsp'"><b>Third
Party</b></td></tr>

<br><em><p>You are authorised to View The Account Status of All accounts along with
Fund Transfer within the Bank</em></p><br>
<br>
<br>
<center>
<tr><td><input type ="submit" name="logout" value="LogOut"></td></tr>
</center>
</table>
</form>

360
As soon as user login As ‘Customer’ he/she will be seeing this
screen with all the Account Balance:

Customer-account-view.jsp

<script language="javascript">
function setaccountnumber()
{
<%session.setAttribute("accountnumber",(String)Accno);
%>

</script>

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

<%!
ResultSet rs1,rs2;
Connection con;
Statement stmt;
String UserName,FirstName,LastName;
String Accno;
public void MakeConnection()
{

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}
catch(Exception e)
{
System.out.println(e);

%>

<%

MakeConnection();

361
try
{

UserName=(String)session.getAttribute("username");

rs2=stmt.executeQuery("select * from cust_personal_info where user_id="+UserName);


rs2.next();
FirstName=rs2.getString("firstname");
LastName=rs2.getString("lastname");
rs2.close();
stmt.close();

}
catch(Exception e)
{
out.println(e);
}

try
{

stmt=con.createStatement();
rs1=stmt.executeQuery("select * from cust_account_info where user_id="+UserName);
//rs1.next();

%>

<CENTER><b>Customer name: <%=FirstName%> <%=LastName%></b>


</CENTER>
<input type="hidden" value="" name="sessionid">
<body bgcolor ="DarkSalmon"></body>
<form name="transaction" action="" method="post">
<table BORDER="" WIDTH="50%" CELLSPACING="2" CELLPADDING="2"
align="center">
<th><tr><td bgcolor="blue"> Account Number </td>
<td bgcolor="blue"> Account Type </td>
<td bgcolor="blue">Amount Balance </td><td bgcolor="blue">Mini
Statement</td></tr></th>

<br>
<%
while(rs1.next())
{
Accno=rs1.getString("account_no");

%>

362
<tr><td bgcolor="white"><%=Accno%> </td> <td
bgcolor="white"><%=rs1.getString("account_type")%> </td><td bgcolor="white">
<%=rs1.getInt("current_balance")%> </td><td bgcolor="white"> <a href="customer-
accountwisedetail.jsp?acno=<%=Accno%>"> <b>View</b></a></td></tr>

<br>

<%
}
rs1.close();

}//try close

catch(Exception e)
{
out.println(e);
}
%>

</table>

</form>

…………………………………………………………………………………………………………………………………
This page shows the Transaction Details once user clicks on MiniStatement hyperlink

Customer-accountwisedetail.jsp

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


<%!
ResultSet rs1,rs2,rs3;
Connection con;
Statement stmt;
int acno, balance;
String userid;
String Accno;

public void MakeConnection()


{

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");

stmt = con.createStatement();

363
catch(Exception e)
{

System.out.println(e+"gggg");

%>

<%
MakeConnection();
try
{

String Accno=request.getParameter("acno");

acno=Integer.parseInt(Accno);

rs1=stmt.executeQuery("select * from cust_account_info where account_no="+acno);


rs1.next();

userid=rs1.getString("user_id");
balance=rs1.getInt("current_balance");

rs1.close();
stmt.close();

}
catch(Exception e)
{
out.println(e+"---Error--");
}

try
{
stmt = con.createStatement();

rs2=stmt.executeQuery("select * from cust_personal_info where user_id="+userid);


rs2.next();
String FirstName=rs2.getString("firstname");
String LastName=rs2.getString("lastname");
rs2.close();
stmt.close();

%>

364
<CENTER><b>Customer name: <%=FirstName%> <%=LastName%><br>
Customer ID:<%=userid%><br>
Balance : <%=balance%><br></b>
</CENTER>

<body bgcolor ="DarkSalmon"></body>


<form name="transaction" action="" method="post">
<table BORDER="" WIDTH="50%" CELLSPACING="2" CELLPADDING="2"
align="center">
<th><tr><td bgcolor="blue"> Account Number </td>
<td bgcolor="blue"> Description </td>
<td bgcolor="blue">Amount </td><td bgcolor="blue">Transaction Type</td> <td
bgcolor="blue">Transaction Date</td> <td bgcolor="blue">Closing balanace</td>
</tr></th>
<br>
<%
stmt = con.createStatement();
rs3=stmt.executeQuery("select * from transaction where account_no="+acno);

while(rs3.next())
{

%>
<tr><td bgcolor="white"><%=acno%> </td> <td
bgcolor="white"><%=rs3.getString("description")%> </td> <td
bgcolor="white"><%=rs3.getInt("amount")%><td
bgcolor="white"><%=rs3.getString("transaction_type")%> </td><td
bgcolor="white"><%=rs3.getString("transaction_date")%> </td> </td><td
bgcolor="white"> <%=rs3.getInt("closing_balance")%> </td></tr>

<%

rs3.close();

}//try close

catch(Exception e)
{
out.println(e+"execute err");
}

%>

</table>

</form>
<a href="customer-account-view.jsp" > <b>Back</b></a>
…………………………………………………………………………………………………………………………………

365
Fund transfer
This page will be Displayed When User Select Fundtransfer within the Bank

Select-own-accounts.jsp
<script language="javascript">

function IsEmpty()
{

if(document.fundtransfer.from.value==document.fundtransfer.to.value)
{
alert("Selected Account Numbers are Same");
return false;

if(document.fundtransfer.amount.value.length==0)

{
alert("Please Enter the amount");
return false;
}

if(isNaN(document.fundtransfer.amount.value))

{
alert(" Wrong Entry");

return false;
}

return true;
}
</script>

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


<body bgcolor="DarkSalmon">

<h2><em> Fund Transfer Between Own Accounts</em></h2>

366
<%!
ResultSet rs1,rs2;
Connection con;
Statement stmt;
String UserName,FirstName,LastName;
int Accno;
public void MakeConnection()
{

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
stmt = con.createStatement();
}
catch(Exception e)
{
System.out.println(e);

%>

<%

MakeConnection();

try
{

UserName=(String)session.getAttribute("username");

rs2=stmt.executeQuery("select account_no from cust_account_info where


user_id="+UserName);

%>

<form name="fundtransfer" action="fundtransfer-submit.jsp?type='own'" method="">


<table>

367
<TR><TD><b>From Account: </b></TD><TD>
<SELECT NAME="from" cellspacing="5">
<%
while(rs2.next())
{
Accno=rs2.getInt(1);
%>

<OPTION VALUE=<%=Accno%>><%=Accno%>

<%

}
%>
</OPTION>
</SELECT></tr>
<%
rs2.close();
stmt.close();
}
catch(Exception e)
{
out.println(e);
}

%>

<br>

<%
try
{
stmt = con.createStatement();
rs2=stmt.executeQuery("select account_no from cust_account_info where
user_id="+UserName);

%>

<TR><TD><b>To Account: </b></TD><TD>


<SELECT width="10" NAME="to">
<%
while(rs2.next())
{
Accno=rs2.getInt(1);
%>

<OPTION VALUE=<%=Accno%>><%=Accno%>

<%

}
%>

368
</OPTION>
</SELECT>
</tr>
<%}
catch(Exception e)
{
out.println(e);
}
%>

<tr><td><b> Amount</b></td><td><input type="text" name="amount"


value=""></td></tr>
<tr><td><b> </b></td><td><input type="hidden" name="type"
value="own"></td></tr>

<tr><td><input type="submit" name="submit" onClick="return IsEmpty();"


value="Accept"></td></tr>
</table>
</form>

………………………………………………………………………………………………………………………………

Select-thirdparty-accounts.jsp

<script language="javascript">

function IsEmpty()
{

if(document.fundtransfer.amount.value.length==0)

{
alert("Please Enter the amount");
return false;
}

if(document.fundtransfer.from.value==document.fundtransfer.to.value)
{
alert("Selected Account Numbers are Same");
return false;

if(isNaN(document.fundtransfer.amount.value))

369
{
alert(" Wrong Entry");

return false;
}

return true;
}
</script>

<body bgcolor="DarkSalmon">

<h2><em> Fund Transfer within Our bank</em></h2>

<form name="fundtransfer" action="fundtransfer-submit.jsp" method="post" >


<table>
<tr><td><b> From Account</b></td><td><input type="text"
name="from"></td></tr>
<tr><td><b> To Account</b></td><td><input type="text" name="to"></td></tr>
<tr><td> <b>Amount</b></td><td><input type="text" name="amount"
value=""></td></tr>
<tr><td><b> </b></td><td><input type="hidden" name="type"
value="third"></td></tr>
<tr><td><input type="submit" name="submit" onClick="return IsEmpty();"
value="Accept"></td></tr>
</table>
</form>
………………………………………………………………………………………………………………………..

Fundtransfer-submit.jsp

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

<%! ResultSet rs1,rs2;


Connection con;
Statement stmt1,stmt2;
String FromAcc,ToAcc,description,amount;
int frombalance,tobalance,amt;
public void MakeConnection()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:green","scott","tiger");
}

370
catch(Exception e)
{
System.out.println(e);
}
}
%>

<%
MakeConnection();
stmt1 = con.createStatement();
stmt2 = con.createStatement();
FromAcc=request.getParameter("from");
ToAcc=request.getParameter("to");
amount=request.getParameter("amount");
amt=Integer.parseInt(amount);

String fundtype=request.getParameter("type");

try
{

rs1 = stmt1.executeQuery("Select * from cust_account_info where account_no= "+


FromAcc);
if(rs1.next()==false)
{
%>

<Center><h2><%=FromAcc%> Account Number Does Not Exits</h2></center>


<jsp:include page="select-thirdparty-accounts.jsp"/>
<%
}
else
{
frombalance=rs1.getInt("current_balance");

rs2=stmt1.executeQuery("Select * from cust_account_info where account_no= "+


ToAcc);

if(rs2.next()==false)
{
%>

<Center><h2><%=ToAcc%> Account Number Does Not Exits</h2></center>


<jsp:include page="select-thirdparty-accounts.jsp"/>

<%
}
else
{

tobalance=rs2.getInt("current_balance");

371
stmt1.close();
stmt2.close();

if(amt>frombalance)
{
if(fundtype.equals("own"))
{
%>

<Center><h2>Account <%=FromAcc%> Balance is Less than the


Transferring Amount</h2></center>
<jsp:include page="select-own-accounts.jsp"/>

<%
}
else
{
%>

<Center><h2><%=ToAcc%> Account Number Does Not


Exits</h2></center>
<jsp:include page="select-thirdparty-accounts.jsp"/>

<%

}
}

else
{
frombalance = frombalance-amt;
description="- transferred to "+ToAcc;
tobalance=tobalance+amt;

try
{

stmt1 = con.createStatement();
stmt2 = con.createStatement();

stmt1.executeUpdate("update cust_account_info set current_balance="+frombalance +"


where account_no="+ FromAcc);

stmt2.executeUpdate("insert into transaction values


("+FromAcc+",'"+description+"',"+amt+",'WithDrawal',sysdate,"+frombalance+")");

stmt1.close();
stmt2.close();
}

catch(Exception e)

372
{
out.println(e);
}

try
{
stmt1 = con.createStatement();
stmt2 = con.createStatement();

stmt1.executeUpdate("update cust_account_info set current_balance="+tobalance +"


where account_no="+ ToAcc);

description="- transferred From "+FromAcc;

stmt2.executeUpdate("insert into transaction values


("+ToAcc+",'"+description+"',"+amt+",'Deposit',sysdate,"+tobalance+")");

stmt1.close();
stmt2.close();
}
catch(Exception e)
{
out.println(e+"middle");
}

%>
<html>
<body bgcolor="DarkSalmon">
<center>
<h1>Amount Succesfuly transferred</h1>
</center>
</html>
<%

}
}

}
}
catch(Exception e)
{
out.println(e+"last");

}
%>

373
Module 7:
J2EE

Copyright © 2008, Wipro Limited, Bangalore

374
J2EE

The lessons covered in this module include:


§ Issues in Enterprise Application
§ Java 2 Editions
§ Naming Services
§ Introduction to RMI
§ EJB

Version 2.0 375

375
Objectives

At the end of this module you will be able to:


§ Identify the challenges of an enterprise application
§ Identify the characteristics of different Java Platforms
§ Describe J2EE architecture
§ Define the role of various J2EE technologies

Version 2.0 376

376
Issues in Enterprise Applications

1. Transactions
2. State management
3. Multithreading
4. Resource pooling
5. Security

Version 2.0 377

Transactions : When developing an Enterprise Application, we have to


ensure that the data consistency and integrity is maintained under all
circumstances. The application is responsible for transaction
management.
State Management : When an application is accessed by multiple
clients simultaneously, the state information of a particular client has to
be maintained, especially when there are multiple conversations between
a client and the application. This is known as State Management and it is
the responsibility of the application to manage state.
Multithreading : The application has to create and maintain multiple
threads for concurrency.
Resource Pooling : Managing resources efficiently like sharing of
component instances, sharing of database connections etc. is the
responsibility of the application.
Security : An enterprise application has to decide which user can access
the application and that too, what part of the application is to be accessed
by whom. So authentication and Access Control are the issues that the
application needs to address.

377
Java 2 Editions

Version 2.0 378

378
Java 2 Editions: Java 2 Platform, Enterprise Edition

Java 2:
RMI EJB
Standard ed.

JNDI JMS

JDBC
J2EE
J2EE JTA

JavaMail Connectors

Servlets JSP Java IDL XML

Version 2.0 379

The Java 2 Platform, Enterprise Edition (J2EE) builds on the existing


technologies in the Java 2 Platform, Standard Edition (J2SE). J2SE
includes the base Java support and the various libraries (.awt, .net, .io)
with support for both applets and applications. Because J2EE builds on
J2SE, a J2EE-compliant product must implement all of J2SE; making
building a J2EE product an absolutely huge undertaking..

RMI : Java RMI (Remote Method Invocation) provides a mechanism for


supporting distributed computing. Using RMI, we can activate a
method on a remotely running object.

JNDI : The Java Naming and Directory Interface (JNDI) is an API used
for accessing different kinds of naming and directory services.

JavaMail : The JavaMail API is provided by Sun Microsystems to allow


users to send, compose, and read e-mail messages. To send or retrieve
an e-mail, the API uses Simple Mail Transfer Protocol (SMTP).

379
Java IDL : For objects interacting on different platform across a network,
Java provides a technology known as Java IDL. It is similar to RMI, but the
difference is that while RMI supports distributed objects written in Java, Java
IDL enables objects to interact with each other regardless of whether they are
written in Java or some other language like C, C++ or Cobol.

Connectors : The J2EE Connector Architecture provides the J2EE


components plug and play access to heterogeneous Enterprise Information
Systems, like ERP, Transaction Processing Systems, and Legacy Database
systems.

JTA : The Java Transaction API(JTA) specification was developed by Sun


Microsystems in cooperation with leading industry partners in the transaction
processing and database system domain. JTA specifies standard Java
interfaces between different entities involved in a distributed transaction
system.

JMS : JMS is a technology that allows Java programs to exchange messages


with other Java programs sharing a messaging system.

EJB : Enterprise Java Beans(EJB) is a server side component architecture


that simplifies the process of building distributed component based enterprise
applications in Java. By using EJB, you can write scalable, reliable and secure
applications without writing your own complex distributed component
framework.

380
Java 2 Editions: J2EE Architecture

Version 2.0 381

381
J2EE Architecture (Contd.).

Services Java Technology


Web Servlets/ JSPs (HTML/ XML)
Database Access Java DataBase Connectivity (JDBC™)
Naming And Directory Java Naming and Directory Interface
Messaging Java Message Service (JMS)
Email Access JavaMail™
Protocol JavaIDL, Remote Method Invocation
(CORBA compatible)
Transaction Object Transaction Service (OTS),
Java Transaction Service (JTS),
Java Transaction API (JTA)

Version 2.0 382

382
Naming Services

Naming services provide J2EE components with access to a JNDI


naming environment.
§ J2EE component locates its environment naming context using
JNDI interfaces

Version 2.0 383

A naming service is responsible for maintaining a set of bindings.


Bindings are a way of connecting a names to objects. All objects in a
naming service follow the same naming convention. Thus naming
services help the clients to locate a particular object in a distributed
environment.

There are a number of naming services available for different


environment, some of them are listed below :

DNS (Domain Name System) – which maps easy to remember


names(yahoo.com) to IP addresses
LDAP(Lightweight Directory Access Protocol) – which is a standard for
network directory services
COS(Common Object Services) – which allows CORBA applications to
store and access references to CORBA objects
NIS(Network Information System) – which is a Network naming service
developed by Sun Microsystems.

383
The various naming services that are used by different environments pose a
challenge as to the storage and accessibility of objects on different platforms.
These naming services are functionally different and they may be using
different naming conventions. To solve this problem, JNDI(Java Naming and
Directory Interface) is used. JNDI provides a common interface to many
existing naming services. JNDI makes it possible for you to work with a
variety of naming services without bothering about how the objects are stored
and accessed in different environments.

J2EE naming services provide application clients, enterprise beans, and Web
components with access to a JNDI naming environment. A naming
environment allows a component to be customized without the need to access
or change the component’s source code. A container implements the
component’s environment, and provides it to the component as a JNDI
naming context.

384
Naming Services: Java Naming and Directory Interface

1) A standard for Naming and directory services

2) EJB strictly relies on JNDI for looking up distributed components


across the network
e.g. Novell’s NDS and the internet standard LDAP

3) JNDI bridges the gap between different directory services:


provides portable interface

Version 2.0 385

JNDI is an API specified in Java that provides naming and directory


functionality to applications written in Java. It is designed especially for
Java by using Java's object model. Using JNDI, Java applications can
store and retrieve named Java objects of any type. In addition, JNDI
provides methods for performing standard directory operations, such as
associating attributes with objects and searching for objects using their
attributes.
JNDI is also defined independent of any specific naming or directory
service implementation. It enables Java applications to access different,
possibly multiple, naming and directory services using a common API.
Different naming and directory service providers can be plugged in
seamlessly behind this common API. This allows Java applications to
take advantage of information in a variety of existing naming and
directory services, such as LDAP, NDS, DNS, and NIS(YP), and allows
Java applications to coexist with legacy applications and systems.
The Naming Interface — javax.naming
Context is the core interface that specifies a naming context. It defines
basic operations such as adding a name-to-object binding, looking up
the object bound to a specified name, listing the bindings, removing a
name-to-object binding, creating and destroying sub contexts of the
same type, etc.

385
Naming Services: JNDI Interface

Version 2.0 386

The JNDI architecture consists of an API (Application Programming


Interface) and an SPI (Service Provider Interface).

JNDI API : Through the use of JNDI API, a java application can access a
variety of naming and directory services.

JNDI SPI : By using JNDI SPI, a variety of naming and directory


services can be plugged in transparently. This enables a java application
to access their services through the use of JNDI API.

386
Introduction to RMI

Distributed Computing
§ RPC
§ RMI

Version 2.0 387

Distributed Computing

The idea behind distributed computing is to share the load of processing


between different machines (PCs). Gone are the days where everything
used to be done on a single/monolithic machine, which had the
limitations of accessibility and scalability. Now as we can network our
machines we can distribute our applications. We have come across
different kinds of distributed applications. Database Application and
Web applications are two of them. In a Database application, we have a
Database server installed on a Remote machine and have a Database
client (Developer 2000) at your Desk. The Database server is used for
storing, updating changes on the data and also processing on the Data.
The Database Client usually is used for presentation and
communication with the Database Server with its own proprietary
protocol. This is an example of a 2 tier System, in which the application
is split into 2 layers.

387
In a Web Application like TEDWEB we will be having the GUI for interacting
like the html pages on the Client side. We will have another machine, which
will have the logic for operating on the database. We call this machine with
the business logic as a middle tier. Then we will have the Server which has
the Database. Here the processing has been distributed into 3 layers.
Validation is done on the Client tier, Business logic processing on the middle
tier, and the database operation on the Server. This is an example of 3 tier
System.

Remote Procedure Call

RPC was one of the earlier way of Distributed computing. As the acronym
says, it is used to invoke functions which are residing in different machines. C
was used as the primary language for RPC. Low level socket programming has
to be done for RPC. RPC works for only procedure oriented languages. It
cannot be used for communicating with Objects. Object Oriented
Programming is the preferred one these days.

Remote Method Invocation

RMI is the java’s way of communicating between two different objects


residing on different Java Virtual Machines, possibly on different hosts.
CORBA is used to communicate with Objects of different languages. E.g.,
using CORBA a Java object on one machine can communicate with C++
object on a different machine.

388
Introduction to RMI: Features of RMI

§ Remote invocations of methods on objects in different JVMs

§ Simple to write reliable distributed applications

§ RMI is transparent

Version 2.0 389

389
Introduction to RMI: RMI Architecture

Client Program Server Program

Stub Skeleton Layer

RRL RRL

Transport Layer

Version 2.0 390

The RMI Architecture has 4 layers:

1) Application Layer
All the programs we write in java for RMI comes under this layer. We
will be having a Server program which will store a remote object in a
Registry service. We have a program which makes a object as Remote.
Then we have a client program which performs a look up on the Remote
object and gets a remote reference and then invokes the remote method.

2) Stub/Skeleton Layer or Proxy Layer


The Application layer on the client side will communicate with another
layer called as Stubs/Skeleton Layer. The stub class acts as a proxy to
the remote service implementation class and is on the client side which
will marshal the data for transfer to the server. A Skeleton is also a proxy
for the Remote Object on the Server side. A Skeleton unmarshals the
data sent from the client side. The skeleton understands how to
communicate with the stub across the RMI link. It carries on the
conversation with the stub. It is responsible for reading the parameters
for the method call, make the call to the remote object, accept the return
value from it and return the value back to the stub.

390
3) Remote Reference Layer (RRL)
RRL manages the Remote References and reconnection strategies. This layer
understands how to interpret and manage references made from clients to the
remote service objects.

4) Transport Layer
Transport receives a request from the RRL Layer. It searches for the RMI
Server and then establishes a Socket Connection. It is responsible for making
connection between two JVMs. It makes network connections using TCP/IP.
This layer maps to the TCP layer of OSI model.

391
Introduction to RMI: Writing a Simple RMI program

1. Write the Remote Object program

//Branch.java
import java.rmi.*;
import java.rmi.server.*;
interface Branch extends Remote
{
public String getDescription() throws RemoteException;
}

Version 2.0 392

We write a remote interface Branch which extends java.rmi.Remote. Any


method which has to be accessed remotely should be a part of this
interface. The method should throw a RemoteException. You can have
any number of methods in the interface Branch.

392
Writing a Simple RMI program (Contd.).

2. Write the Remote Server Program

//BranchImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class BranchImpl extends UnicastRemoteObject implements Branch{
private String str;
public BranchImpl(String d) throws RemoteException{
str=d;
}
public String getDescription() throws RemoteException{
return "Branch Name : "+str;
}
contd..

Version 2.0 393

We should provide the implementation of the remote method in a


separate class which implements the Remote interface. BranchImpl is
the class which implements the interface, the class has to extend the
UnicastRemoteObject for making the exporting of Remote Object
easier.

393
Writing a Simple RMI program (Contd.).

2. Write the Remote Server Program (contd.).


public static void main(String args[]){
try{
BranchImpl p1 = new BranchImpl("Jayanagar");
BranchImpl p2 = new BranchImpl("Malleshwaram");
BranchImpl p3 = new BranchImpl("Indira Nagar");
BranchImpl p4 = new BranchImpl("Electronics City");
Naming.rebind("Jay", p1);
Naming.rebind("Mal", p2);
Naming.rebind("Ind", p3);
Naming.rebind("Ele", p4);
}
catch(Exception e){
System.out.println("Error : "+e);
e.printStackTrace();
}
}}

Version 2.0 394

The program creates 4 remote objects of type BranchImpl and registers


the objects in the RMI Registry. RMI Registry is a naming service which
helps locate the objects through Name. Naming.rebind will bind the
remoteobject to a name like p1, p2 etc.

394
Writing a Simple RMI program (Contd.).

3. Write the Client program

import java.rmi.*;
import java.rmi.server.*;
public class BranchClient{
public static void main(String args[]){
try{
String url1 = "rmi://127.0.0.1/Jay";
String url2 = "rmi://localhost/Mal";
String url3 = "rmi://127.0.0.1/Ind";
String url4 = "rmi://localhost/Ele";
Branch c1 = (Branch)Naming.lookup(url1);
Branch c2 = (Branch)Naming.lookup(url2);
Branch c3 = (Branch)Naming.lookup(url3);
Branch c4 = (Branch)Naming.lookup(url4);
contd..

Version 2.0 395

The client first looks up for the remote object in the RMI Registry. Gets
a reference to the RemoteObject and the invokes the remotemethod
getDescription.

395
Writing a Simple RMI program (Contd.).

3. Write the Client program (contd.).

System.out.println(c1.getDescription());
System.out.println(c2.getDescription());
System.out.println(c3.getDescription());
System.out.println(c4.getDescription());
}
catch(Exception e)
{
System.out.println("Error : "+e);
}
}
}
contd..

Version 2.0 396

396
Enterprise JavaBeans (EJB)

Enterprise JavaBeans is an architecture for component- based


distributed computing:
§ Customizable at deployment time
§ Deployed on a compatible application server
§ Portable to other application servers

Enterprise Beans are components of distributed transaction – oriented


enterprise applications.

Version 2.0 397

The term enterprise Java bean refers to an architecture for the


deployment of component based distributed computing. The
components’ runtime characteristics are customizable at deployment
time and are deployed on a compatible application server. The
components can also be deployed on other application servers that
support the EJB specification.

Enterprise Java Beans are defined by the specification as component of


distributed , transaction oriented enterprise applications and are also
referred to as business components.

397
EJB: Defining EJB Technology

EJB servers provide core services to server components:


§ Transaction
§ Security
§ Concurrency
§ Naming
§ Persistence

EJB technology enhances:


§ Simplified access to services
§ Portability of components across server platforms

Version 2.0 398

The EJB servers provide core services including control of transactions,


security, concurrency, persistence, naming and lifecycle management of
EJB components. The technology simplifies accesses to these services so
an enterprise development team does not have to be an expert in all of
these areas. It also encourages reuse by allowing the components to port
to other server platforms. it is up to the vendor who is implementing an
EJB server, not the application developer, to provide an environment
that has good performance and scalability.

398
Defining EJB Technology (Contd.).

§ Is a server component specification (for vendors)


§ Separates and defines integration of development stages:
– Component creation
– Application assembly
– Application deployment

Version 2.0 399

The overall goal of the technology is to encourage the separation of roles


during the development and deployment processes, ideally making the
components portable and reusable.

EJB Developer Roles


The actual stages of component -oriented application development and
deployment are represented in the definition of the EJB specification
itself. by clearly defining the roles played in each of these stages, EJB
makes it easier to develop complex applications in stages, encouraging
object oriented implementations and component reuse.

399
EJB: EJB Developer Roles

Version 2.0 400

Bean provider. The bean provider writes the bean that performs
business operations in a specific vertical or horizontal area. Because the
server hides service implementations in the framework, the bean
developer can concentrate on writing code that implements business
rules rather than focusing on the code that manages operations like
transaction, persistence, concurrency etc.

Application assembler. The assembler uses the bean component to


build groups of beans to be deployed as an application group, and can
also be responsible for developing the client applications.

Deployer. Once the Application assembler assembles the components


into an application, the application must be deployed in a live
environment. Most of the times the bean providers/assemblers are not
familiar with runtime environment issues. EJB deployers are aware of
specific operational requirements. Hence it is their responsibility to
deploy the application and make it live. A deployer knows how to deploy
an application within the server and how to customize the beans for a
specific environment.

400
EJB: EJB Programming Paradigm

Declarative programming and customizing

Version 2.0 401

In EJB, the information about what services the Bean is supposed to use
and other environmental information is declared in a XML file called a
deployment descriptor (or DD). The business logic is written within a
class as with standard programming techniques. However, the remote
information (or client contract) is placed within two interfaces: home
,and remote. The bean developer is not responsible for the
implementation of these interfaces.

401
EJB Programming Paradigm (Contd.).

Deploying

Version 2.0 402

Once the bean developer has created the files, they are packaged in a jar
file. The application assembler can modify the information in the
deployment descriptor using tools provided by the container vendor,
but the deployer is the one who makes the final modifications in the
descriptor and deploys into the server environment. The deployer uses
tools provided by the container vendor, which is responsible for
implementing the interfaces and ensuring that the home object is
created in the environment. It also is responsible for ensuring the
creation of the EJB object and the enterprise bean component when
needed. This course discusses how this is done. However, you must
understand that there are multiple pieces to support one component,
unlike normal programming techniques where the remote interface and
environment information is built into the component. This feature
might seem complex at first, but is what makes enterprise beans so
portable and reusable.

402
EJB: EJB Architecture Overview

1. Uniform client access whether local or remote


2. Home object is a factory for EJBs
3. EJB object is the remote object for accessing EJBs

Version 2.0 403

EJB Architecture Overview


Figure above illustrates EJB architecture. Listed below are the main
elements.
•EJB server
•EJB container
•Home object
•EJB Object
•Enterprise bean

The client can reside either locally or remotely to the enterprise bean,
but the interaction with the bean is always the same. The client never
accesses the bean directly because the home and EJB objects must work
with the container to manage the bean and to provide the abstraction
from the server, which makes the bean portable to other vendors’
servers. The home object acts as a factory to manage the life cycle of a
bean. The EJB object (or remote object) acts as an intercessor to the
bean. In other words, it receives the method call from the client, works
with the container to check security and add transaction context before
passing it to the bean.

403
EJB Architecture Overview (Contd.).

Version 2.0 404

Figure above illustrates the steps for accessing an enterprise bean.


[1] The client needs to locate the business component and obtain a
reference to it.
[2] JNDI provides access to a lookup service to obtain a reference to the
bean's home object.
[3] A reference is returned to the client.
[4] The client asks the home object to create or find an enterprise bean.
[5] The home object creates or finds the bean. It is also responsible for
removing the bean when the client requests it to be removed.
[6] A reference to the remote object (EJB object) is returned to the
client.
[7] The client calls a business method to the EJB object.
[8] The EJB object intercedes the call on behalf of the bean and works
with the container to authenticate the client and to add transaction
context to the calling thread. This intercession is a known design pattern
called a proxy.
[9] The EJB object forwards the method call to the bean component
whose return values are passed to the EJB object.
[10] The bean might need to access its properties, which is done through
JNDI. These properties were stored in the DD.
[11] The EJB object returns, to the bean, the values obtained by the
business call.

404
EJB: EJB Server

§ Services:
– Transaction support
– Data access
– System resource
– Namespace
§ Industry support:
– Application/ middleware servers
– Database servers

Version 2.0 405

EJB Server. The EJB server uses a container to provide enterprise


beans transparent access to system services. There is wide industry
support with many vendors providing products that support the EJB
specification.
Services. Services must be available to support EJBs. In some cases
the services are internal to the server, possibly the naming and
transaction services, while other services reside outside the server but
are accessed and managed by the server, such as database connection
pools. The services can be made available to the container, such as
transaction control, or to the bean, such as implicit use of connection
pooling through the standard JDBC interfaces.
Industry Support. There are various products on the market that are
in the process of providing support for EJB. These products can be
labelled as application servers, middleware servers, database servers,
and so on. Generally, the product vendor will use their own core
technology and integrate it with an EJB framework to provide
specialised enhancements to the EJB environment.
EJB 2.0 requires that every EJB server supports Java RMI-IIOP
protocol. Enterprise beans are made available for remote client using
RMI.

405
EJB: EJB Container

§ Can contain multiple Bean classes or homes


– Often created using code generation by tools
– Is normally provided by EJB server vendor
§ Is not visible to the client
§ Is implemented in different ways by different vendors

Version 2.0 406

The EJB container is an abstraction usually composed of one or more


classes that provide a set of services to your enterprise bean. These
services are largely transparent, such as transaction control. The classes
are created at deployment time using code generation by a tool that is
usually provided by the server vendor.
The container is intended to function transparently to the client which
means there are no intermediary APIs about which the client must
know. The client accesses the enterprise bean exactly the same way,
regardless of in which container the bean resides. The client accesses the
bean as if it did not reside in a container.
The EJB specification provides flexibility for server and container
vendors to implement their products. For example, the container might
represent all instances of one enterprise bean class, or it might represent
multiple classes. Also, in the specification, the container is often
referred to as the object that implements the bean's home interface.
While this is a common implementation, it is not a requirement. These
are examples of implementations that do not affect the enterprise bean
provider's development.

406
EJB Container (Contd.).

§ Provides some standard services:


– Persistence
– Transaction control
– Security
– EJB instance lifecycle management
– EJB instance identification

Version 2.0 407

The EJB container provides several standard services, including


persistence (state management), transaction control, security, lifecycle
management, identification, and swapping.

Persistence
A container is responsible for allowing an entity bean instance to
synchronize itself with its underlying store. The container must allow
for bean-managed persistence, where the bean manages its own
persistence. In addition, a container can provide container-managed
persistence, where the container is responsible for synchronizing the
entity bean with its data store.

Transaction Control
The container works with the bean's EJB Object to transparently
provide transaction support for the bean. By ensuring that all method
calls from a client first passes thru’ the EJB object, the container vendor
can wrap method calls with it’s transaction context before calling the
EJB methods.

407
EJB: Home Interface

§ Factory interface for the bean:


– Interface provided by EJB developer
– Class generated by vendor tool

§ One factory class per bean class


§ Factory instance is installed into the server’s naming service

Version 2.0 408

Communicating With the EJB


The bean developer provides the home interface that is used by the
container to create the home object.

Home Interface
The home interface represents the factory for the bean class, and can be
implemented by the container or by one or more other classes provided
by the vendor. The term used to represent the factory implementation is
the home object. In many cases, the home interface is implemented
directly by the container, making the container the home object.

The bean developer provides a home interface to represent the


appropriate factory methods for the corresponding bean. The home
object is typically generated at installation time as a vendor-specific
class that implements this home interface.

The factory is used to create instances of enterprise beans. This factory


instance is installed into the namespace of the server as part of the
installation process of the enterprise bean so clients can locate the home
to create and remove bean instances.

408
EJB: Remote Interface

§ Interface is provided by bean developer.


§ Implementation is provided by container tools, which include:
– Stubs and skeletons
– The EJB Object

Version 2.0 409

The bean developer provides the remote interface content. During


deployment, the container tool provides the implementation of this
interface by providing a stub that can be downloaded to the client and a
class that is instantiated as the EJB Object.

409
EJB: EJB Object

§ The EJB Object is a wrapper object that acts as a proxy to the EJB
instance.
– Interface provided by Bean developer
– Implementation class generated by vendor tool

§ Each business method has a corresponding wrapper method in the


EJB Object
– Wrapper method implements container- provided services

Version 2.0 410

This is a remote object that acts as a proxy for your enterprise bean. All
method calls from the client are actually made on the EJB Object. The
EJB Object works with the container to provide services to the
enterprise bean transparently, before delegating the method call to the
enterprise bean itself.

The methods on your bean can never be invoked directly by a client. If


this happened, there would be no method interpositioning to allow for
transparent service support, such as transactions.

When a client obtains a reference to an EJB, it is actually a reference to


its EJB Object. This EJB Object is a custom wrapper class generated
specifically to support your bean. When your bean class is installed into
the server, the installation process generates this custom proxy class for
you.

When the client invokes the business method on an EJB Object


instance, the generated code for the EJB Object will provide service
support and then delegate the method call to the corresponding method
in the associated bean instance.

410
EJB: Types of EJBs

§ Session Beans
– Stateless
– Stateful

§ Entity Beans

§ Message Driven Beans(MDB)

Version 2.0 411

Session Bean. Session Beans are extensions of the client application


and are responsible for managing processes or tasks. A session bean
represents a single client on an EJB server. A client can access an
application on an EJB server by invoking the session bean’s methods.
Session Beans are used for implementing business logic, processes and
workflow.
There are two types of Session Beans : Stateless and Stateful

Stateless Session Beans. Stateless Session Beans don’t maintain


conversational state for the client.
Stateful Session Beans.Stateful Session Beans can hold client state
across multiple method invocations.

Entity Bean. Entity Beans model real-world objects. These objects are
usually rows or records in some kind of persistent storage, like a
database. Entity beans represent data stored in a persistent storage and
they are used for storing and retrieving persistent data.
Message Driven Beans. Message Driven Bean (MDB) new to EJB
2.0, is a server side component that receives asynchronous messages
from other systems.

411
Stateless Session Bean – Life Cycle

Does not Exist


State

1. newInstance()
2. setSessionContext(sc)
ejbRemove()
3. ejbCreate()

Method Ready
Pool
Business
method call

Source: “Understanding stateful and stateless session bean life cycle,” n.d

Version 2.0 412

412
Example 1 – Stateless Session Bean

§ The example given below is a demonstration of how we can create


Stateless session beans.
§ Here we are developing a bean module which we can use in any
application (including banking application) that requires Rupee
value to be converted into Dollars or Yen.
§ The client application, written in JSP gives an interface to the user
to enter any value in Rupees. By clicking on the appropriate button
(Dollar or Yen), we get the corresponding value of Rupees in Dollars
or Yen.

Version 2.0 413

413
Stateless Session Bean – Sample Exercise
//Calculator.java - Remote Interface

package stateless;
import javax.ejb.*;
import java.rmi.*;

public interface Calculator extends EJBObject


{
public double calculateDollar(double rs) throws
RemoteException;
public double calculateYen(double rs) throws
RemoteException;
}

414
//CalculatorBean.java - Bean class
package stateless;
import javax.ejb.*;
import java.rmi.*;

public class CalculatorBean implements SessionBean


{
public double calculateDollar(double rs)
{
double value=rs/40;
return value;
}
public double calculateYen(double rs)
{
double value=rs/20;
return value;
}
public void ejbCreate() {}
public void setSessionContext(SessionContext ctx) {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbRemove() {}

415
//CalculatorHome.java - Home Interface

package stateless;
import javax.ejb.*;
import java.rmi.*;

public interface CalculatorHome extends EJBHome


{
public Calculator create() throws RemoteException,
CreateException;
}

----------------------------------------------------------------------------
//ejb-jar.xml

<!DOCTYPE ejb-jar PUBLIC '-//Sun Microsystems, Inc.//DTD Enterprise


JavaBeans 1.1//EN' 'http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd'>

<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>CalculatorBean</ejb-name>
<home>stateless.CalculatorHome</home>
<remote>stateless.Calculator</remote>
<ejb-class>stateless.CalculatorBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>

</ejb-jar>

416
//weblogic-ejb-jar.xml

<!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD


WebLogic 8.1.0 EJB//EN'
'http://www.bea.com/servers/wls810/dtd/weblogic-ejb-jar.dtd'>

<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>CalculatorBean</ejb-name>
<jndi-name>CalculatorBean</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>

----------------------------------------------------------------------------------------------------------

417
//index.jsp(Client)

<%@page
import="javax.naming.*,stateless.*,javax.rmi.*,javax.ejb.*,java.rmi.*,java.util.*,java.io.*
" %>
<html>
<body>
<form>
Enter Rs <input type=text name=t1>
<input type=submit name=b1 value=dollar>
<input type=submit name=b1 value=yen>
</form>
</body>
</html>

<%! CalculatorHome ch;


public void jspInit()
{
try{
Properties props=new Properties();

props.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialC
ontextFactory");

props.put(Context.PROVIDER_URL,"t3://localhost:7001");
Context ic=new InitialContext(props);
Object o=ic.lookup("CalculatorBean");

ch=(CalculatorHome)PortableRemoteObject.narrow(o,CalculatorHome.cla
ss);
}catch(Exception e){System.out.println(e);}
}

%>
<% String btn=request.getParameter("b1");
if(btn!=null)
{ String val=request.getParameter("t1");
double val1=Double.parseDouble(val);
if(btn.equals("dollar"))
{
Calculator rem=ch.create();
out.println(rem.calculateDollar(val1));
}
else
{
Calculator rem=ch.create();
out.println(rem.calculateYen(val1));
}
}
%>

418
//web.xml (for client application)

<?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>

<display-name>Welcome to Conversion App</display-name>


<description>Welcome to Conversion App</description>

<servlet>
<servlet-name>hello</servlet-name>
<jsp-file>index.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/index.jsp</url-pattern>
</servlet-mapping>

</web-app>

419
Stateful Session Bean – Life Cycle

Does not System Exception


exist state
create(arg) ejbRemove()
Bean
Timeout

Passive
1. newInstance()
2. setSessionContext(sc)
3. ejbCreate(arg) ejbPassivate()

ejbActivate()

Method call Method


ready state

Version 2.0 Source: “Understanding stateful and stateless session bean life cycle,” n.d. 420

420
Example 2 : Stateful Session Bean

§ The example below gives the customer of Green Bank options of


selecting from a range of products, viz. Credit Cards. The customer
can select more than one card depending on his needs.
§ This application allows multiple conversation between the client and
the application, enabling the user to add or delete the selections he
has made. Since the application uses a stateful session bean, it
remembers all the previous selections made.

Version 2.0 421

421
//Card.java – Remote Interface

package newcard;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;

public interface Card extends EJBObject


{
public void addCard(String n) throws RemoteException;
public Vector display() throws RemoteException;
public void removeCard(String n) throws RemoteException;
}

---------------------------------------------------------------------------------------

422
//CardBean.java – Bean class

package newcard;
import javax.ejb.*;
import java.rmi.*;
import javax.rmi.*;
import java.util.*;

public class CardBean implements SessionBean


{
String card;
Vector v;
public void setSessionContext(SessionContext ctx) {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbRemove() {}

public void ejbCreate()


{
card=" ";
v = new Vector();
}

public void addCard(String name)


{
v.addElement(name);
}

public Vector display()


{
return v;
}

public void removeCard(String name)


{
int i=v.indexOf(name);
v.remove(i);
}
}

----------------------------------------------------------------------------------------

423
//CardHome.java – Home Interface

package newcard;
import javax.ejb.*;
import java.rmi.*;

public interface CardHome extends EJBHome


{
public Card create() throws RemoteException, CreateException;
}

----------------------------------------------------------------------------------------

424
//ejb-jar.xml

<!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>
<enterprise-beans>
<session>
<ejb-name>CardBean</ejb-name>
<home>newcard.CardHome</home>
<remote>newcard.Card</remote>
<ejb-class>newcard.CardBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>

<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>CardBean</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>

</ejb-jar>

-------------------------------------------------------------------------------------------

425
//weblogic-ejb-jar.xml

<!DOCTYPE weblogic-ejb-jar PUBLIC '-//BEA Systems, Inc.//DTD WebLogic 8.1.0


EJB//EN' 'http://www.bea.com/servers/wls810/dtd/weblogic-ejb-jar.dtd'>

<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>CardBean</ejb-name>

<jndi-name>CardBean</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>

-------------------------------------------------------------------------------------------

426
\\index.jsp – Client Interface

<%@page
import="javax.naming.*,newcard.*,javax.rmi.*,javax.ejb.*,java.rmi.*,java.util.*
,java.io.*" %>
<html>
<body>
<form>
<h1><center>Green Bank Ltd</center></h1>
<fieldset>
<legend>
Select the Credit Card from the list:
</legend>

<select name="t1">
<option value="Creditcard">Green Bank Credit Card</option>
<option value="GreenAirwayscard">Green Bank Green Airways Credit
Card</option>
<option value="IndianOilcard" selected="selected">Green Bank Indian Oil Credit
Card</option>
<option value="LifeStylecard">Green Bank Life Style Credit Card</option>
<option value="Vodafonecard">Green Bank Vodafone Credit Card</option>
</select>
</fieldset>

<p>
<fieldset>
<legend>
And Click on the button below to indicate which credit cards you are interesed
in(you are welcome to select more than one type of credit card), remove the
card you have selected or just display your selection
</legend>

<input type=submit name="b1" value=" add ">


<input type=submit name="b1" value="display">
<input type=submit name="b1" value="remove ">
</p>
</fieldset>
</form>
</body>
</html>

<%! CardHome ch;


Card rem;
public void jspInit()

427
{
try{
Properties props=new Properties();

props.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLI
nitialContextFactory");

props.put(Context.PROVIDER_URL,"t3://localhost:7001");
Context ic=new InitialContext(props);
Object o=ic.lookup("CardBean");

ch=(CardHome)PortableRemoteObject.narrow(o,CardHome.class);
}catch(Exception e){System.out.println(e);}
try
{
rem=ch.create();
}catch(Exception e){System.out.println(e);}
}

%>
<% String btn=request.getParameter("b1");
if(btn!=null)
{ String val=request.getParameter("t1");
if(btn.equals(" add "))
{
rem.addCard(val);
out.println(val+" just added");

}
if(btn.equals("display"))
{
out.println(rem.display());

}
if(btn.equals("remove "))
{
rem.removeCard(val);
out.println(val+" just removed");

}
}
%>

428
//web.xml – Web Application deployment descriptor

<?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>

<display-name>Welcome to Course App</display-name>


<description>Welcome to Course App</description>

<servlet>
<servlet-name>card</servlet-name>
<jsp-file>index.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>card</servlet-name>
<url-pattern>/index.jsp</url-pattern>
</servlet-mapping>

</web-app>

-------------------------------------------------------------------------------------------

429
//weblogic.xml
<!DOCTYPE weblogic-web-app PUBLIC "-//BEA Systems, Inc.//DTD Web
Application 8.1//EN" "http://www.bea.com/servers/wls810/dtd/weblogic810-
web-jar.dtd">

<weblogic-web-app>

</weblogic-web-app>

430
Lab Set up Guide & Assignments

Copyright © 2008, Wipro Limited, Bangalore

431
Setting up Path and Classpath

Set the path :


Ensure that you set the correct path for the JDK directory for compiling your
EJB source codes.
The path should point the JDK 1.5 bin directory.
For example :
D:\bea\jdk150_06\bin;

Set the classpath :


The classpath needs to be set for the EJB. The classpath should contain the
path the weblogic.jar. The path to this directory will usually be
D:\bea\weblogic92\server\lib\weblogic.jar.
Just check whether this path matches with the path for weblogic.jar within
your system, before setting the classpath.

Developing an EJB Application


Create a folder named Calculator(in any drive you like). This folder will be
considered as the application root.
Within this folder create two more folders named META-INF and stateless.
stateless folder is for the package. In case you are not using any package to
store your ejb classes, these classes can be stored directly under root.
Store the java source files(for ex: Calculator.java, CalculatorHome.java and
CalculatorBean.java) within the package stateless and compile it .
Create two xml files, ejb-jar.xml and weblogic-ejb-jar.xml .and store
them within the META-INF folder.

432
Creating a Jar file
Now once the application is ready, you have to create a JAR file which
includes all the class files related to EJBs and the deployment descriptors. The
jar file can be created from the command prompt.
The syntax of the command for creating Jar files is :
jar –cvf <jarfile name> <the class files> META-INF\*.*
Example :
D:\calculator> jar –cvf calculator.jar *.class META-INF\*.*
Ensure that you are within the calculator directory/folder while executing this
command.

Developing a Web Application for the client


Create the index.jsp file using any editor and store it within the root(You
can also store this file within any directory as demonstrated in the second
example).
Create a folder named WEB-INF within the root(calculator folder).
Within WEB-INF folder create a folder named classes. Within classes
folder create one more folder stateless. This folder represents the package
within which you are storing your ejb classes. Copy all the classes which you
have created compiling your ejb source files to this folder.(In the first
example, these classes will be Calculator.class, CalculatorHome.class,
CalculatorBean.class)
Create web.xml(deployment descriptor) using any editor as demonstrated.
Store this web.xml file within WEB-INF directory.
Once our web application is ready, we will create a WAR file, which will
contain the entire web application.
Go the command prompt. Ensure that the current directory is
D:\calculator(the root of this application).

433
The command for creating the war file is same as that of creating a jar file.
jar –cvf <warfile name> <the html and jsp files related with web
app> WEB-INF\*.*
Example :
D:\bea> jar –cvf calculator-client.war index.jsp WEB-INF\*.*
Once the jar and war files are created, your application is ready for
deployment.

To create a new Weblogic Domain


Click On Programs -> BEA Products -> Tools -> Configuration
Wizard
BEA Weblogic Configuration Wizard Welcome screen appears.
You will see
Create a new Weblogic Domain
option selected by Default.
Click on Next.
You see the Select Domain Source screen.
The default selection here is
Generate a Domain configured automatically to support the
following BEA products :
Weblogic Server(Required).
Since our requirement is the same, we are not going to change any setting
here, we will click on Next.
Now you will a screen which says Configure Administrator Username
and Password.
Username by default is weblogic. Don’t change it.
Specify the user password as weblogic and repeat it in the Confirm
User Password text box.
Click on Next.
Now you are in Configure Server Start Mode and JDK screen.
Let the Server Start Mode be Development Mode(which is the default
selection).

434
For JDK Selection, we will choose
Sun SDK 1.5.0_06@D:\bea\jdk150_06
from the BEA supplied JDKs(again this is the default selection)
Click on Next.
We, now move on to Customize Environment and Service Settings.
Don’t change any setting here. Just click on Next.
Now you are in Create Weblogic Domain screen.
Here you are going to specify a name for your domain.
In the text box where you have to specify a Domain Name,
type TRP_Weblogic_Domain(or it can be any logical name of your
choice).
Do not change the Domain Location.
Click on Create.

To Start the Admin Server for WebLogic Domain


Click On Programs -> BEA Products -> User Projects ->
TRP_Weblogic_Domain -> Start Admin Server for Weblogic
Server Domain

To Start the Admin Server Console


Click On Programs -> BEA Products -> User Projects ->
TRP_Weblogic_Domain -> Admin Server Console
When it prompts for username and password, type
Username : weblogic
Password : weblogic
The Admin Server Console screen appears.

435
Steps for deploying an EJB or a Web Application
In the left pane of the Administration Console,
Click on Lock and Edit tab.
Under the section Domain Structures, you will see
TRP_Weblogic_Domain listed. Click on deployments for this domain.
On the right hand pane, under summary of deployments you will observe
that no application is deployed(when you open the administration console for
the first time).
Under deployments, you will see install button. Click on it.
You are asked to specify the location of the jar file you have created. Browse
through the locator available there till you locate the particular jar file.
Example :Suppose E:\Green PRP\ejb\Calculator directory contains
Calculator.jar file. As soon as you open this directory/folder you will see a
list of all the jar and war files. One among them will be Calculator.jar. Select
the appropriate jar/war file.
Click on Next button displayed as part of the Install Application
Assistant.
Next you have to choose the Targeting style. We will select
Install this deployment as an application(which is again the default
selection)
Click on Next.
In the Optional Settings Menu, let the default setting remain.
Click on Finish.
Now you will see the jar, which represents your application, displayed in the
deployment list.
It shows the status as distribute initializing.
Click on Activate changes from the Change Centre menu on the Left
hand pane.
Now the status of your application changes to Prepared.
Select your application and click on Start button. You will see a drop down
menu. Select Servicing all requests.

436
You will see the Start Application Assistant asking you to confirm
whether you want to start deployment. Click on Yes.
Now the status of the application deployed changes to active. Now it is ready
to handle requests from clients.
You can install the client application, using the same steps as above.
For deploying EJBs, you will use a JAR file while for deploying client web
applications, you will use a WAR file.
Once the client(web) application is deployed you can select the application
and click on Testing tab. You will see a hyperlink displaying an URL. Click
on the URL to run the application.

437
Summary

In this module you have learnt to:

§ Identify characteristics of different Java Platforms

§ Identify the challenges of an enterprise application

§ Describe J2EE architecture

§ Define the role of various J2EE technologies

Version 2.0 438

438
References

1. Armstrong, E., Ball, J., Bodoff, S., Carson, B.D., Evans, I., Green, D.,
Haase, K., and Jendrock, E. (2005). The J2EETM1.4 tutorial.
Retrieved June 27, 2007, from
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html
2. JNDI overview. (n.d.). Retrieved June 27, 2007, from
http://java.sun.com/products/jndi/tutorial/getStarted/overview/in
dex.html
3. Sun Microsystems (2007). JDBC Basics. Retrieved June 27, 2007
from
http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html
4. Understanding stateful and stateless session bean life cycle.
Retrieved July 8, 2008, from,
http://www.roseindia.net/javabeans/sessionbeanlifecycle.shtml
Urls
http://www.myvacation.com/cgi/ListDest.exe
http://www.myvacation.com/ListDest.htm
Version 2.0 439

439
Version 2.0 440

440