Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
INDEX
Sl.No Experiment Page No
1. Introduction To Html 4
7. Introduction To Frames 20
Home page
Registration
User Login
Books catalog
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 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>
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>
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>
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>
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
output:
11
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>
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
</body>
</html>
Output:
14
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>
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>
<h1> Heading with arial font instead of times new roman by using
embedded style for h1 tag </h1>
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>
<h1> Heading with arial font instead of times new roman by using
embedded style for h1 tag </h1>
</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%,*").
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 
<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
</html>
Output:
Program 5:
• 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">
</center>
</body>
</html>
Login page:
<html>
<head>
<title>login page</title>
</head>
<body>
<center>
<p><strong>name:</strong>
</p>
<p><strong>password</strong>
27
<p><strong>male</strong>
<p><strong>female</strong>
</form>
</center>
</body>
</html>
Registration:
<html>
<head>
<title>registration</title>
</head>
<body>
<center>
<p><strong>name:</strong>
</p>
<p><strong>password</strong>
<p><strong>male</strong>
28
<p><strong>female</strong>
<p><strong>address:</strong>
</textarea>
</p>
<p><strong>mobile no:</strong>
</p><br><br>
</form>
</center>
</body>
</html>
Books Catalog:
<html>
<head>
<title>books catalog</title>
</head>
<body>
<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
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
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:
</pre><br><br>
</div>
<br><br>
<div align=”center”>
<input type=”submit” value=”ok” onClick=”validate()”>
<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()">
<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">
<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">
<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()">
<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()">
<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.
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
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.
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:-
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
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
Step 5:
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
State
Output:
1 XYZ
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
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:
Web.xml
<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
<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()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>
Reg.html
</div>
</form>
</body>
</html>
Profile.html
Catalog.html
</form>
</body>
</html>
Order.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
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("</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:-
/WEB-INF/classes/HelloServlet.java:-
package com.nit.hello;
import javax.servlet.*;
import java.io.*;
78
Output:
79
80
ServletRequest :-
Servlet container takes the request related data from the protocol adapter
and sets them into the ServletRequest object
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: <input type="text"
name="firstname"/><br/><br/>
Last-Name: <input type="text"
name="lastname"/><br/><br/>
Father-Name: <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: "+fn+"<br/>");
pw.println("LastName: "+ln+"<br/>");
pw.println("FatherName: "+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.
path
domain name
Cookie[] getCookies()
addCookie(cookie)
setMaxage(int) - sets the maximum time for which the cookie is alive
on the client
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"/>
Cookie1-value:<input type="text"
name="cookieonevalue"/><br/>
Cookie2-name:<input type="text"
name="cookietwoname"/>
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/>
</form>
</body>
</html>
85
/WEB-INF/web.xml:-
<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: "+c[i].getName()
+" ");
pw.println("cookievalue: "+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
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: <input type="text"
name="firstname"/><br/><br/>
Last-Name: <input type="text"
name="lastname"/><br/><br/>
Father-Name: <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: <input type="text"
name="dob"/><br/><br/><br/>
Address: <textarea
name="address" cols="20" rows="5"></textarea><br/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
/WEB-INF/web.xml:-
<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
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:
The following page directive at the beginning of JSP page indicates that it is serving
as an error page
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.
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
• 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) { ... }
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"/>
<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="*"/>
property="propName" value="expression"/>
<jsp:setProperty name="beanName"
property="propName" >
<jsp:attribute name="value">
expression
</jsp:attribute>
</jsp:setProperty>
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
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.
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
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: <jsp:getProperty
name="bean" property="firstName"/><br/><br/>
LastName is: <jsp:getProperty
name="bean" property="lastName"/><br/><br/>
Dateofbirth is: <jsp:getProperty
name="bean" property="dob"/><br/><br/>
address is: <jsp:getProperty
name="bean" property="address"/><br/><br/>
</body>
</html>
/WEB-INF/web.xml:-
<!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
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:
Catalina.bat run
At install-dir/bin
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()"> <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()">()"> <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()">()"> <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”> <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
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
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
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
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:
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: