Professional Documents
Culture Documents
Version 2.0
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
3
HTML
Version 2.0 4
4
Objectives
Version 2.0 5
5
WEB Architecture
WEB SERVER
WEB SITE
Version 2.0 6
6
Introduction to HTML
The Problem
The Solution:
Version 2.0 7
What is HTML?
7
Features of HTML
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.
Version 2.0 9
9
Types of HTML Tags
Version 2.0 10
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>
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
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.
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
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.
19
List: Glossary List
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
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.
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.
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:
Horizontal Rule:
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
Version 2.0 24
<html>
<body bgcolor=“blue” >
<body background=“image.jpg”>
</html>
24
Semantic Tags: Special Characters
Syntax:
&#char code; or &code;
Example:
< <
> >
& &
“ "
Registered Trade mark ® or ®
Copyright © or ©
Non-Breaking space
Version 2.0 25
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
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
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
29
Example for Merging Cells:
30
Application Tags: Forms
Container: Form
<FORM NAME=“” ACTION=“” METHOD=“”></FORM>
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.
31
Forms: Input Tag
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
Checkbox Checkbox
Version 2.0 32
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
EXAMPLE:
</TEXTAREA>
Version 2.0 33
TEXTAREA:
This component allows to enter a multi-line text, e.g., address.
33
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:
<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
Version 2.0 35
<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: <INPUT TYPE="Radio" NAME="R1"
VALUE="Male"/> Female:
<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>
<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
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
Version 2.0 39
Transaction.html
<Frameset Rows="70%,*">
<frame src ="Transation-select.html" name="upper">
<frame src = "transcationsecondform.html" name="lower">
</frameset>
39
Transaction-select.html
<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
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
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
Version 2.0 43
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
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: <INPUT TYPE="Radio" NAME="R1"
VALUE="Male"/> Female:
<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>
46
Case Study: Bank Application
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)
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
<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
………………………………………………………………………………………………………………………
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
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>
<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>
50
Summary
Version 2.0 51
51
Module 2:
JavaScript
52
Objectives
Version 2.0 53
53
DHTML
Version 2.0 54
54
Introduction to JavaScript
Version 2.0 55
55
Introduction to JavaScript: JavaScript Versus Java
Version 2.0 56
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
Version 2.0 58
58
Elements of JavaScript Program: Variables
§ Data Types
§ Type Casting
Version 2.0 59
59
JavaScript Statements
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
}
60
JavaScript Statements: switch Statement
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
Version 2.0 62
<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
do {
statement
} while (condition)
Version 2.0 63
63
JavaScript Statements: while Statement
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
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
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
Version 2.0 67
</P>
67
Objects: The Document Object
Version 2.0 68
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.
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);
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">
70
Objects: Frame Objects
Version 2.0 71
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
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">
73
Objects: The String Object
Version 2.0 74
74
Objects: The Date Object
Version 2.0 75
75
Defining Objects
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
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
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
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.
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.
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>
82
Time Outs
Handy for periodically updating a Web Page or for delaying the display
of a message or execution of a function.
Version 2.0 83
83
Integrating JavaScript with Java
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
Version 2.0 86
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>");
87
Case Study: Bank Application
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>
89
Case Study: Bank Application
Version 2.0 90
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: <INPUT TYPE="Radio" NAME="R1" VALUE="Male"/> Female:
<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
Version 2.0 95
…………………………………………………………………………………………………………………………………………………..
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;
}
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
Version 2.0 98
<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>
<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
100
Module 3:
JDBC
101
Objectives
102
Introduction to 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
104
Stage 1: Connect
Process
results
Close
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.
105
Connect: A JDBC Driver
Database
JDBC calls commands
Driver
Database
106
JDBC – ODBC Bridge Driver (Type 1 Driver)
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 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.
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)
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)
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:<subprotocol>:<subname>
Database
Protocol Subprotocol
identifier
jdbc:oracle:<driver>:@<database>
111
JDBC URLs: Examples
§ JDBC-ODBC driver
jdbc:odbc:jdbcoodbcDriverDsn
§ OCI driver
jdbc:oracle:oci8:@<TNSNAMES entry>
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?
Class c = Class.forName(
”sun.jdbc.odbc.JdbcOdbcDriver");
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
Close
114
Query: The Statement Object
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.
115
How to Query the Database?
116
Querying the Database: Examples
117
Stage 3: Process the Results
Connect
Query
Step through the results
Close
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
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
userid Number 16
password Varchar2 16
user_type Varchar2 1
status Varchar2 1
120
Examples:
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?
while (rset.next()) { … }
while (rset.next()) {
String name = rset.getString(“NAME");
String supervisor = rset.getString(“SUPERVISOR");
… // Process or display the data
}
A cursor remains valid until the ResultSet object or its parent Statement
object is closed.
123
How to Handle SQL Null Values?
Do not use a primitive type when your query might return a SQL null.
while (rset.next()) {
String year = rset.getString("YEAR");
if (rset.wasNull() {
… // Handle null value}
…}
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.
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
126
How to Close the Connection?
rset.close();
stmt.close();
127
The DatabaseMetaData Object
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?
129
The ResultSetMetaData Object
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?
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
int id = rset.getInt(1);
Date rentaldate = rset.getDate(2);
String status = rset.getString(3);
ID NUMBER
DATE_OF_JOIN DATE
SUPERVISOR VARCHAR2
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
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
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.
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?
PreparedStatement pstmt =
conn.prepareStatement("update STUDENT
set SUPERVISOR = ? where ID = ?");
PreparedStatement pstmt =
conn.prepareStatement("select SUPERVISOR from
STUDENT where ID = ?");
135
How to execute PreparedStatement?
pstmt.setXXX(index, value);
pstmt.executeQuery();
pstmt.executeUpdate();
PreparedStatement pstmt =
conn.prepareStatement("update STUDENT
set SUPERVISOR = ? Where ID = ?");
pstmt.setString(1, "OUT");
pstmt.setInt(2, id);
pstmt.executeUpdate();
136
Case Study: Banking Application (Contd.).
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
137
Examples (Contd.).
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
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.).
userid Number 16
accno Number 16
accc_type Varchar2 1
current_balance Number 15,2
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
}
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.).
accno Number 16
tran_desc Varchar2 40
tran_type Varchar2 1
tran_date date
amount Number 15,2
closing_balance Number 15,2
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);
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 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.
148
How to Create a CallableStatement?
CallableStatement cstmt =
conn.prepareCall("{call " +
ADDITEM +
"(?,?,?)}");
cstmt.registerOutParameter(2,Types.INTEGER);
cStmt.registerOutParameter(3,Types.DOUBLE);
149
How to execute a CallableStatement?
cstmt.setXXX(index, value);
cstmt.execute(statement);
var = cstmt.getXXX(index);
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.).
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:
153
Using Transactions
With other drivers new connections are in autocommit mode and use
conn.setAutoCommit(false) to turn autocommit off.
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();
156
catch(Exception e)
{
System.out.println(e);
try
{
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
158
Summary
159
Module 4:
Servlets
160
Servlets
161
Servlets (Contd.).
162
Objectives
163
Introduction to Servlet
164
Introduction to Servlet: Static Web Site
HTTP Server
HTML HTTP
<HTML>
Aruba
Bermuda
Bahamas
</HTML>
Source: http://www.myvacation.com/ListDest.htm
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
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
167
What is a Servlet?
168
Servlet: Benefits
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
170
Building a Servlet Using the Servlet API
§ Extend HttpServlet
Servlet
§ Code Servlet's life cycle Methods
GenericServlet
HttpServlet
LogonServlet
171
Web Container
172
The following services are provided by a Web Container :
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
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.
175
Servlet Life Cycle (Contd.).
Servlets Container
HTTP Server
Thread
init( )
doGet( )
Servlet
Thread
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
177
Servlet Life Cycle (Contd.).
Servlets Container
HTTP Server
init( )
doGet( )
destroy( )
Servlet
178
Servlet Life Cycle (Contd.).
Servlets Container
HTTP Server
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
180
ServletContext and ServletConfig
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.
181
The init() Method
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.
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.
183
The service() Method
184
The destroy() Method
public void destroy() is called to destroy the servlet and release the
resources.
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.
185
Handling HTTP GET requests
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
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.
187
The servlet Interface
188
ServletConfig Interface
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)
190
ServletContext Interface
Methods:
getServerInfo()
getAttribute(String name)
getAttributeNames()
setAttribute(String name, Object obj)
log(String)
191
Servlet Chaining: RequestDispatcher Interface
1. RequestDispatcher.forward(request,response)
2. RequestDispatcher.include(request,response)
192
Servlet Chaining: forward(request,response)
ServletContext ctx=getServletContext();
RequestDispatcher
dis=ctx.getRequestDispatcher(“/servlet/AnotherServlet”);
dis.forward(request,response);
193
Servlet Chaining: forward (request , response);
Response Generation
194
Servlet Chaining: include(request, response)
ServletContext ctx=getServletContext();
RequestDispatcher
dis=ctx.getRequestDispatcher(“/servlet/AnotherServlet”);
dis.include(request,response);
195
Servlet Chaining: include (request , response);
196
The Cookie class
197
Session Management
198
Session Management (Contd.).
HttpSession Methods:
199
Some common techniques of doing this are to implement one of the
following techniques:
200
Lab Setup Guide
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.
202
Lab Setup Guide (Contd.).
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
Open the browser and type the following URL to display the Web App
HTML Page(or whatever is your starting interface for the app)
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.
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.*;
-------------------------------------------------------------------------------------
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.
208
Example 2: Using getParameterNames()
method
HTML
index.jsp
-------------------------------------------------------------------------------------
<HTML>
<HEAD>
<H2 ALIGN="center" > Customer Registration</H2>
</HEAD>
<BODY bgcolor="blue">
<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: <INPUT TYPE="Radio" NAME="R1"
VALUE="M"/> Female:
<INPUT TYPE="Radio" NAME="R1" VALUE="F"/>
</TABLE>
</FORM>
</BODY>
</HTML>
209
Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;
writer.println(pname+" : "+pvalue);
writer.println("<BR>");
}
writer.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
--------------------------------------------------------------------------------------------------------------------------------
210
Deployment Descriptor(web.xml)
211
Example 3
The example shows how to store cookies and how to retrieve them.
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.*;
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))
{
if(rs.next())
String fn=rs.getString(1);
String ln=rs.getString(2);
res.addCookie(c);
res.addCookie(c);
res.sendRedirect("GeneralForm.html");
else
{
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.*;
-------------------------------------------------------------------------------------
217
web.xml
<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
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.
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.*;
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();
}
}
221
{
if(s2.equals(password))
flag=1;
}
}
else
{
flag=1;
}
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
224
Case Study : Banking Application (Contd.).
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.
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">
<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>
</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>
</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>
<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.*;
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();
}
}
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+"')");
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
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>
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.*;
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();}
}
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())
{
acctype="Savings";
else
acctype="Current";
writer.println("<body
bgcolor ='red'></body>");
writer.println("<table
BORDER=' ' WIDTH='50%' CELLSPACING='2' CELLPADDING='2' align='center'>");
237
Example 4.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
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);
}
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();
}
catch(Exception e)
{
e.printStackTrace();
return false;
}
}
}
240
web.xml
<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.
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>
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>
243
Servlets
Example 5.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
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();
}
}
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.*;
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();
}
}
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())
{
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("</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
250
Module 5:
Java Beans
251
Java Beans
252
Objectives
253
The Software Component Assembly Model
Monolithic Application
Module1
Module2 Module3
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.).
Module1
Module2
Module5
Module3
Module4
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
257
Java’s Approach to Developing Software
Components
258
The Difference between a Bean and a Normal Class
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
260
Java Server Pages
261
Objectives
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.
263
JSP: JSP Request Model
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 is powered by Java and has access to all Java APIs and J2EE APIs
and has inherent Platform independence.
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
266
The Architecture
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
268
Methods of Generated Servlet Class
_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.
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
The difference between these two lies in the way they handle the
request.
270
The Architecture: JSP Model 1 Architecture
Application Server
Client
1. Request
Browser JSP
4. Response
2. Creates
JavaBeans
3. Retrieves Data
JavaBeans
DB
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
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
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.
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.
Expressions are used to insert Java values directly into the output.
275
Example:
276
Expressions: Pre-defined Variables
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.
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.
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:
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.
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:
282
Directives
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.
However, you can also combine multiple attribute settings for a single
directive, as follows:
<%@ directive attribute1="value1"
attribute2="value2"
...
attributeN="valueN" %>
registerconfirmation.jsp
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.*" %>
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.
The included file can be an HTML file, a JSP file, a text file, or a code
file written in the Java programming language.
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
289
Actions: The jsp:include Action
This action lets you insert files into the page being generated.
The syntax looks like this:
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.
290
Actions: The jsp:forward Action
Syntax
<jsp:forward page= “relativeURL" />
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
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" />
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>
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");
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
%>
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;
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);
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>
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
302
<jsp:setProperty>
Syntax:
<jsp:setProperty name="beanInstanceName"
property= "*" |
property="propertyName" [param=parameterName" ] |
property= "propertyName"
value="{ string | <%= expression %> }" } />
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
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.
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
<! –
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
%>
306
store it in a Package deposit
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;
}
}
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.
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
catch(Exception e)
{
out.println(e);
}
311
Session Management
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.
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">
custid.jsp
313
bank.jsp
</BODY> </HTML>
314
Summary
315
Case Study : Banking Application
The example given below shows how a JSP processes the inputs from
an HTML page.
316
Case Study : Banking Application
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.
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>
318
Loginsubmit.jsp
(this jsp page authenticating the login)
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
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
<!– 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);
}
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
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>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: <INPUT TYPE="Radio" NAME="R1"
VALUE="Male"/> Female:
<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
<%
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:
<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">
</SELECT>
337
Case Study : Banking Application
Manager Login:
<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">
<br><br/>
<center>
</center>
</FORM>
</BODY>
</HTML>
339
removecustomer-submit.jsp
<%!
ResultSet rs;
Connection con;
Statement stmt;
String acctype;
int accno,customerno;
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.
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
<%
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>
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");
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>
<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>
………………………………………………………………………………………………………………………………
withdrawal-submit.jsp
%>
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.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();
<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;
}
return true;
}
</script>
351
Deposit-submit.jsp
%>
<%
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.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
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();
%>
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.
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>
<%
Cookie[] k=null;
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);
}
%>
359
<br><b> You have logged in As
:<%=(String)session.getAttribute("username")%></b><br>
<table>
<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>
<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>
<%!
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");
}
catch(Exception e)
{
out.println(e);
}
try
{
stmt=con.createStatement();
rs1=stmt.executeQuery("select * from cust_account_info where user_id="+UserName);
//rs1.next();
%>
<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
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);
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();
%>
364
<CENTER><b>Customer name: <%=FirstName%> <%=LastName%><br>
Customer ID:<%=userid%><br>
Balance : <%=balance%><br></b>
</CENTER>
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>
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");
%>
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);
%>
<OPTION VALUE=<%=Accno%>><%=Accno%>
<%
}
%>
368
</OPTION>
</SELECT>
</tr>
<%}
catch(Exception e)
{
out.println(e);
}
%>
………………………………………………………………………………………………………………………………
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">
Fundtransfer-submit.jsp
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
{
if(rs2.next()==false)
{
%>
<%
}
else
{
tobalance=rs2.getInt("current_balance");
371
stmt1.close();
stmt2.close();
if(amt>frombalance)
{
if(fundtype.equals("own"))
{
%>
<%
}
else
{
%>
<%
}
}
else
{
frombalance = frombalance-amt;
description="- transferred to "+ToAcc;
tobalance=tobalance+amt;
try
{
stmt1 = con.createStatement();
stmt2 = con.createStatement();
stmt1.close();
stmt2.close();
}
catch(Exception e)
372
{
out.println(e);
}
try
{
stmt1 = con.createStatement();
stmt2 = con.createStatement();
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
374
J2EE
375
Objectives
376
Issues in Enterprise Applications
1. Transactions
2. State management
3. Multithreading
4. Resource pooling
5. Security
377
Java 2 Editions
378
Java 2 Editions: Java 2 Platform, Enterprise Edition
Java 2:
RMI EJB
Standard ed.
JNDI JMS
JDBC
J2EE
J2EE JTA
JavaMail Connectors
JNDI : The Java Naming and Directory Interface (JNDI) is an API used
for accessing different kinds of naming and directory services.
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.
380
Java 2 Editions: J2EE Architecture
381
J2EE Architecture (Contd.).
382
Naming Services
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
385
Naming Services: JNDI Interface
JNDI API : Through the use of JNDI API, a java application can access a
variety of naming and directory services.
386
Introduction to RMI
Distributed Computing
§ RPC
§ RMI
Distributed Computing
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.
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.
388
Introduction to RMI: Features of RMI
§ RMI is transparent
389
Introduction to RMI: RMI Architecture
RRL RRL
Transport Layer
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.
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
//Branch.java
import java.rmi.*;
import java.rmi.server.*;
interface Branch extends Remote
{
public String getDescription() throws RemoteException;
}
392
Writing a Simple RMI program (Contd.).
//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..
393
Writing a Simple RMI program (Contd.).
394
Writing a Simple RMI program (Contd.).
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..
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.).
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..
396
Enterprise JavaBeans (EJB)
397
EJB: Defining EJB Technology
398
Defining EJB Technology (Contd.).
399
EJB: EJB Developer Roles
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.
400
EJB: EJB Programming Paradigm
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
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
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.).
404
EJB: EJB Server
§ Services:
– Transaction support
– Data access
– System resource
– Namespace
§ Industry support:
– Application/ middleware servers
– Database servers
405
EJB: EJB Container
406
EJB Container (Contd.).
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
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.
408
EJB: Remote Interface
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
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.
410
EJB: Types of EJBs
§ Session Beans
– Stateless
– Stateful
§ Entity Beans
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
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
412
Example 1 – Stateless Session Bean
413
Stateless Session Bean – Sample Exercise
//Calculator.java - Remote Interface
package stateless;
import javax.ejb.*;
import java.rmi.*;
414
//CalculatorBean.java - Bean class
package stateless;
import javax.ejb.*;
import java.rmi.*;
415
//CalculatorHome.java - Home Interface
package stateless;
import javax.ejb.*;
import java.rmi.*;
----------------------------------------------------------------------------
//ejb-jar.xml
<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
<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>
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)
<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
Passive
1. newInstance()
2. setSessionContext(sc)
3. ejbCreate(arg) ejbPassivate()
ejbActivate()
Version 2.0 Source: “Understanding stateful and stateless session bean life cycle,” n.d. 420
420
Example 2 : Stateful Session Bean
421
//Card.java – Remote Interface
package newcard;
import javax.ejb.*;
import java.rmi.*;
import java.util.*;
---------------------------------------------------------------------------------------
422
//CardBean.java – Bean class
package newcard;
import javax.ejb.*;
import java.rmi.*;
import javax.rmi.*;
import java.util.*;
----------------------------------------------------------------------------------------
423
//CardHome.java – Home Interface
package newcard;
import javax.ejb.*;
import java.rmi.*;
----------------------------------------------------------------------------------------
424
//ejb-jar.xml
<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
<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>
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
<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
431
Setting up Path and Classpath
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.
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.
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.
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
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