You are on page 1of 128

1

INDEX
Sl.No Experiment Page No

1. Introduction To Html 4

2. Write A Html Program For Feedback Form Of 8


An Website

3. Introduction To Ordered , Unordered , 11


Definition Lists

4. Write A Html Program To Explain About 13


Ordered Lists And Unordered Lists

5. Introduction To Cascading Style Sheets 15

6. Write A Html Program To Explian About 16


Different Stylesheets In Html

7. Introduction To Frames 20

8. Write A Html Program To Explian About 22


Frames In Html?

9. Develop static pages (using Only HTML) of an 26


online Book store.The pages should
resemble:www.amazon.com.The website
should consists the following pages.

Home page

Registration

User Login

Books catalog

10. Introduction To Java Script 32

11. Write A Javascript Program Performing 33


Differnt Mathematical Operations

12. Write A Javascript Program To Check Whether 35


A Chechbox Is Checked Or Not And Displaying
Text In The Text Field Entered

13. Write A Javascript Program To Create 37


Documents On The Fly
2

14. Validate the Registration, user login, user 39


profile and payment by credit card pages using
JavaScript.

15. Introduction To Xml , Dtd 50

16. Develop A DTD And A Xml Document For 55


Employees In An Organisation And Check
Whether The Document Is Valid Or Not ?

17. Create and save anXML document at the 57


server,which contains 10users
Information.write a Program,which takes user
Id as an input and returns th User details by
taking the user information from the XML
document.

18. Write A Program To Display Information From 59


An Xml Document

19. Install TOMCAT web server. Convert the static 61


webpages of assignments 2 into dynamic
webpages using servlets and cookies. Hint:
Users information (user id, password, credit
card number) would be stored in web.xml.
Each user should have a separate Shopping
Cart.

20. Introduction To Servlets 75

21. Program To Explain LifeCycle Of Servlet 76

22. Program To Get Request Data From The Client 79

23. Program To Explain Cookies Concept In 82


Servlets

24. Introduction To Session Managament 89

25. Program To Explain Session Tracking In 91


Servlets

26. Introduction To Java Server Pages 96

27. Program To Explain Accessing Java Beans 103


From Java Server P ages
3

28. Redo the previous task using JSP by converting 107


the static web pages of assignments 2 into
dynamic web pages. Create a database with
user information and books information and
books information. The books catalogue should
be dynamically loaded from the database.
Follow the MVC architecture while doing the
website.

29. Implement the "Hello World!" program using 121


JSP Struts Framework

30. Program to show how to use Resultset to get 124


data From database table

31. Program to show how to use 125


PreparedStatement to insert data into
database table

32. Program to explain ResultSetMetaData 126

INTRODUCTION TO HTML :
4

What is HTML?
HTML is a language for describing web pages.
• HTML stands for Hyper Text Markup Language
• HTML is not a programming language, it is a markup language
• A markup language is a set of markup tags
• HTML uses markup tags to describe web pages
HTML Tags :
HTML markup tags are usually called HTML tags
• HTML tags are keywords surrounded by angle brackets like <html>
• HTML tags normally come in pairs like <b> and </b>
• The first tag in a pair is the start tag, the second tag is the end tag
• Start and end tags are also called opening tags and closing tags
HTML Documents = Web Pages
• HTML documents describe web pages
• HTML documents contain HTML tags and plain text
• HTML documents are also called web pages
The purpose of a web browser (like Internet Explorer or Firefox) is to read
HTML documents and display them as web pages. The browser does not
display the HTML tags, but uses the tags to interpret the content of the
page.
Tag Description

<html> Defines an HTML document

<body> Defines the document's body

<h1> to <h6> Defines header 1 to header 6

<hr /> Defines a horizontal rule

<!--> Defines a comment


5

HTML Paragraphs
Paragraphs are defined with the <p> tag.
HTML Line Breaks
Use the <br /> tag if you want a line break (a new line) without starting a
new paragraph
Forms
A form is an area that can contain form elements.
Form elements are elements that allow the user to enter information (like
text fields, textarea fields, drop-down menus, radio buttons, checkboxes,
etc.) in a form.
A form is defined with the <form> tag.
<form>
input elements
</form>

Input
The most used form tag is the <input> tag. The type of input is specified
with the type attribute. The most commonly used input types are explained
below.

Text Fields

Text fields are used when you want the user to type letters, numbers, etc. in
a form.
<form>
First name:
<input type="text" name="firstname" />
<br />
Last name:
<input type="text" name="lastname" />
</form>

How it looks in a browser:


Top of Form

First name:

Last name:
6

Bottom of Form
Note that the form itself is not visible. Also note that in most browsers, the
width of the text field is 20 characters by default.
Radio Buttons
Radio Buttons are used when you want the user to select one of a limited
number of choices.
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>

How it looks in a browser:


Top of Form

Male

Female

Bottom of Form
Note that only one option can be chosen.
Checkboxes
Checkboxes are used when you want the user to select one or more options
of a limited number of choices.
<form>
I have a bike:
<input type="checkbox" name="vehicle" value="Bike" /><br />
I have a car:
<input type="checkbox" name="vehicle" value="Car" /><br />
I have an airplane:
<input type="checkbox" name="vehicle" value="Airplane" />
</form>

How it looks in a browser:


Top of Form
7

I have a bike:

I have a car:

I have an airplane:

Bottom of Form
The Form's Action Attribute and the Submit Button
When the user clicks on the "Submit" button, the content of the form is sent
to the server. The form's action attribute defines the name of the file to send
the content to. The file defined in the action attribute usually does
something with the received input.
<form name="input" action="html_form_submit.asp" method="get">
Username:<input type="text" name="user" />
<input type="submit" value="Submit" />
</form>

How it looks in a browser:


Top of Form
Submit

Username:

Form Tags

Tag Description
<form> Defines a form for user input
<input> Defines an input field
<textarea> Defines a text-area (a multi-line text input control)
<label> Defines a label to a control
<fieldset> Defines a fieldset
<legend> Defines a caption for a fieldset
<select> Defines a selectable list (a drop-down box)
<optgroup> Defines an option group
<option> Defines an option in the drop-down box
<button> Defines a push button
<isindex> Deprecated. Use <input> instead
8

Program 1:
write a html program for feedback form of an website

Code:
<html>
<head>
<title>example for forms</title>
</head>
<body>
<h1>Feedback Form</h1>
<p>please fill out this form to help us improve our
site</p>
<form method="post">
<p><label>Name:
<input type="text" name="name" size="25"/>
</label></p>
<p><label>Comments:<br/>
<textarea name="comments" rows="4"
cols="50"></textarea>
</label></p>
<p><label>E-mail Address:
<input type="password" name="email"
size="25"/>
</label></p>
<p>
<strong>Things you liked:</strong><br/>
<label>Site design
<input name="thingsliked"
type="checkbox" value="Design"/>
</label>
<label>Links
<input name="thingsliked"
type="checkbox" value="Case"/>
</label>
<label>Ease of use
<input name="thingsliked"
type="checkbox" value="Ease"/>
</label>
<label>Images
<input name="thingsliked"
type="checkbox" value="Images"/>
</label>
<label>SourceCode
9

<input name="thingsliked"
type="checkbox" value="code"/>
</label>
</p>
<p>
<strong>How did you get to our site?:</strong><br/>
<label>Search Engine
<input name="howtosite" type="radio"
value="search engine" checked="checked"/>
</label>
<label>Links from other site
<input name="howtosite" type="radio"
value="link" />
</label>
<label>Deitel.com web site
<input name="howtosite" type="radio"
value="deitel.com" />
</label>
<label>Reference in a book
<input name="howtosite" type="radio"
value="book" />
</label>
<label>other
<input name="howtosite" type="radio"
value="other" />
</label>
</p>
<p>
<label>Rate our site:
<select name="rating">
<option
selected="selected">Amazing</option>
<option>10</option>
<option>9</option>
<option>8</option>
<option>7</option>
<option>6</option>
<option>5</option>
<option>4</option>
<option>3</option>
<option>2</option>
<option>1</option>
<option>Awful</option>
</select>
</label>
</p>
<p>
10

<input type="submit" value="submit your


entries"/>
<input type="reset" value="clear your
entries"/>
</p>
</form>
</body>
</html>

output:
11

INTRODUCTION TO ORDERED , UNORDERED , DEFINITION


LISTS:

HTML supports ordered, unordered and definition lists.


Unordered Lists
An unordered list is a list of items. The list items are marked with bullets
(typically small black circles).
An unordered list starts with the <ul> tag. Each list item starts with the <li>
tag.
<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>

Here is how it looks in a browser:


• Coffee
• Milk
Inside a list item you can put paragraphs, line breaks, images, links, other
lists, etc.
Ordered Lists
An ordered list is also a list of items. The list items are marked with
numbers.An ordered list starts with the <ol> tag. Each list item starts with
the <li> tag.
<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>

Here is how it looks in a browser:


1. Coffee
2. Milk
Inside a list item you can put paragraphs, line breaks, images, links, other
lists, etc.

Definition Lists
12

A definition list is not a list of single items. It is a list of items (terms), with a
description of each item (term).
A definition list starts with a <dl> tag (definition list).
Each term starts with a <dt> tag (definition term).
Each description starts with a <dd> tag (definition description).
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>

Here is how it looks in a browser:


Coffee
Black hot drink
Milk
White cold drink
Inside the <dd> tag you can put paragraphs, line breaks, images, links,
other lists, etc
List Tags

Tag Description
<ol> Defines an ordered list
<ul> Defines an unordered list
<li> Defines a list item
<dl> Defines a definition list
<dt> Defines a term (an item) in a definition list
<dd> Defines a description of a term in a definition list
<dir> Deprecated. Use <ul> instead
<menu> Deprecated. Use <ul> instead

Program 2:
write a html program to explain about ordered lists and
unordered lists

Code:
<html>
<head>
13

<title> Example to explain lists </title>


</head>
<body>
<h1>Best features of internet </h1>
<ul type=A>
<li> You can meet people across world </li>
<li> Can access to new media like
<ul>
<li>Games </li>
<li>new applications
<ol>
<li> for business </li>
<li> for pleasure </li>
</ol>
</li>

<li type=square>around the clock news </li>


<li type=square>search engines</li>
<li type=square> shoping </li>
<li type=square> programing
<ol>
<li> XML </li>
<li> JAVA </li>
<li> HTML </li>
<li> XHTML </li>
<li> New languages </li>
</ol>
</li>
</ul>
</li>
<li> LInks </li>
<li> keeping in touch with old firends </li>
<li> it is a technology of future </li>
</ul>

</body>
</html>

Output:
14

INTRODUCTION TO CASCADING STYLE SHEETS :


15

The HTML Style Attribute


The purpose of the style attribute is:
To provide a common way to style all HTML elements.
Styles was introduced with HTML 4, as the new and preferred way to style
HTML elements. With HTML styles, styles can be added to HTML elements
directly by using the style attribute, or indirectly by in separate style sheets
(CSS files).
What is CSS?
• CSS stands for Cascading Style Sheets
• Styles define how to display HTML elements
• Styles were added to HTML 4.0 to solve a problem
• External Style Sheets can save a lot of work
• External Style Sheets are stored in CSS files
Styles Solved a Big Problem
HTML was never intended to contain tags for formatting a document.
HTML was intended to define the content of a document, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2
specification, it started a nightmare for web developers. Development of
large web sites, where fonts and color information were added to every
single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
In HTML 4.0, all formatting could be removed from the HTML document, and
stored in a separate CSS file.All browsers support CSS today.CSS Saves a
Lot of Work!CSS defines HOW HTML elements are to be displayed.Styles are
normally saved in external .css files. External style sheets enable you to
change the appearance and layout of all the pages in a Web site, just by
editing one single file!

Program 3:
write a html program to explian about different stylesheets in
html

code:
16

Inline stylesheet:

<html>
<head >
<title> Example for inline styles </title>
<body>
<p> This text does not have any style applied to it. </p>

<p style= "font-size:20pt"> This text has <em> font-size 20 pt


applied to it </em> </p>

<p style="font-size:20pt; color:0000FF"> This text is in BLUE


color with font size 2o pt </p>
</body>
</html>
Output:

Embedded stylesheet:

<html>
<head >
<title> Example for embeded style sheets </title>
<style type="text/css">
em { background-color:#0000ff; }
h1 { font-family:arial,sans-serif }
p { font-size:15pt}
17

.special{color:red}
</style>
</head>
<body>
<p> This line text had font size 15pt which was effected using
embeeded style sheet for p tag </p>

<em> This line of text is effected by embedded style sheet with


backgournd color blue </em>

<h1> Heading with arial font instead of times new roman by using
embedded style for h1 tag </h1>

<p class="special"> This text is effected with red color by using


embeeded style class </p>
</body>
</html>
Output:

External stylesheet:

Styles.css:-

em { background-color:#0000ff; }

h1 { font-family:arial,sans-serif }
18

p { font-size:15pt}

.special{color:red}

External.html:-

<html>

<head>
<title> Demonstration on external style sheet linking </title>
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>

<body>

<p> This line text had font size 15pt which was effected using
embeeded style sheet for p tag </p>

<em> This line of text is effected by embedded style sheet with


backgournd color blue </em>

<h1> Heading with arial font instead of times new roman by using
embedded style for h1 tag </h1>

<p class="special"> This text is effected with red color by using


embeeded style class </p>

</body>
</html>

Output:
19

INTRODUCTION TO FRAMES:
20

With frames, you can display more than one HTML document in the same
browser window. Each HTML document is called a frame, and each frame is
independent of the others.
The disadvantages of using frames are:
• The web developer must keep track of more HTML documents
• It is difficult to print the entire page
The Frameset Tag
• The <frameset> tag defines how to divide the window into frames
• Each frameset defines a set of rows or columns
• The values of the rows/columns indicate the amount of screen area
each row/column will occupy
The Frame Tag
• The <frame> tag defines what HTML document to put into each frame
In the example below we have a frameset with two columns. The first
column is set to 25% of the width of the browser window. The second
column is set to 75% of the width of the browser window. The HTML
document "frame_a.htm" is put into the first column, and the HTML
document "frame_b.htm" is put into the second column:
<frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>

Note: The frameset column size value can also be set in pixels
(cols="200,500"), and one of the columns can be set to use the remaining
space (cols="25%,*").

Basic Notes - Useful Tips


If a frame has visible borders, the user can resize it by dragging the border.
To prevent a user from doing this, you can add noresize="noresize" to the
<frame> tag.
Add the <noframes> tag for browsers that do not support frames.
21

Important: You cannot use the <body></body> tags together with the
<frameset></frameset> tags! However, if you add a <noframes> tag
containing some text for browsers that do not support frames, you will have
to enclose the text in <body></body> tags! See how it is done in the first
example below.
Frame Tags

Tag Description
<frameset> Defines a set of frames
<frame> Defines a sub window (a frame)
<noframes> Defines a noframe section for browsers that do not handle frames
<iframe> Defines an inline sub window (frame)

Program 4:
write a html program to explian about frames in html?

Code:
Welcome.html:-
22

<html>
<body>
<h1><center>welcome to our site</center></h1>
</body>
</html

Registration.html:-

<html>
<head>
<title>registration</title>
</head>
<body>
<form name="registration" action="registration.html"
method="get">
<table>
<tr>
<td>user name:</td>
<td><input type="text box" name="uname"/>
</td>
</tr>
<tr>
<td>password:</td>
<td><input type="password" name="pwd"/>
</td>
</tr>
<tr>
<td>confirm password:</td>
<td><input type="password" name="cpwd"/>
</td>
</tr>
<tr>
<td>email id:</td>
<td><input type="text box" name="uemail"/>
</td>
</tr>
<tr>
<td>gender</td>
<td><input type="radio" name="gender" value="male"
checked="true"/>
male&nbsp
<input type="radio" name="gender" value="female"/>
female
</td>
</tr>
<tr>
23

<td>address</td>
<td><textarea rows="3" cols="30"
name="uaddress"/></textarea></td>
</tr>
<tr>
<td><input type="submit" value="register"/><input type="reset"
value="clear"/></td>
</tr>
</form>
</table>
</body>
</html>

Main.html:-

<html>
<body>
<h3><center>This is the main page</center></h3><br/>
<h3><center><u>our site provides the following
facilities</u></h3>
<ul>
<li> You can meet people across world </li>
<li> Can access to new media like Games,business,new
softwares.</li>
<li> keeping in touch with old firends </li>
<li> it is a technology of future </li>
</ul>
</body>
</html>

Login.html:-

<html>
<head>
<title>login</title>
</head>
<body>
<table>
<tr>
24

<td>user name:<td>
<td><input type="text box" name="uname"/>
</td>
</tr>
<tr>
<td>password:<td>
<td><input type="password" name="pwd"/>
</td>
</tr>
<tr>
<td><input type="submit" value="login"/>
</td>
</tr>
</body>
</html>

Nav.html:-

<html>
<body>
<a href="main.html" target="main">about us</a><br/>
<a href="registration.html" target="main">register</a><br/>
<a href="login.html" target="main">login</a>
</body>
</html>

Frames.html:-

<html>
<head>
<title>example to explain frames</title>
</head>
<frameset cols="130,*">
<frame name="leftframe" src="./nav.html"/>
<frameset rows="80,*">
<frame name="welcome" src="welcome.html"/>
25

<frame name="main" src="main.html"/>


</frameset>
<noframes>
<body>
<p>this page uses frames,but your browser
does not support them.</p>
</body>
</noframes>
</frameset>

</html>
Output:

Program 5:

Develop static pages (using Only HTML) of an online Book


store.The pages should resemble:www.amazon.com.The
website should consists the following pages.
• Home page
• Registration
• User Login
26

• Books catalog

Code:
Main page:

<html>

<head>

<title>home page</title>

</head>

<body>

<center><b><h1>welcome to amazon.com</h1></b><br><br>

<form method="post"action="login.html">

<input type="submit"value="click">registration user login hear

</center>

</body>

</html>

Login page:

<html>

<head>

<title>login page</title>

</head>

<body>

<center>

<form method="post" action="login.html">

<p><strong>name:</strong>

<input type="text" name="username" size="25">

</p>

<p><strong>password</strong>
27

<input name="pass" type="password" size="6"></p>

<p><strong>male</strong>

<input type="radio" value="male"<hacked>&nbsp&nbsp</p>

<p><strong>female</strong>

<option><input type="radio" value="female"<hacked>&nbsp;</p>

<input type="submit" value="submit">&nbsp&nbps

<input type="reset" value="reset">

<a href="registration.html">new users register hear </a>

</form>

</center>

</body>

</html>

Registration:

<html>

<head>

<title>registration</title>

</head>

<body>

<center>

<form method="post" action="login.html">

<p><strong>name:</strong>

<input type="text" name="username" size="25">

</p>

<p><strong>password</strong>

<input name="pass" type="password" size="6"></p>

<p><strong>male</strong>
28

<input type="radio" value="male"<hacked>&nbsp&nbsp</p>

<p><strong>female</strong>

<input type="radio" value="female" </p>

<p><strong>address:</strong>

<textarea name="address" row="6" cols="20">

</textarea>

</p>

<p><strong>mobile no:</strong>

<input type="text" name="phno" size="10">

</p><br><br>

<input type="submit" value="submit">

<input type="reset" value="reset">

</form>

</center>

</body>

</html>

Books Catalog:

<html>

<head>

<title>books catalog</title>

</head>

<body>

<center><h1><p>welcome to books catalog</p></h1>

<table border="1"width="25%"height="50%">

<tr>
29

<th>computers</th>

<th>electronics</th>

<th>biotech</th>

<th>mechanical</th>

</tr>

<tr>

<td>

</body>

</html>

Output:
30
31
32

INTRODUCTION TO JAVA SCRIPT:


What is JavaScript?
• JavaScript was designed to add interactivity to HTML pages
• JavaScript is a scripting language
• A scripting language is a lightweight programming language
• JavaScript is usually embedded directly into HTML pages
• JavaScript is an interpreted language (means that scripts execute
without preliminary compilation)
• Everyone can use JavaScript without purchasing a license
What can a JavaScript do?
• JavaScript gives HTML designers a programming tool - HTML
authors are normally not programmers, but JavaScript is a scripting
language with a very simple syntax! Almost anyone can put small
"snippets" of code into their HTML pages
• JavaScript can put dynamic text into an HTML page - A
JavaScript statement like this: document.write("<h1>" + name +
"</h1>") can write a variable text into an HTML page
• JavaScript can react to events - A JavaScript can be set to execute
when something happens, like when a page has finished loading or
when a user clicks on an HTML element
• JavaScript can read and write HTML elements - A JavaScript can
read and change the content of an HTML element
• JavaScript can be used to validate data - A JavaScript can be used
to validate form data before it is submitted to a server. This saves the
server from extra processing
• JavaScript can be used to detect the visitor's browser - A
JavaScript can be used to detect the visitor's browser, and - depending
on the browser - load another page specifically designed for that
browser
• JavaScript can be used to create cookies - A JavaScript can be
used to store and retrieve information on the visitor's computer
To insert a JavaScript into an HTML page, we use the <script> tag.
Inside the <script> tag we use the type attribute to define the
scripting language.
So, the <script type="text/javascript"> and </script> tells where the
JavaScript starts and ends
By entering the document.write command between the <script> and
</script> tags, the browser will recognize it as a JavaScript command
and execute the code line
33

Program 6:
write a javascript program performing differnt mathematical
operations

Code:
<HTML>
<HEAD><center><b>USING JAVASCRIPT WITH COMBO BOX (SELECT
TYPE)</center></b></HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
function fun()
{
x=document.f1.t1.value;
y=document.f1.t2.value;
/* to find the selected option combo box
document.f1.s1.selectedIndex */
st=document.f1.s1.options[document.f1.s1.selectedIndex].val
ue;
if(st=='add')
{ document.f1.t3.value=eval(x)+eval(y) }
else
if(st=='mult')
{ document.f1.t3.value=eval(x)*eval(y) }
else
if(st=='sub')
{ document.f1.t3.value=eval(x)-eval(y) }

}
</SCRIPT>
<FORM NAME=f1>
<CENTER><b>
FIRSTNO:<INPUT TYPE=TEXT NAME=t1 SIZE=5><BR>
SECONDNO:<INPUT TYPE=TEXT NAME=t2 SIZE=5><BR>
SELECT AND PRESS TAB TO GET RESULT:
<SELECT NAME=s1 onBlur="fun()">
<option value="mult">mulitply</option>
<option value="add" selected>addition</option>
<option value="sub">subtract</option>
</SELECT>
<BR>
RESULT:<INPUT TYPE=TEXT NAME=t3 SIZE=5>
<BR>
<INPUT TYPE=RESET></b>
</FORM>
34

</BODY></HTML>

Output:
35

Program 7:
write a javascript program to check whether a chechbox is
checked or not and displaying text in the text field entered

Code:
<html>
<head>
<title>Objects</title>
<script language="JavaScript">
<!-- hide
function first() {
// creates a popup window with the
// text which was entered into the text element
alert("The value of the textelement is: " +
document.myForm.myText.value);
}
function second() {
// this function checks the state of the checkbox
var myString= "The checkbox is ";
// is checkbox checked or not?
if (document.myForm.myCheckbox.checked) myString+= "checked"
else myString+= "not checked";
// output string
alert(myString);
}
// -->
</script>
</head>
<body bgcolor=lightblue>
<form name="myForm">
<input type="text" name="myText" value="hai how r u">
<input type="button" name="button1" value="Button 1"
onClick="first()">
<br>
<input type="checkbox" name="myCheckbox" CHECKED>
<input type="button" name="button2" value="Button 2"
onClick="second()">
</form>
<p><br><br>
<script language="JavaScript">
<!-- hide
document.write("The background color is: ");
document.write(document.bgColor + "<br>");
36

document.write("The text on the second button is: ");


document.write(document.myForm.button2.value);
// -->
</script>
</body>
</html>

Output:
37

Program 8:
write a javascript program to create documents on the fly

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

</head>
<body>
<form>
<input type=button value="On-the-fly" onClick="openWin3()">
</form>
</body>
</html>

Output:
39

Program 9:
40

Develop static pages (using only HTML) of an online Book store. The pages
should resemble :www.amazon.com. The website should consist the
following pages.

• Home page
• Registration and user Login
• User profile page
• Books catalog
• Shopping cart
• Payment by credit cardtt
• Order Conformation

Validate the Registration, user login, user profile and payment by credit
card pages using JavaScript.

Code:
Main.html:

<frameset rows=”25%, 75 %”>


<frame src=”top.html” name=”top”>
<frameset cols=”25%,75%”>
<frame src=”left.html” name=”left”>
<frame src=”right.html” name=”right”>
</frameset>
</frameset>
Top.html:
<html>
<body bgcolor=”pink”> <br><br>
<marquee><h1 align=”center”><b><u>ONLINE BOOK
STORAGE</u></b></h1></marquee>
</body>
</html>
Right.html:
<html>
<body bgcolor=”pink”>
<br><br><br><br><br>
<h2 align=”center”>
<b><p> welcome to online book storage. Press login if you are having id
otherwise press registration.
</p></b></h2></body></html>
Left.html:
<html>
<body bgcolor=”pink”>
<h3>
<ul>
41

<li><a href=”login.html” target=”right”><font color=”black”>


LOGIN</font></a></li><br><br>
<li><a href=”reg.html” target=”right”><font color=”black”>
REGISTRATION</font></a></li><br><br>
<li><a href=”profile.html” target=”right”><fontcolor=”black”>
USER PROFILE</font></a></li><br><br>
<li><a href=”catalog.html” target=”right”><fontcolor=”black”>
BOOKS CATALOG</font></a></li><br><br>
<li><a href=”scart.html” target=”right”><font color=”black”>
SHOPPINGCART</font></a></li><br><br>
<li><a href=”payment.html” target=”right”><fontcolor=”black”>
PAYMENT</font></a></li><br><br>
<li><a href=”order.html” target=”right”><font color=”black”>
ORDER CONFIRMATION</font></a></li><br><br>
</ul>
</body>
</html>
login.html:
<html>
<body bgcolor=”pink”><br><br><br>
<script language=”javascript”>
function validate()
{
var flag=1;
if(document.myform.id.value==”“||document.myform.pwd.
value==” “)
{
flag=0;
}
if(flag==1)
{
alert(“VALID INPUT”);
}
else
{
alert(“INVALID INPUT”);
document.myform.focus();
}
}
</script>
<form name=”myform”>
<div align=”center”><pre>
LOGIN ID:<input type=”text” name=”id”><br>
PASSWORD:<input type=”password” name=”pwd”>
42

</pre><br><br>
</div>
<br><br>
<div align=”center”>
<input type=”submit” value=”ok” onClick=”validate()”>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;<input type=”reset” value=”clear”>
</form>
</body>
</html>

reg.html:
<html>
<body bgcolor=”pink”><br><br>
<script language=”javascript”>
function validate()
{
var flag=1;
if(document.myform.name.value==””||
document.myform.addr.value==””||
document.myform.phno.value==””||
document.myform.id.value==””||
document.myform.pwd.value==””)
{
flag=0;
}
var str=document.myform.phno.value;
var x;
for(var i=0;i<str.length;i++)
{
x=str.substr(i,1)
if(!(x<=9))
{
flag=0;
break;
}
}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
43

}
}
</script>
<form name="myform">
<div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input type="type" name="addr"><br>
CONTACT NUMBER:<iput type="text" name="phno"><br>
LOGINID :<input type="text" name="id"><br>
PASSWORD :<input type="password"
name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" onClick="validate()">&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear">
</form></body></html>

catalog.html:
<html>
<body bgcolor="pink"><br><br><br>
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok" name="button1">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2">
</body>
</html>

order.html:
<html>
<body bgcolor="pink"><br><br><br>
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
TITLE :<input type="text" name="title"><br>
NO.OF BOOKS :<input type="text" name="no"><br>
COST OF BOOK:<input type="text"name="cost"><br>
DATE :<input tpe="text" name="date"><br></pre><br><br>
</div>
44

<br><br>
<div align="center">
<input type="submit" value="ok" name="button1"> &nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2">
</body>
</html>

payment.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.pwd.value==""||
document.myform.amount.value==""||
document.myform.num.value=="")
{
flag=0;
}
var str=document.myform.amount.value;
var x;
for(var i=0;i<str.length;i++)
{
x=str.substr(i,1);
if(!(x<=9))
{
flag=0;
break;
}
}
str=document.myform.num.value;
for(var i=0;i<str.lenght;i++)
{
x=str.substr(i,1);
if(!(x<=9))
{
flag=0;
break;
}
}
if(flag==1)
{
45

alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD :<input type="password" name="pwd"><br>
AMOUNT :<input type="text" name="amount"><br>
CREDITCARDNUMBER:<input type="PASSWORD"
name="num+"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok"
onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</form>
</body>
</html>

profile.html:
<html>
<body bgcolor="pink"><br><br><br>
<script language="javascript">
function validate()
{
var flag=1;
if(document.myform.id.value==""||
document.myform.pwd.value=="")
{
flag=0;
46

}
if(flag==1)
{
alert("VALID INPUT");
}
else
{
alert("INVALID INPUT");
document.myform.focus();
}
}
</script>
<form name="myform">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
PASSWORD:<input type="password" name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok"
onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" >
</form>
</body>
</html>
47
48
49
50
51

INTRODUCTION TO XML,DTD :
52

XML:
XML was designed to transport and store data.
HTML was designed to display data.
What is XML?
• XML stands for EXtensible Markup Language
• XML is a markup language much like HTML
• XML was designed to carry data, not to display data
• XML tags are not predefined. You must define your own tags
• XML is designed to be self-descriptive
• XML is a W3C Recommendation
The Difference Between XML and HTML
XML is not a replacement for HTML.
XML and HTML were designed with different goals:
• XML was designed to transport and store data, with focus on what data
is.
• HTML was designed to display data, with focus on how data looks.
HTML is about displaying information, while XML is about carrying
information.
XML Does not DO Anything
Maybe it is a little hard to understand, but XML does not DO anything. XML
was created to structure, store, and transport information.
The following example is a note to Tove from Jani, stored as XML:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The note above is quite self descriptive. It has sender and receiver
information, it also has a heading and a message body.
But still, this XML document does not DO anything. It is just pure
information wrapped in tags. Someone must write a piece of software to
send, receive or display it.
XML is Just Plain Text
53

XML is nothing special. It is just plain text. Software that can handle plain
text can also handle XML.
However, XML-aware applications can handle the XML tags specially. The
functional meaning of the tags depends on the nature of the application.
With XML You Invent Your Own Tags
The tags in the example above (like <to> and <from>) are not defined in
any XML standard. These tags are "invented" by the author of the XML
document.
That is because the XML language has no predefined tags.
The tags used in HTML (and the structure of HTML) are predefined. HTML
documents can only use tags defined in the HTML standard (like <p>, <h1>,
etc.).
XML allows the author to define his own tags and his own document
structure.
XML is Not a Replacement for HTML
XML is a complement to HTML.
It is important to understand that XML is not a replacement for HTML. In
most web applications, XML is used to transport data, while HTML is used to
format and display the data.

XML is a software- and hardware-independent tool for carrying


information.
XML is Everywhere
We have been participating in XML development since its creation. It has
been amazing to see how quickly the XML standard has developed, and how
quickly a large number of software vendors has adopted the standard.
XML is now as important for the Web as HTML was to the foundation of the
Web.
XML is everywhere. It is the most common tool for data transmissions
between all sorts of applications, and is becoming more and more popular in
the area of storing and describing information.
XML Separates Data from HTML
54

If you need to display dynamic data in your HTML document, it will take a lot
of work to edit the HTML each time the data changes.
With XML, data can be stored in separate XML files. This way you can
concentrate on using HTML for layout and display, and be sure that changes
in the underlying data will not require any changes to the HTML
XML Simplifies Data Sharing
In the real world, computer systems and databases contain data in
incompatible formats.
XML data is stored in plain text format. This provides a software- and
hardware-independent way of storing data.
This makes it much easier to create data that different applications can
share.
XML Simplifies Data Transport
With XML, data can easily be exchanged between incompatible systems.
One of the most time-consuming challenges for developers is to exchange
data between incompatible systems over the Internet.
Exchanging data as XML greatly reduces this complexity, since the data can
be read by different incompatible applications.
XML Simplifies Platform Changes
Upgrading to new systems (hardware or software platforms), is always very
time consuming. Large amounts of data must be converted and incompatible
data is often lost.
XML data is stored in text format. This makes it easier to expand or upgrade
to new operating systems, new applications, or new browsers, without losing
data.
XML Makes Your Data More Available
Since XML is independent of hardware, software and application, XML can
make your data more available and useful.
Different applications can access your data, not only in HTML pages, but also
from XML data sources.
With XML, your data can be available to all kinds of "reading machines"
(Handheld computers, voice machines, news feeds, etc), and make it more
available for blind people, or people with other disabilities.
XML is Used to Create New Internet Languages
A lot of new Internet languages are created with XML.
Here are some examples:
55

• XHTML the latest version of HTML


• WSDL for describing available web services
• WAP and WML as markup languages for handheld devices
• RSS languages for news feeds
• RDF and OWL for describing resources and ontology
• SMIL for describing multimedia for the web

DTD :
• A Document Type Definition (DTD) defines the legal building blocks of
an XML document. It defines the document structure with a list of legal
elements and attributes.
• A DTD can be declared inline inside an XML document, or as an
external reference.

Internal DTD Declaration


If the DTD is declared inside the XML file, it should be wrapped in a
DOCTYPE definition with the following syntax:
<!DOCTYPE root-element [element-declarations]>

External DTD Declaration


If the DTD is declared in an external file, it should be wrapped in a DOCTYPE
definition with the following syntax:
<!DOCTYPE root-element SYSTEM "filename">

Why Use a DTD?


With a DTD, each of your XML files can carry a description of its own format.
With a DTD, independent groups of people can agree to use a standard DTD
for interchanging data.
Your application can use a standard DTD to verify that the data you receive
from the outside world is valid.
You can also use a DTD to verify your own data.
56

Program 10:
Develop a DTD and a xml document for employees in an
organisation and check whether the document is valid or not ?

Code:
Emps.dtd:-

<!ENTITY % text "#PCDATA">


<!ELEMENT emps (emp+,dept)>
<!ELEMENT emp (name,sal,desig)>
<!ELEMENT name (first-name,last-name)>
<!ELEMENT first-name (%text;)>
<!ELEMENT last-name (%text;)>
<!ELEMENT sal (%text;)>
<!ELEMENT desig (%text;)>
<!ELEMENT dept (dept-name,desc)>
<!ELEMENT dept-name (%text;)>
<!ELEMENT desc (%text;)>
<!ATTLIST emp empno ID #REQUIRED>
<!ATTLIST emp managerid IDREF #IMPLIED>
<!ATTLIST emp working (yes | no) 'yes'>
<!ATTLIST dept deptno ID #REQUIRED>

Emp.xml:-

<?xml version="1.0"?>
<!DOCTYPE emps SYSTEM "emps.dtd" >
<emps>
<emp empno="e201" working="yes">
<name>
<first-name> raj </first-name>
<last-name> kumar </last-name>
</name>
<sal>4400.0</sal>
<desig> engineer </desig>
57

</emp>
<emp empno="e102" managerid="e201" working="yes">
<name>
<first-name> durga </first-name>
<last-name> rao </last-name>
</name>
<sal>16500.0</sal>
<desig> manager </desig>
</emp>
<dept deptno="d101">
<dept-name> SCIENCE </dept-name>
<desc> Developes science projects </desc>
</dept>
</emps>

validateDocument.java:-

import java.io.*;
import org.w3c.dom.*;
import com.ibm.xml.parser.*;
public class ValidateDocument
{
public static void main(String s[])throws Exception
{
FileInputStream fis=new FileInputStream(s[0]);
Parser p=new Parser("errors");
p.readStream(fis);
System.out.println("document validated");
}
}

Output:

Javac ValidateDocument.java

Java ValidateDocument

If there are no errors in xml document the you will get


“ document validated “ message
Otherwise you will get the errors in your xml document
58

Program 11:
Create and save anXML document at the server,which contains 10 users
Information.write a Program,which takes user Id as an input and returns the
User details by taking the user information from the XML document.
PROCEDURE:
Step 1:
Copy xmlbeans – current-src.zip to a directory(E:\tr)
Then extract the content of above jar file using the following
command
E:\tr> jar XVF Xmlbeans-current-src.zip
Step 2:
Search for the ant tool for complining all the extracted java files
and set that to path
Set Path=C:\j2sdkee1.4\bin;%Path%;
Step 3:
Move to the directory Xmlbeans-1.0.3 make sure that there is no
folder with the name
build.
Then give the command
E:\tr\Xmlbeans-1.0.3>ant
As part of the Xmlbeans-1.0.3/bin we get the tool called
scomp(schema compiler)
Step 4:
Create the Xml directory in E:\
59

Then given the command


E:\Xmlb>set path=E:\tr\Xmlbeans-1.0.3\bin;%path%
E:\Xmlb>scomp
No error means Xmlbeans is loaded correctly.
Create src,cls directories under Xmlb.

Step 5:

Open the Xmlspy>file>new>xsdfile>ok

Schema design > schema setting>

Select notarget namespace

Give the root element name as user then right click and select add
child/sequence then right click select add child/element and give
the name as user id repeat this,and add the elements as

Userid User— name

Address --------- city

State

Save this as user.xsd in E:\xmlb directory

E:\xmlb>scomp--- srg –d cls user.xsd

Output:

1 XYZ

III I.T Rajahmundry

A.P
60

Program 12:
write a program to display information from an xml document

Code:
import org.w3c.dom.*;
import com.ibm.xml.parser.*;
import java.io.*;
public class GetEmpDetails
{
public static void main(String s[])throws Exception
{
Parser p=new Parser("myerrors");
TXDocument td=p.readStream(new FileInputStream(s[0]));
Element emps=td.getDocumentElement();
NodeList emps_childs=emps.getChildNodes();
int len=emps_childs.getLength();
for(int i=0;i<len;i++)
{

Node emps_child=emps_childs.item(i);
if(emps_child.getNodeType()==Node.ELEMENT_NODE)
{

if(emps_child.getNodeName().equals("emp"))
{

Element emp=(Element)emps_child;
NodeList
nl=emp.getElementsByTagName("name");

Element name=(Element)nl.item(0);
61

Node
first_name=(name.getElementsByTagName("first-name")).item(0);

Node
first_name_text=(first_name.getChildNodes()).item(0);

System.out.print(first_name_text.getNodeValue()+"\t");
Node
last_name=(name.getElementsByTagName("last-name")).item(0);
Node
last_name_text=(last_name.getChildNodes()).item(0);

System.out.print(last_name_text.getNodeValue()+"\t");
Node
sal=(emp.getElementsByTagName("sal")).item(0);
Node
sal_text=(sal.getChildNodes()).item(0);

System.out.print(sal_text.getNodeValue()+"\t");

System.out.print(emp.getAttribute("empno"));
}
}
System.out.println("\n");
}
}
}

Output:

javac GetEmpDetails.java

java GetEmpDetails

raj kumar 4400 e201

durga rao 16500 e102


62

Program 13:
Install TOMCAT web server. Convert the static webpages of assignments 2 into dynamic
webpages using servlets and cookies. Hint: Users information (user id, password, credit card
number) would be stored in web.xml. Each user should have a separate Shopping Cart.

PROCEDURE:

First install the tomcat into the system.


Then make a subdirectly(eg., tr) in the \tomcat\webapps.
Under tr create WEB-INF directory and also place the html files in this tr directory only.
Next under WEB-INF create two subclasses lib,classes and web.xml
Next place all the class files under the classes and jar files(servlet-api.jar,classes12.jar etc…) under lib
subdirectories.
After this start tomcat by giving the following command at the instll_dir>tomcat>bin
Catalina.bat run
At the I.E(web browser) give the url as http;//localhost:8080//tr/htmlfile or servlet url pattern
Portno 8080 is assigned for the tomcat.

Web.xml

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


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Servlet 2.4 Examples</display-name>
<description>
Servlet 2.4 Examples.
</description>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>reg</servlet-class>
</servlet>
63

<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet>
<servlet-name>profile</servlet-name>
<servlet-class>profile</servlet-class>
</servlet>
<servlet>
<servlet-name>catalog</servlet-name>
<servlet-class>catalog</servlet-class>

<servlet-mapping>
<servlet-name>order</servlet-name>
<url-p</servlet>
<servlet>
<servlet-name>order</servlet-name>
<servlet-class>order</servlet-class>
</servlet>
attern>order</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>catalog</servlet-name>
<url-pattern>catalog</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>profile</servlet-name>
<url-pattern>profile</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>reg</url-pattern>
</servlet-mapping>
</web-app>

Main.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink">
64

<br /><br /><br /><br /><br />


<h1 align="center"><U>ONLINE BOOK STORAGE</U></h1><br /><br /><br />
<h2 align="center"><pre>
<b>Welcome to online book storage.
Press LOGIN if you are having id
otherwise press REGISTRATION
</b></pre></h2>
<br /><br /><pre>
<div align="center"><a href="/tr/login.html">LOGIN</a> <a href="/tr/reg.html">
REGISTRATION</a></div></pre></body></html>
Login.html

<html>
<body bgcolor="pink"><br /><br /><br />
<form name="myform" method="post" action="/tr/login">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Reg.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br />
<form name="myform" method="post" action="/tr/reg">
<div align="center"><pre>
NAME :<input type="text" name="name" /><br />
ADDRESS :<input type="text" name="addr" /><br />
CONTACT NUMBER :<input type="text" name="phno" /><br />
LOGINID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
65

</div>
</form>
</body>
</html>

Profile.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br /><br />
<form name="myform" method="post" action="/tr/profile">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Catalog.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body bgcolor="pink"><br /><br /><br />
<form method="post" action="/tr/catalog">
<div align="center"><pre>
BOOK TITLE :<input type="text" name="title" /><br />
</pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" name="button1"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="reset" value="clear" name="button2"/>
</div>
66

</form>
</body>
</html>

Order.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<body bgcolor="pink"><br /><br />


<form method="post" action="/tr/reg">
<div align="center"><pre>
NAME :<input type="text" name="name" /><br />
PASSWORD :<input type="password" name="pwd" />
TITLE :<input type="text" name="title" /><br />
NO. OF BOOKS :<input type="text" name="no" /><br />
DATE :<input type="text" name="date" /><br />
CREDIT CARD NUMBER:<input type="password" name="cno" /><br /></pre><br /><br />
</div>
<br /><br />
<div align="center">
<input type="submit" value="ok" name="button1"/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="reset" value="clear" name="button2"/>
</div>
</form>
</body>
</html>

Login.java

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
67

String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","sco
tt","tiger");
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\"/tr/login.html\">press LOGIN to RETRY</a>");
}
else
{
pw.println("VALID LOGIN ID<br><br>");
pw.println("<h3><ul>");
pw.println("<li><ahref=\"profile.html\"><fontcolor=\"black\">USER
PROFILE</font> </a></li><br><br>");

pw.println("<li><ahref=\"catalog.html\"><fontcolor=\"black\">BOOKS
CATALOG</font></a></li><br><br>");
pw.println("<li><ahref=\"order.html\"><fontcolor=\"black\">ORDER
CONFIRMATION</font> </a></li><br><br>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}
68

Reg.java

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String name=req.getParamenter("name");
String addr=req.getParameter("addr");
String phno=req.getParameter("phno");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
int no=Integer.parseInt(phno);
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","sco
tt","tiger");
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equal(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==1)
{
pw.println("SORRY INVALID ID ALREADY EXITS TRY AGAIN WITH
NEW ID<br><br>");
pw.println("<a href=\"/tr/reg.html\">press REGISTER to RETRY</a>");
}
69

else
{
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insertintologin
values("+names","+addr+","+no+","+id+","+pwd+")");
pw.println("YOUR DETAILS ARE ENTERED<br><br>");
pw.println("<a href=\"/tr/login.html\">press LOGIN to login</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Catlog.java

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String title=req.getParameter("title");
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","sco
tt","tiger");
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
70

pw.println(",div align=\"center\">");
pw.println("TITLE :"+rs.getString(1)+"<br>");
pw.println("AUTHOR :"+rs.getString(2)+"<br>");
pw.println("VERSION :"+rs.getString(3)+"<br>");
pw.println("PUBLISHER :"+rs.getString(4)+"<br>");
pw.println("COST :"+rs.getString(5)+"<br>");
pw.println("</div");
flag=1;
}
if(flag==0)
{
pw.println("SORRY INVALID TITLE TRY AGAIN <br><br>");
pw.println("<a href=\"/tr/catalog.html\">press HERE to RETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Profile.java

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection con=DriverManager.getConnection("jdbc:oracle:thin:
@localhost:1521:orcl","scott","tiger");
Statement stmt=con.createStatement();
71

String sqlstmt="select * from login where id="+id+"";


ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
pw.println("<br><br><br>");
while(rs.next())
{
pw.println("<div align=\"center\">");
pw.println("NAME :"+rs.getString(1)+"<br>");
pw.println("ADDRESS :"+rs.getString(2)+"<br>");
pw.println("PHONE NO :"+rs.getString(3)+"<br>");
pw.println("</div>");
flag=1;
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\"/tr/profile.html\">press HERE to RETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Order.java

import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body bgcolor=\"pink\");
String id=req.getParamenter("id");
String pwd=req.getParameter("pwd");
String title=req.getParameter("title");
String count1=req.getParameter("no");
72

String date=req.getParameter("date");
String cno=req.getParameter("cno");
int count=Integer.parseInt(count1);
try
{
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","sco
tt","tiger");
Statement stmt=con.createStatement();
String sqlstmt="select id,password from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");

}
else
{
Statement stmt2=con.createStatement();
String s="select cost from book where title="+title+"";
ResultSet rs1=stmt2.executeQuery(s);
int flag1=0;
while(rs1.next())
{
flag1=1;
x=Integer.parseInt(rs1.getString(1));
amount=count*x;
pw.println("AMOUNT :"+amount+"<br><br><br><br>");
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insertintodetails
values('"+id+",'"+title+"'+amount+'","'+cno+'")"');
pw.println("YOUR ORDER has taken<br>");
}
if(flag1==0)
{
73

pw.println("SORRY INVALID ID TRY AGAIN ID<br><br>");


pw.println("<a href=\\"/tr/order.html\\">press HERE to RETRY</a>");

}
}
pw.println("</body></html>");
con.close();
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}

Output:
74
75
76

INTRODUCTION TO SERVLETS:

What Is a Servlet?
A servlet is a Java programming language class that is used to extend the capabilities
of servers that host applications access via a request-response programming model.
Although servlets can respond to any type of request, they are commonly used to
extend the applications hosted by web servers. For such applications, Java Servlet
technology defines HTTP-specific servlet classes.
The javax.servlet and javax.servlet.http packages provide interfaces and
classes for writing servlets. All servlets must implement the Servlet interface, which
defines life-cycle methods. When implementing a generic service, you can use or
extend the GenericServlet class provided with the Java Servle API. The
HttpServlet class provides methods, such as doGet and doPost, for handling
HTTP-specific services.
Servlet Life Cycle
The life cycle of a servlet is controlled by the container in which the servlet has been
deployed. When a request is mapped to a servlet, the container performs the following
steps.
1. If an instance of the servlet does not exist, the web container
a. Loads the servlet class.
b. Creates an instance of the servlet class.
c. Initializes the servlet instance by calling the init method. Initialization is
covered in Initializing a Servlet.
2. Invokes the service method, passing request and response objects..
If the container needs to remove the servlet, it finalizes the servlet by calling the
servlet's destroy method.

Program 14:
Program To Explain LifeCycle Of Servlet
77

Code:
hello.html:-

<html>
<body>
<center><u><h3>Program to demonstrate lifecycle of
servlet</h3></u></center>
<form method="get" action="sayhello">
<input type="submit" value="HELLO"/>
</form>
</body>
</html>

/WEB-INF/web.xml:-

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


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- Define servlets that are included in the example application -->
<servlet>
<servlet-name>HS</servlet-name>
<servlet-class>com.nit.hello.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HS</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>

/WEB-INF/classes/HelloServlet.java:-

package com.nit.hello;
import javax.servlet.*;
import java.io.*;
78

public class HelloServlet implements Servlet


{
ServletConfig sc;
public void init(ServletConfig sc)throws ServletException
{
System.out.println("in init method ");
this.sc=sc;
}
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{
System.out.println("in service method");
PrintWriter out=res.getWriter();
out.println("<b> Hello from first servlet </b> ");
}
public void destroy()
{
System.out.println("in destroy method");
}
public ServletConfig getServletConfig()
{
return sc;
}
public String getServletInfo()
{
return "helloservlet";
}
}

Output:
79
80

ServletRequest :-
Servlet container takes the request related data from the protocol adapter
and sets them into the ServletRequest object

ServletRequest object represents the request related data(i.e., usong this


object we can interact with container and get request related information )

Methods of ServletRequest object for retrieving request related information:-

 String getParameter(String)
 Enumeration getPrameterNames()
 String[] getParameterValues(String)

Program 15:
Program To Get Request Data From The Client

Code:
form.html:-

<html>
<body>
<center><u><h3>Program to get the request data from the
client</h3></u></center>
<form method="get" action="s1">
First-Name:&nbsp;&nbsp;&nbsp;<input type="text"
name="firstname"/><br/><br/>
Last-Name:&nbsp;&nbsp;&nbsp;&nbsp;<input type="text"
name="lastname"/><br/><br/>
Father-Name:&nbsp;<input type="text"
name="fathername"/><br/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

/WEB-INF/web.xml:-
<?xml version="1.0" encoding="ISO-8859-1"?>
81

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- Define servlets that are included in the example application -->
<servlet>
<servlet-name>HS</servlet-name>
<servlet-class>com.nit.reqdata.RequestData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HS</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
</web-app>

/WEB-INF/classes/RequestData.java:-
package com.nit.reqdata;
import java.io.*;
import javax.servlet.*;
public class RequestData extends GenericServlet
{ public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{ String fn=req.getParameter("firstname");
String ln=req.getParameter("lastname");
String fathername=req.getParameter("fathername");
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body>");
pw.println("<center><u><h3>Program to get the request data
from the client</h3></u></center>");
pw.println("<center><u><h3>The Given Information
are</h3></u></center>");
pw.println("FirstName:&nbsp;&nbsp;"+fn+"<br/>");
pw.println("LastName:&nbsp;&nbsp;"+ln+"<br/>");
pw.println("FatherName:&nbsp;&nbsp;"+fathername+"<br/>");
pw.println("</html></body>");
}
}
Output:
82
83

Cookies:-
Cookie is a small data unit which can be saved into client machine .cookies
are supported by HTTP protocol i.e., the client side http adapter can take the
instructions from the server(in the response message) and save the data
given by the server.

Each and every cookie consist of following information:-

name of the cookie

value of the cookie

maximum age(or time) a cookie can be alive on client machine

path

domain name

To present this cookie information to the servlet , servlet container uses


javax.servlet.http.Cookie abstract class

In HttpServletRequest class the following method is used to get the cookies


associated with current request :-

Cookie[] getCookies()

In HttpServletResponse class the following method is used to add a cookie to


the response:-

addCookie(cookie)

some of the methods Cookie class are :-

String getName() - returns the name of the cookie

String getValue() - returns the value of the cookie

setMaxage(int) - sets the maximum time for which the cookie is alive
on the client

int getMaxage() – gets maxium age of a cookie


84

Program 16:
Program to explain cookies concept in servlets

Code:
Firstform.html:-

<html>
<body>
<center><u><h3>Program to demonstrate use of
Cookies</h3></u></center>
<form method="get" action="ser1">
<center><h3> <u>Enter cookie name and values
</u></h3></center>
Cookie1-name:<input type="text"
name="cookieonename"/>&nbsp;&nbsp;&nbsp;
Cookie1-value:<input type="text"
name="cookieonevalue"/><br/>
Cookie2-name:<input type="text"
name="cookietwoname"/>&nbsp;&nbsp;&nbsp;
Cookie2-value:<input type="text"
name="cookietwovalue"/><br/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

secondform.html:-

<html>
<body>
<center><u><h3>Program to demonstrate use of
Cookies</h3></u></center>
<form method="get" action="ser2">
<br/><br/><br/>

<center><h3> <u><a href="ser2">Click here to view


the added cookies</a> </u></h3></center>

</form>
</body>
</html>
85

/WEB-INF/web.xml:-

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


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>

<!-- Define servlets that are included in the example


application -->
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/ser1</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>servlet2</servlet-name>
<url-pattern>/ser2</url-pattern>
</servlet-mapping>
</web-app>

/WEB-INF/classes/FirstServlet.java:-

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest
req,HttpServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");

PrintWriter pw=res.getWriter();

String cookieonename=req.getParameter("cookieonename");
86

String cookietwoname=req.getParameter("cookietwoname");
String
cookieonevalue=req.getParameter("cookieonevalue");
String
cookietwovalue=req.getParameter("cookietwovalue");
Cookie c1=new Cookie(cookieonename,cookieonevalue);
Cookie c2=new Cookie(cookietwoname,cookietwovalue);
res.addCookie(c1);
res.addCookie(c2);

RequestDispatcher
rd=req.getRequestDispatcher("/SecondForm.html");
rd.forward(req,res);
}
}
/WEB-INF/classes/SecondServlet.java:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet
{
public void doGet(HttpServletRequest
req,HttpServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.println("<html><body>");
pw.println("<center><u><h3>Program to demonstrate Use
of Cookies</h3></u></center>");
pw.println("<center><u><h3>The Added Cookies
are</h3></u></center>");
Cookie c[]=req.getCookies();
for(int i=0;i<c.length;i++)
{
pw.println("CookieName:&nbsp;&nbsp;"+c[i].getName()
+"&nbsp;&nbsp;");
pw.println("cookievalue:&nbsp;&nbsp;"+c[i].getValue());
pw.println("<br/><br/>");
}
pw.println("<br/><br/><br/><br/>");
pw.println("<center><h3> <u><a
href=\"./FirstForm.html\">Click here to add more cookies</a>
</u></h3></center>");
pw.println("</html></body>");
}
}
87

Output:
88
89
90

INTRODUCTION TO SESSION MANAGAMENT :


Maintaining Client State
Many applications require that a series of requests from a client be associated with one
another. Web-based applications are responsible for maintaining such state, called a
session, because HTTP is stateless. To support applications that need to maintain
state, Java servlet technology provides an API for managing sessions and allows
several mechanisms for implementing sessions.
Accessing a Session
Sessions are represented by an HttpSession object. You access a session by calling
the getSession method of a request object. This method returns the current session
associated with this request, or, if the request does not have a session, it creates one.
Associating Objects with a Session
You can associate object-valued attributes with a session by name. Such attributes are
accessible by any web component that belongs to the same web context and is
handling a request that is part of the same session.
Notifying Objects That Are Associated with a Session
Recall that your application can notify web context and session listener objects of
servlet life-cycle events (Handling Servlet Life-Cycle Events). You can also notify
objects of certain events related to their association with a session such as the
following:
• When the object is added to or removed from a session. To receive this
notification, your object must implement the
javax.servlet.http.HttpSessionBindingListener interface.
• When the session to which the object is attached will be passivated or activated.
A session will be passivated or activated when it is moved between virtual
machines or saved to and restored from persistent storage. To receive this
notification, your object must implement the
javax.servlet.http.HttpSessionActivationListener interface.

Session Management
Because there is no way for an HTTP client to signal that it no longer needs a session,
each session has an associated timeout so that its resources can be reclaimed. The
timeout period can be accessed by using a session's [get|
set]MaxInactiveInterval methods.
To ensure that an active session is not timed out, you should periodically access the
session via service methods because this resets the session's time-to-live counter.
When a particular client interaction is finished, you use the session's invalidate
method to invalidate a session on the server side and remove any session data.
91

Session Tracking
A web container can use several methods to associate a session with a user, all of
which involve passing an identifier between the client and the server. The identifier can
be maintained on the client as a cookie, or the web component can include the identifier
in every URL that is returned to the client.
If your application uses session objects, you must ensure that session tracking is
enabled by having the application rewrite URLs whenever the client turns off cookies.
You do this by calling the response's encodeURL(URL) method on all URLs returned
by a servlet. This method includes the session ID in the URL only if cookies are
disabled; otherwise, it returns the URL unchanged.

Program 17:
Program to explain session tracking in servlets

Code :
92

Firstform.html:-

<html>
<body>
<center><u><h3>Program to demonstrate Session
Tracking</h3></u></center>
<form method="get" action="ser1">

First-Name:&nbsp;&nbsp;&nbsp;<input type="text"
name="firstname"/><br/><br/>
Last-Name:&nbsp;&nbsp;&nbsp;&nbsp;<input type="text"
name="lastname"/><br/><br/>
Father-Name:&nbsp;<input type="text"
name="fathername"/><br/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

Secondform.html:-

<html>
<body>
<center><u><h3>Program to demonstrate Session Tracking-
Second Form</h3></u></center>
<form method="get" action="ser2">

DateofBirth:&nbsp;<input type="text"
name="dob"/><br/><br/><br/>
Address:&nbsp;&nbsp;&nbsp;&nbsp;<textarea
name="address" cols="20" rows="5"></textarea><br/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

/WEB-INF/web.xml:-

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


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
93

<!-- Define servlets that are included in the example


application -->
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/ser1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>servlet2</servlet-name>
<url-pattern>/ser2</url-pattern>
</servlet-mapping>
</web-app>

/WEB-INF/classes/FirstServlet.java:-

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest
req,HttpServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
HttpSession hs=req.getSession();
String firstname=req.getParameter("firstname");
String lastname=req.getParameter("lastname");
String fathername=req.getParameter("fathername");
hs.setAttribute("firstname",firstname);
hs.setAttribute("lastname",lastname);
hs.setAttribute("fathername",fathername);
RequestDispatcher
rd=req.getRequestDispatcher("/SecondForm.html");
rd.forward(req,res);
}
}

/WEB-INF/classes/FirstServlet.java:-
94

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet
{
public void doGet(HttpServletRequest
req,HttpServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
HttpSession hs=req.getSession();
String dob=req.getParameter("dob");
String address=req.getParameter("address");
String firstname=(String)hs.getAttribute("firstname");
String lastname=(String)hs.getAttribute("lastname");
String
fathername=(String)hs.getAttribute("fathername");
pw.println("<html><body>");
pw.println("<center><u><h3>Program to demonstrate
Session Tracking</h3></u></center>");
pw.println("<center><h3>The Details Given by you
are</h3></center>");
pw.println("First Name
is:<h3>"+firstname+"</h3><br/>");
pw.println("Last Name is:<h3>"+lastname+"</h3><br/>");
pw.println("Father name
is:<h3>"+fathername+"</h3><br/>");
pw.println("Date of Birth:<h3>"+dob+"</h3><br/>");
pw.println("address is:<h3>"+address+"</h3><br/>");

}
}

Output :
95
96
97

INTRODUCTION TO JAVA SERVER PAGES :

What Is a JSP Page?


A JSP page is a text document that contains two types of text: static data, which can be
expressed in any text-based format (such as HTML, SVG, WML, and XML, and JSP
elements, which construct dynamic content.
The recommended file extension for the source file of a JSP page is .jsp. The page
can be composed of a top file that includes other files that contain either a complete
JSP page or a fragment of a JSP page. The recommended extension for the source file
of a fragment of a JSP page is .jspf.
The JSP elements in a JSP page can be expressed in two syntaxes--standard and
XML--though any given file can use only one syntax. A JSP page in XML syntax is an
XML document and can be manipulated by tools and APIs for XML documents.
The Life Cycle of a JSP Page
A JSP page services requests as a servlet. Thus, the life cycle and many of the
capabilities of JSP pages (in particular the dynamic aspects) are determined by Java
Servlet technology.
When a request is mapped to a JSP page, the web container first checks whether the
JSP page's servlet is older than the JSP page. If the servlet is older, the web container
translates the JSP page into a servlet class and compiles the class. During
development, one of the advantages of JSP pages over servlets is that the build
process is performed automatically.
Translation and Compilation
During the translation phase each type of data in a JSP page is treated differently.
Static data is transformed into code that will emit the data into the response stream.
JSP elements are treated as follows:
• Directives are used to control how the web container translates and executes the
JSP page.
• Scripting elements are inserted into the JSP page's servlet class. See Chapter 16
for details.
• Expression language expressions are passed as parameters to calls to the JSP
expression evaluator.
• jsp:[set|get]Property elements are converted into method calls to
JavaBeans components.
• jsp:[include|forward] elements are converted into invocations of the Java
Servlet API.
• The jsp:plugin element is converted into browser-specific markup for
activating an applet.
98

Both the translation and the compilation phases can yield errors that are observed only
when the page is requested for the first time. If an error is encountered during either
phase, the server will return JasperException and a message that includes the
name of the JSP page and the line where the error occurred.
After the page has been translated and compiled, the JSP page's servlet (for the most
part) follows the servlet life cycle described in Servlet Life Cycle:
1. If an instance of the JSP page's servlet does not exist, the container
a. Loads the JSP page's servlet class
b. Instantiates an instance of the servlet class
c. Initializes the servlet instance by calling the jspInit method
2. The container invokes the _jspService method, passing request and response
objects.
If the container needs to remove the JSP page's servlet, it calls the jspDestroy
method.
Execution
You can control various JSP page execution parameters by using page directives. The
directives that pertain to buffering output and handling errors are discussed here. Other
directives are covered in the context of specific page-authoring tasks throughout the
chapter.
Buffering
When a JSP page is executed, output written to the response object is automatically
buffered. You can set the size of the buffer using the following page directive:
<%@ page buffer="none|xxxkb" %>
A larger buffer allows more content to be written before anything is actually sent back to
the client, thus providing the JSP page with more time to set appropriate status codes
and headers or to forward to another web resource. A smaller buffer decreases server
memory load and allows the client to start receiving data more quickly.
Handling Errors
Any number of exceptions can arise when a JSP page is executed. To specify that the
web container should forward control to an error page if an exception occurs, include
the following page directive at the beginning of your JSP page:

<%@ page errorPage="file_name" %>

The following page directive at the beginning of JSP page indicates that it is serving
as an error page

<%@ page isErrorPage="true" %>


99

JavaBeans Components

JavaBeans components are Java classes that can be easily reused and composed
together into applications. Any Java class that follows certain design conventions is a
JavaBeans component.

JavaServer Pages technology directly supports using JavaBeans components with


standard JSP language elements. You can easily create and initialize beans and get
and set the values of their properties.

JavaBeans Component Design Conventions

JavaBeans component design conventions govern the properties of the class and
govern the public methods that give access to the properties.
A JavaBeans component property can be

• Read/write, read-only, or write-only


• Simple, which means it contains a single value, or indexed, which means it
represents an array of values

A property does not have to be implemented by an instance variable. It must simply be


accessible using public methods that conform to the following conventions:

• For each readable property, the bean must have a method of the form
PropertyClass getProperty() { ... }
• For each writable property, the bean must have a method of the form
setProperty(PropertyClass pc) { ... }

In addition to the property methods, a JavaBeans component must define a constructor


that takes no parameters.

Creating and Using a JavaBeans Component


To declare that your JSP page will use a JavaBeans component, you use a
jsp:useBean element. There are two forms:
<jsp:useBean id="beanName"
class="fully_qualified_classname" scope="scope"/>
and
<jsp:useBean id="beanName"
class="fully_qualified_classname" scope="scope">
<jsp:setProperty .../>
</jsp:useBean>
The second form is used when you want to include jsp:setProperty statements,
described in the next section, for initializing bean properties.
100

The jsp:useBean element declares that the page will use a bean that is stored within
and is accessible from the specified scope, which can be application, session,
request, or page. If no such bean exists, the statement creates the bean and stores it
as an attribute of the scope object .The value of the id attribute determines the name of
the bean in the scope and the identifier used to reference the bean in EL expressions,
other JSP elements, and scripting expressions.). The value supplied for the class
attribute must be a fully qualified class name. Note that beans cannot be in the
unnamed package. Thus the format of the value must be
package_name.class_name.
The following element creates an instance of mypkg.myLocales if none exists, stores
it as an attribute of the application scope, and makes the bean available throughout the
application by the identifier locales:
<jsp:useBean id="locales" scope="application"
class="mypkg.MyLocales"/>

Setting JavaBeans Component Properties


The standard way to set JavaBeans component properties in a JSP page is by using
the jsp:setProperty element. The syntax of the jsp:setProperty element
depends on the source of the property value. Table 12-3 summarizes the various ways
to set a property of a JavaBeans component using the jsp:setProperty element.

Table 12-3 Valid Bean Property Assignments from String Values

Value Source Element Syntax

<jsp:setProperty name="beanName"
String constant property="propName" value="string
constant"/>

<jsp:setProperty name="beanName"
Request parameter
property="propName" param="paramName"/>

<jsp:setProperty name="beanName"

property="propName"/>
Request parameter name that
matches bean property
<jsp:setProperty name="beanName"

property="*"/>

Expression <jsp:setProperty name="beanName"


101

property="propName" value="expression"/>

<jsp:setProperty name="beanName"

property="propName" >

<jsp:attribute name="value">
expression
</jsp:attribute>

</jsp:setProperty>

1. beanName must be the same as that specified for the


id attribute in a useBean element.

2. There must be a setPropName method in the


JavaBeans component.

3. paramName must be a request parameter name.

A property set from a constant string or request parameter must have one of the types
listed in Table 12-4. Because constants and request parameters are strings, the web
container automatically converts the value to the property's type; the conversion applied
is shown in the table.
String values can be used to assign values to a property that has a
PropertyEditor class. When that is the case, the setAsText(String) method is
used. A conversion failure arises if the method throws an
IllegalArgumentException.
The value assigned to an indexed property must be an array, and the rules just
described apply to the elements.
Table 12-4 Valid Property Value Assignments from String Values

Property Type Conversion on String Value

Bean Property Uses setAsText(string-literal)

boolean or Boolean As indicated in java.lang.Boolean.valueOf(String)

byte or Byte As indicated in java.lang.Byte.valueOf(String)

char or Character As indicated in java.lang.String.charAt(0)

double or Double As indicated in java.lang.Double.valueOf(String)

int or Integer As indicated in java.lang.Integer.valueOf(String)


102

float or Float As indicated in java.lang.Float.valueOf(String)

long or Long As indicated in java.lang.Long.valueOf(String)

short or Short As indicated in java.lang.Short.valueOf(String)

Object new String(string-literal)

You use an expression to set the value of a property whose type is a compound Java
programming language type. The type returned from an expression must match or be
castable to the type of the property.

Retrieving JavaBeans Component Properties


The main way to retrieve JavaBeans component properties is by using the JSP EL
expressions. Thus, to retrieve a book title, the Duke's Bookstore application uses the
following expression:
${bookDB.bookDetails.title}
Another way to retrieve component properties is to use the jsp:getProperty
element. This element converts the value of the property into a String and inserts the
value into the response stream:
<jsp:getProperty name="beanName" property="propName"/>
Note that beanName must be the same as that specified for the id attribute in a
useBean element, and there must be a getPropName method in the JavaBeans
component. Although the preferred approach to getting properties is to use an EL
expression, the getProperty element is available if you need to disable expression
evaluation.
103

Program 18:
Program to explain accessing java beans from java server pages

Code:
Firstpage.html:-

<html>
<body>
<center><u><h3>Program to demonstrate accessing javabeans
from jsp</h3></u></center>
<form action="First.jsp">
First-name:<input type="text"
name="firstName"/><br/><br/>
Last-Name:<input type="text"
name="lastName"/><br/></br>
Dateofbirth:<input type="text"
name="dob"/><br/><br/>
Address:<textarea name="address" rows="5"
cols"10"/></textarea><br/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

First.jsp:-

<html>
<body>
<center><u><h3>Program to demonstrate accessing
javabeans from jsp</h3></u></center><br/><br/>
<%@page language="java"
import="com.nit.beans.FirstBean" %>
<jsp:useBean id="bean" scope="session"
class="com.nit.beans.FirstBean">
<jsp:setProperty name="bean" property="*"/>
</jsp:useBean>
104

<center><a href="Second.jsp"><h2>click here to view


Details</h2></a></center>
</body>
</html>

Second.jsp:-

<html>
<body>
<center><u><h3>Program to demonstrate accessing
javabeans from jsp</h3></u></center><br/><br/>
<%@ page language="java"
import="com.nit.beans.FirstBean" %>
<jsp:useBean id="bean" scope="session"
class="com.nit.beans.FirstBean"/>
FirstName is:&nbsp;&nbsp;&nbsp;<jsp:getProperty
name="bean" property="firstName"/><br/><br/>
LastName is:&nbsp;&nbsp;&nbsp;<jsp:getProperty
name="bean" property="lastName"/><br/><br/>
Dateofbirth is:&nbsp;&nbsp;&nbsp;<jsp:getProperty
name="bean" property="dob"/><br/><br/>
address is:&nbsp;&nbsp;&nbsp;<jsp:getProperty
name="bean" property="address"/><br/><br/>

</body>
</html>

/WEB-INF/web.xml:-

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

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app/>

/WEB-INF/classes/FirstBean.java:-

package com.nit.beans;
105

public class FirstBean


{
private String firstName,lastName,address,dob;

public void setFirstName(String fname)


{
firstName=fname;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String lname)
{
lastName=lname;
}
public String getLastName()
{
return lastName;
}
public void setAddress(String addr)
{
address=addr;
}
public String getAddress()
{
return address;
}
public void setDob(String d)
{
dob=d;
}
public String getDob()
{
return dob;
}
}
Output:
106
107

Program 19:
Redo the previous task using JSP by converting the static web pages of
assignments 2 into dynamic web pages. Create a database with user information
and books information and books information. The books catalogue should be
dynamically loaded from the database. Follow the MVC architecture while doing the
website.

PROCEDURE:

1) Create your own directory under tomcat/webapps (e.g. tr1)

2) Copy the html files in tr1

3) Copy the jsp files also into tr1

4) Start tomcat give the following command

Catalina.bat run

At install-dir/bin

5) at I.E give url as http://localhost:8081/tr1/main.html


108

Main.html:
<html>
<body bgcolor=”pink”>
<br><br><br><br><br><br>
<h1 align=”center”>>U>ONLINE BOOK
STORAGE</u></h1><br><br><br>
<h2 align=”center”><PRE>
<b> Welcome to online book storage.
Press LOGIN if you are having id
Otherwise press REGISTRATION
</b></PRE></h2>
<br><br><pre>
<div align=”center”><a href=”/tr/login.html”>LOGIN</a>
href=”/tr/login.html”>REGISTRATION</a></div></pre>
</body></html>

Login.html:
<html>
<body bgcolor=”pink”><br><br><br>
<form name="myform" method="post" action=/tr1/login.jsp">
<div align="center"><pre>
LOGIN ID : <input type="passwors" name="pwd"></pre><br><br>
PASSWORD : <input type="password"
name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
type="reset" value="clear">
</form>
109

</body>
</html>

Reg.html:
<html>
<body bgcolor="pink"><br><br>
<form name="myform" method="post" action="/tr1/reg.jsp">
<div align="center"><pre>
NAME :<input type="text" name="name"><br>
ADDRESS :<input type="text" name="addr"><br>
CONTACT NUMBER : <input type="text" name="phno"><br>
LOGIN ID : <input type="text" name="id"><br>
PASSWORD : <input type="password"
name="pwd"></pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
type="reset" value="clear">
</form>
</body>
</html>
file.html:
<html>
<body bgcolor="pink"><br><br>
<form name="myform" method="post" action="/tr1/profile.jsp">
<div align="center"><pre>
LOGIN ID : <input type="text" name="id"><br>
</pre><br><br>
</div>
110

<br><br>
<div align="center">
<inputtype="submit"value="ok"
onClick="validate()">()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
type="reset" value="clear">
</form>
</body>
</html>

Catalog.html:
<html>
<body bgcolor="pink"><br><br><br>
<form method="post" action="/tr1/catalog.jsp">
<div align="center"><pre>
BOOK TITLE : <input type="text" name="title"><br>
</pre><br><br>
</div>
<br><br>
<div align="center">
<inputtype="submit"value="ok"
name=”button1”>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<inputtype="reset"v
alue="clear" name=”button2”>
</form>
</body>
</html>
Order.html:
<html>
<body bgcolor="pink"><br><br><br>
<form method="post" action="/tr1/order.jsp">
<div align="center"><pre>
LOGIN ID :<input type="text" name="id"><br>
111

PASSWORD : <input type="password" name="pwd"><br>


TITLE :<input type="text" name="title"><br>
NO. OF BOOKS : <input type="text" name="no"><br>
DATE : <input type="text" name="date"><br>
CREDIT CARD NUMBER : <input type="password"
name="cno"><br></pre><br><br>
</div>
<br><br>
<div align="center">
<input type="submit" value="ok"
name=”button1”>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input
type="reset" value="clear" name=”button2”>
</form>
</body></html>
Login.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println(“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter(“id”);
String pwd=request.getParameter(“pwd”);
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection
con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:or
cl”,”scott”,”tiger”);
Statement stmt=con.createStatement();
String sqlstmt=”select id,password from login where id=”+id+” and
password=”+pwd+””;
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
112

while(rs.next())
{
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID<br><br>”);
out.println(“ <a href=\”/tr1/login.html\”>press LOGIN to
RETRY</a>”);
}
else
{
out.println(“VALID LOGIN ID<br><br>”);
out.println(“<h3><ul>”);
out.println(“<li><ahref=\”profile.html\”><fontcolor=\”black\”>
USER PROFILE</font></a></li><br><br>”);

out.println(“<li><ahref=\”catalog.html\”><fontcolor=\”black\”>B
OOKS CATALOG</font></a></li><br><br>”);
out.println(“<li><ahref=\”order.html\”><fontcolor=\”black\”>
ORDER CONFIRMATION</font></a></li><br><br>”);
out.println(“</ul>”);
}
out.println(“<body></html>”);
%>
Reg.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println(“<html><body bgcolor=\”pink\”>”);
String name=request.getParameter(“name”);
113

String addr=request.getParameter(“addr”);
String phno=request.getParameter(“phno”);
String id=request.getParameter(“id”);
String pwd=request.getParameter(“pwd”);
int no=Integer.parseInt(phno);
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection con=
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement();
String sqlstmt=”select id from login”;
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equals(rs.getString(1)))
{
flag=1;
}
}
if(flag==1)
{
out.println(“SORRY LOGIN ID ALREADY EXISTS TRY AGAIN WITH NEW ID
<br><br>”);
out.println(“<a href=\”/tr1/reg.html\”>press REGISTER to RETRY</a>”);
}
else
{
Statement stmt1=con.createStatement ();
114

stmt1.executeUpdate (“insert into login values


(“+name+”,”+addr+”,”+no+”,”+id+”,”+pwd+”)”);
out.println (“YOU DETAILS ARE ENTERED <br><br>”);
out.println (“<a href =\”/tr1/login.html\”>press LOGIN to login</a>”);
}
out.println (“</body></html>”);
%>

Profile.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter(“id”);
Driver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.regiserDriver(d);
Connection con=
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement ();
String sqlstmt=”select * from login where id=”+id+””;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0;
while(rs.next())
{
out.println (“<div align=\”center\”>”);
out.println (“NAME :”+rs.getString(1)+”<br>”);
out.println (“ADDRESS :”+rs.getString(2)+”<br>”);
out.println (“PHONE NO :”+rs.getString(3)+”<br>”);
out.println (“</div>”);
flag=1;
115

}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/profile.html\”>press HERE to RETRY
</a>”);
}
out.println (“</body></html>”);
%>

Catalog.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String title=request.getParameter (“title”);
Driver d=new oracle.jdbc.driver.OracleDriver ();
DriverManager.regiserDriver (d);
Connection con=
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement ();
String sqlstmt=”select * from book where title=”+title+””;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0;
while(rs.next())
{
out.println (“<div align=\”center\”>”);
116

out.println (“TITLE :”+rs.getString(1)+”<br>”);


out.println (“AUTHOR :”+rs.getString(2)+”<br>”);
out.println (“VERSION:”+rs.getString(3)+”<br>”);
out.println (“PUBLISHER :” +rs.getString(4)+”<br>”);
out.println (“COST :” +rs.getString(5)+”<br>”);
out.println (“</div>”);
flag=1;
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/catalog.html\”>press HERE to RETRY
</a>”);
}
out.println (“</body></html>”);
%>

Order.jsp:
<%@page import=”java.sql.*”%>
<%@page import=”java.io.*”%>
<%
out.println (“<html><body bgcolor=\”pink\”>”);
String id=request.getParameter (“id”);
String pwd=request.getParameter (“pwd”);
String title=request.getParameter (“title”);
String count1=request.getParameter (“no”);
String date=request.getParameter (“date”);
String cno=request.getParameter (“cno”);
int count=Integer.parseInt(count1);
Driver d=new oracle.jdbc.driver.OracleDriver ();
DriverManager.regiserDriver (d);
117

Connection con=
DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:orcl”,”scott”,”tiger”);
Statement stmt=con.createStatement ();
String sqlstmt=”select id, password from login”;
ResultSet rs=stmt.executeQuery (sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(1))&& pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
out.println(“SORRY INVALID ID TRY AGAIN ID <br><br>”);
out.println(“<a href=\”/tr1/order.html\”>press HERE to RETRY
</a>”);
}
else
{ Statement stmt2=con.createStatement();
String s=”select cost from book where title=”+title+””;
ResultSet rs1=stmt2.executeQuery(s);
int flag1=0;
while(rs1.next())
{ flag1=1;
x=Integer.parseInt(rs1.getString(1));
amount=count*x;
out.println(“AMOUNT :”+amount+”<br><br><br><br>”);
Statement stmt1=con.createStatement ();
118

stmt1.executeUpdate (“insert into details


(“+id+”,”+title+”,”+amount+”,”+date+”,”+cno+”)”);
out.println (“YOU ORDER HAS TAKEN<br>”);
}
if(flag1==0)
{
out.println(“SORRY INVALID BOOK TRY AGAIN <br><br>”);
out.println(“<a href=\”/tr1/order.html\”>press HERE to RETRY
</a>”);
}
} out.println (“</body></html>”);%>
119
120
121

Program 20:
Implement the "Hello World!" program using JSP Struts Framework

PROCEDURE:
Step 1:
in tomcat install directory
Open tomcat/webapps
Create a subdirectory(ts)
Copy the struts-blank.war file
At that directory path in cmd give the command as
Jar xvf struts-blank.war
Step 2:

create a directory (work in e:\) and copy struts.jar,servelet-appi.jar into work


d directory.Then set the classpath as
set classpath=struts.jar;servlet-api.jar;
122

then copy the ActionOne.class file to webapps/ts/WEB-INF/classes

ActionOne.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
public class ActionOne extends Action
{
publicActionForwardexecute(ActionMappingmapping,ActionFormform,HttpSe
rvletRequest request,HttpServletResponse response)throws Exception
{
System.out.println("---Action executed----");
PrintWriter pw=response.getWriter();
pw.println("HELLO WORLD!");
return null;
}
}

Step 3:
Struts-Config.xml file
<?xml version="1.0" encoding="UTF-8"?>
<struts-config>
<action-mappings>
<action path="/xxx" type="ActionOne"/>
</action-mappings>
</struts-config>
Step 4:
Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init--param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
123

<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<!--Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Struts Tag Library Descriptors -->
<taglib>
<taglib-uri>/tags/struts-bean</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-logic</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-nested</taglib-uri>
<taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-tiles</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
</taglib>
</web-app>

Step 5:
then in I.E give the url as http:localhost:8080/ts/xxx.do
124

Program 21:
Program to show how to use Resultset to get data From database table

Code :

import java.sql.*;
public class ResultSetEx
{
public static void main(String args[]) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:nit","scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from bank");
while(rs.next())
{ int accno=rs.getInt(1);
String name=rs.getString(2);
double bal=rs.getDouble("bal");
System.out.println(accno + "\t" + name + "\t" + bal
+ "\n");
}
125

con.close();
}
}
Output:
Before executing this program create a database table bank as
follows :
Create table bank(accno number,name varchar2(50),bal number)
And insert some data into that table as follows :
Insert into bank values(101,satish,16000)
Insert into bank values(102,Prasad,20000)
Javac ResultSetEx.java
Java ResultSetEx
101 satish 16000
102 prasad 20000

Program 22:
Program to show how to use PreparedStatement to insert data into database
table

Code :

import java.sql.*;
public class InsertEx
{
public static void main(String args[]) throws Exception
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1;nit","scott","tiger");
PreparedStatement ps=con.prepareStatement("insert
into myemp values(?,?)");
ps.setInt(1,101);
ps.setString(2,"satish");
int i=ps.executeUpdate();
System.out.println("i:"+i);
ps.setInt(1,102);
126

ps.setString(2,"prasad");
int j=ps.executeUpdate();
System.out.println("j:" +j);
con.close();
}
}

Output:
Before executing this program create a database table myemp as
follows :
Create table myemp(empno number,empname varchar2(50))
Javac InsertEx
Java InsertEx

Program 23:
Program to explain ResultSetMetaData

Code:

import java.sql.*;
import java.util.*;
public class RSMDEX
{
public static void main(String s[])throws Exception
{
String tablename=s[0];
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:152
1:nit","scott","tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select *
from"+tablename);
ResultSetMetaData rsmd=rs.getMetaData();
127

int col_count=rsmd.getColumnCount();
System.out.println("--------------------------------");
for(int i=1;i<=col_count;i++)
{
System.out.println(rsmd.getColumnName(i) + "\t");
}
System.out.println();
System.out.println("--------------------------------");
while(rs.next())
{
for(inti=1;i<=col_count;i++)
{
int type=rsmd.getColumnType(i);
if(type==Types.INTEGER)
{
System.out.println(rs.getInt(i) + "\t");
}
elseif(type==Types.DOUBLE)
{
System.out.println(rs.getDouble(i) + "\t");
}
else
{
System.out.println(rs.getString(i) + "\t");
}
System.out.println();
}
}
}
}

Output:

Before executing this program create a database table bank as


follows :
Create table bank(accno number,name varchar2(50),bal number)
And insert some data into that table as follows :
Insert into bank values(101,satish,16000)
Insert into bank values(102,Prasad,20000)
128

Insert into bank values(103,babu,30000)


Javac RSMDEX.java
Java RSMDEX
--------------------------------------------
Accno name bal
---------------------------------------
101 satish 16000
102 prasad 20000
103 BABU 30000