Web Technologies notes2
Web Technologies notes2
Web Technologies notes2
UNIT I
INTRODUCTION: INTRODUCTION TO HTML
HTML stands for Hypertext Markup Language. It is a Language used to create Web
Pages or Hypertext document. A Markup Language is a set of instructions often called TAGS
which can be added to text files. HTML is only a formatting language are not a programming
language. The idea behind hypertext is that instead of reading text in a right linear structure we
can easily jump from one point to another point.HTML is all about specifying the structure and
format of our webpage i.e., it is mainly used for describing the structure document.
HTML is platform independent i.e., for example if we can access internet, we can access
WORLD WIDE WEB (WWW) irrespective of client OS and OS of the webserver are accessing.
So, we can view one download HTML files on www through browser.
Elements of a web document are labelled through the usage of HTML tags. It is the tags
that describe the document. Anything that is not a tag will be displayed in the document itself.
HTML does not describe any page layout i.e., for example, word for windows have different
styles for headings, font size etc. But HTML doesn’t have all these. Based on the Platforms,
appearance of any element will change. The formatted text will appear differently on different
machines / Platforms. By separating the Structure of the document and appearance, a Program
that reads and Understands HTML can make formatting decision based on capabilities of
individual Platform. Web Browsers are best examples of HTML formatters.
Advantages of HTML: -
A HTML document is small and hence easy to send over the net. It is small because
it doesn’t include format information.
2
WEB TECHNOLOGIES
3
WEB TECHNOLOGIES
<head> and <body> tags to indicate these two sections. <head> section holds the header
information of a webpage document indicated by a title that is provided by using <title> tag in
the <head>. The title helps us to refer to the webpage. <body> section contains the content
which
4
WEB TECHNOLOGIES
we want to display which the webpage. Anything that is not a tag will be displayed within
the webpage.
Example:
<html>
<head>
<title>First Webpage</title>
</head>
<body>
This is my first page
</body>
</html>
Output:
Attribute:
An Attribute is a Keyword we use in an opening tag to give more information to the web
browser. HTML tags tell the web browsers how to format and organize our webpages. But we
can customize tags using attributes. The Format of an attribute is:
<tag name Attribute=value>
Attributes of the <body> tag:
(1) Background:
5
WEB TECHNOLOGIES
The URL or a graphic file to be used in the filling the browser’s Background.
(2) Bgcolor:
The color of the browser’s background.
(3) Bgproperties:
It Indicates if the background should scroll when text does. If we set it to
“FIXED”, the background will not scroll when the text does.
(4) Bottom margin:
Specifies the bottom margin ,the empty space at the bottom of the documenting pixels.
(5) Id:
It is a unique alphanumeric identifier for the tag which we can use to refer to it.
(6) Language:
Scripting language used for the tag.
(7) Left margin:
Specifies the left margin, the empty space at the left of the document.
(8) Margin height:
Gives the height of the margin at the top and bottom of the page in pixels.
(9) MarginWidth:
Gives the width of the left and right margins of the page in pixels.
(10) Rightmargin:
It specifies the right margin, the empty space to the right margin of thedocument in pixels.
(11) Scroll:
It specifies whether a vertical scrollbar appears to the right of the documentcan be yes
(or) no.
(12) Style:
Inline style indicating how to render the element.
(13) Text:
Color of the in the document.
6
WEB TECHNOLOGIES
(14) Topmargin:
It specifies the top margin the space at the top of the document in pixels.
(15) Link:
It specifies the color of hyperlinks that have not yet been visited.
(16) Alink:
It specifies the color of hyperlinks as they are being clicked.
(17) Vlink:
It specifies the color of hyperlinks as they have been visited.
(18)<!-------> Comment tag:
Annotates a web page with a comment. In the HTML that we can by lookingat the
HTML but it will not be displayed in the web browser.
<! ------ This is a comment--------->
Formatting with HTML tags:
To set the actual style of text as displayed in a web page we can text style tags.There are a
number of ways to apply styles to text.
(1) <b>:
It creates a bold text i.e, sets the text style to bold.
Attributes:
a. Id:
It is a unique alphanumeric identifier for the tag which we can use to refer toit.
b. Style:
The Inline style indicating how to render the element.
Example:
<html>
<head>
<title>Using Bold Tag </title>
</head>
<body bgcolor=”pink”>
Here is some text displayed as <b> Bold Text </b>
7
WEB TECHNOLOGIES
</body>
</html>
Output:
(2)<I>:
It displays text in Italics.(3)
<U>:
It displays text in Underlined text.(4)
<P>:
It displays the Paragraph text.
Example:
<html>
<head>
<title> Using Styles </title>
</head>
<body bgcolor=”pink”>
<p> This is a paragraph <br>
Here is some text that is <i> Displayed in Italics </i>
<br>Here is some <u> Underlined text </u>
</body>
</html>
8
WEB TECHNOLOGIES
Output:
9
WEB TECHNOLOGIES
Output:
10
WEB TECHNOLOGIES
(11)Headings:
<h1>,<h2>,<h3>,<h4>,<h5> & <h6>
The heading element tags are <h1>,<h2>,<h3>,<h4>,<h5><h6>. These elements create
the headings in our web pages by displaying bold text in avariety of sizes <h1> being
larger <h6> being smaller.
Example:
<html>
<head>
<title> Heading tags </title>
</head>
<body bgcolor=”pink”>
<center>
<h1> Using Heading Tags</h1><br>
<h1> RGMCET </h1><br>
<h2> RGMCET </h2><br>
<h3> RGMCET </h3><br>
<h4> RGMCET </h4><br>
<h5> RGMCET </h5><br>
11
WEB TECHNOLOGIES
(12)<font>:
This tag will give us an option to select text size, color and face.
Attributes:
a. color: Color of the text.
b. Size: Size of the text in points
c. Face: The font face can be a list of names separated by commas.
d. Id: Unique alphanumeric identifier for a tag, which we can use to refer to it.
Example:
12
WEB TECHNOLOGIES
<html>
<head>
<title> Using Font Styles </title>
</head>
<body bgcolor=”pink”>
<center>
<font size=”1” color=”red”> The Font Size is 1 </font> <br>
<font size=”10” color=”yellow”> The Font Size is 10 </font> <br>
<font size=”20” color=”orange”> The Font Size is 20</font> <br>
<font size=”30” color=”aqua”> The Font Size is 30 </font> <br>
</center>
</body>
</html>
Output
(13)<marquee> tag:
Displays scrolling text in a marquee style.
Attributes:
a. Align:
Sets the alignment of the text relative to marquee.Set to:
13
WEB TECHNOLOGIES
14
WEB TECHNOLOGIES
15
WEB TECHNOLOGIES
</center>
</body>
</html>
Output:
Lists:
Lists lets us display information in a compact, right format. There are three kindsof lists:
1. Unordered List
2. Ordered List
3. Definition List
Unordered List:
An Unordered list is a list of items that are marked with burden. The Unordered list is
created by using <ul>tag are the list items in the list are createdby </ul> tag and the list items
in the list are created by <li> tag.
<ul>
<li>List Item 1 </li>
<li>List Item 2 </li>
</ul>
Example:
<html>
16
WEB TECHNOLOGIES
<head>
<title> Creating Unorder List </title>
</head>
<body bgcolor=”pink”>
<h1 align=”center”> Creating Unorder List</h1>
<h1 align=”center”>List of Colleges in Kurnool</h1>
<ul>
<li>GPREC</li>
<li>RGMCET</li>
<li>GPCET</li>
</ul>
</body>
</html>
Output
17
WEB TECHNOLOGIES
Example:
<html>
<head>
<title> Creating Unorder List </title>
</head>
<body bgcolor=”pink”>
<h1 align=”center”> Creating Unorder List</h1>
<h1 align=”center”>List of Colleges in Kurnool</h1>
<ul type=”square”>
<li>GPREC</li>
<li>RGMCET</li>
<li>GPCET</li>
</ul>
</body>
</html>
Output
Ordered List:
While the unordered lists display simple bullet before each list item. Ordered lists use a number
system / lettering scheme to indicate that the items are ordered in some ways, ordered lists are
18
WEB TECHNOLOGIES
created by <ol> tag and the list items are created using
<li> tag.
Example:
<html>
<head>
<title> Creating Order List </title>
</head>
<body bgcolor=”pink”>
<h1 align=”center”> Creating Order List</h1>
<h1 align=”center”>List of branches in RGMCET</h1>
<ol>
<li>CSE</li>
<li>IT</li>
<li>ECE</li>
<li>EEE</li>
<li>CIVIL</li>
<li>ME</li>
</ol>
</body>
</html>
Output
19
WEB TECHNOLOGIES
20
WEB TECHNOLOGIES
<ol type=”A”>
<li>CSE</li>
<li>IT</li>
<li>ECE</li>
<li>EEE</li>
<li>CIVIL</li>
<li>ME</li>
</ol>
</body>
</html>
Output
Definition List:-
These lists include both definition terms as well as their definition. To create the definition lists
we use <dl> tag. For creating definition terms we use <dt> tag andfor data definitions we use
<dd> tag.
Example:
<html>
<head>
<title>Creating Definition List</title>
21
WEB TECHNOLOGIES
</head>
<body bgcolo=”pink”>
<h1 align=”center”>Definition List</h1>
<dl>
<dt>CSE<dd>Computer Science & Engineering
<dt>ECE<dd>Electronics & Communication Engineering
<dt>IT<dd>Information Technology
<dt>EEE<dd>Electrical & Electronics Engineering
<dt>CE<dd>Civil Engineering
</dl>
</
body>
</html>
Output
22
WEB TECHNOLOGIES
Nesting Lists:-
23
WEB TECHNOLOGIES
24
WEB TECHNOLOGIES
Creating Hyperlinks:
What makes the web so effective is the ability to define links from one page to another. In web
terms, a “hyperlinks” is a reference on the web. Hyperlinks can point to any resources on the
web. An anchor is a term used to define a hyperlinkdestination inside a document. Format of
anchor tag is:
<a href=”address”> Line Text </a>
The <a> anchor tag has the following attributes.
1. href: It holds the target URL of the hyperlink.
2. Id: A unique alphanumeric identifier for the tag, which we can use to refer toit.
3. name: It specifies an anchor name, the name we want to use when referringto enclose
items.
4. Target: This attribute defines where the linked document will be opened.
Example:
<html>
<head>
<title>Creating Hyper Links</title>
25
WEB TECHNOLOGIES
</head>
<body bgcolor="pink">
<center><h1>This is page 1</h1>
<a href=”page2.html”>Click here</a>to goto page2
</center>
</body>
</html>
Output
26
WEB TECHNOLOGIES
27
WEB TECHNOLOGIES
28
WEB TECHNOLOGIES
29
WEB TECHNOLOGIES
30
WEB TECHNOLOGIES
31
WEB TECHNOLOGIES
<title>Creating Tables</title>
</head>
<body bgcolor="pink">
<center><h1>Creating tables</h1>
<table border=”1” cellpadding=”3” cellspacing=”3”>
<tr>
<th colspa=”2”>Websites</th>
</tr>
<tr>
<td>Mail sites</td>
<td>Job sites</td>
</tr>
<tr>
<td>Gmail.com</td>
<td>Frushersworld.com</td>
</tr>
<tr>
<td>Yahoo.com</td>
<td>Nauted.com</td>
</tr>
</center>
</table> </body></html>
32
WEB TECHNOLOGIES
Output
33
WEB TECHNOLOGIES
<caption>Subject Description</caption>
<thead>
<tr> <td colspan="2">Advance Java Programming</td>
</thead>
<tbody>
<tr> <td>Units</td>
<td>Contents</td>
</tr>
<tr> <td>I</td>
<td>HTML & CSS</td>
</tr>
<tr> <td>II</td>
<td>JavaScript</td>
</tr>
<tr> <td>III</td>
<td>XML</td>
</tr>
</tbody>
<tfoot align="center">
<tr>
<td colspan="2">The table foot</td>
</tr>
</tfoot>
</table>
</center>
</body>
</html>
Output
34
WEB TECHNOLOGIES
Nesting of Tables:
<html>
<head>
<title>Nesting of Tables</title>
</head>
<body bgcolor="pink">
<center><h1>Nested tables</h1>
<table border="1" cellpadding="3" cellspacing="3">
<tr>
<td>
<table border="2">
<tr>
<th>Mail sites</th>
<th>Job sites</th>
</tr>
35
WEB TECHNOLOGIES
<tr>
<td>Gmail.com</td>
<td>Frushersworld.com</td>
</tr>
<tr>
<td>Yahoo.com</td>
<td>Nauted.com</td>
</tr>
</table>
</td>
<td>
<table border="2">
<tr>
<th>Number</th>
<th>Words</th>
</tr>
<tr>
<th>1</th>
<th>One</th>
</tr>
<tr>
<th>2</th>
<th>Two</th>
</tr>
</table>
</td>
</tr>
</table>
</center>
</body>
36
WEB TECHNOLOGIES
</html>
Output
Images in HMTL:
In HTML we have the capability of displaying images in a webpage.This imagesmust be in a
format that the web browser can handle , such as Graphics Interchange Format(GIF) , Joint
Photograph Expert Group(JPEG) , and for somebrowser Portable Network Graphics(PNG)
formats.
Displaying images in webpage is done by using <img> tag
Format
<img src=”URL of image source”>
Attributes of <img> tag:
alt : this attribute is used to specify text to be displayed in place of image forbrowser that
cannot handle graphics.
src : specifies the URL of the image to display.
border : sets the border for the image.
height : indicates the height of the image.
width : indicates the width of the image.
37
WEB TECHNOLOGIES
38
WEB TECHNOLOGIES
39
WEB TECHNOLOGIES
40
WEB TECHNOLOGIES
41
WEB TECHNOLOGIES
method : indicates a method or protocol for sending data to the target actionURL.
action : gives the URL that that will handle the form data.
Example
Registration.html
<html>
<head>
<title>HTML Form</title>
</head>
<body bgcolor="pink">
<center>
<form name="form1">
<table border="0" cellpadding="4" cellspacing="4">
<caption>Registration form</caption>
<tr>
<th>Name</th>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<th>Password</th>
<td><input type="password"/></td>
</tr>
<tr>
<th>Enter your address</th>
<td><textarea rows="5" cols="10"></textarea></td>
</tr>
<tr>
<th>Enter your email</th>
<td><input type="email"/></td>
</tr>
<tr>
42
WEB TECHNOLOGIES
43
WEB TECHNOLOGIES
</html>
Output
44
WEB TECHNOLOGIES
45
WEB TECHNOLOGIES
<frameset cols="30%,70%">
<frame src=frame1.html>
<frame src=frame2.html>
</frameset>
</html>
Frame1.html
<html>
<head>
<title>page1</title>
</head>
<body>
<h1>Web Technologies</h1>
</body>
</html>
Frame2.html
<html>
<head>
<title>page2</title>
</head>
<body>
<h1>Web Technologies</h1>
</body>
</html>
Output
46
WEB TECHNOLOGIES
47
WEB TECHNOLOGIES
<frame src=page2.html>
</frameset>
</html>
page1.html
<html>
<head>
<title>page1</title>
</head>
<body>
<h1 align=”center”>This is page1</h1>
</body>
</html>
page2.html
<html>
<head>
<title>page2</title>
</head>
<body>
<h1 align=”center”>This is page2</h1>
</body>
</html>
Output
48
WEB TECHNOLOGIES
49
WEB TECHNOLOGIES
Output
<noframes> tag:
When the browser does not support frameset use <noframes> element to indicateto users that
the browser doesnot support frames.The <noframes> element is ignored that handle frames.
Example
<html>
<head>
<title>Vertical Frames</title>
</head>
<frameset cols="30%,70%">
<noframes>Your browser does not support frames...</noframes>
<frame src=on.html>
<frame src=two.html>
</frameset>
50
WEB TECHNOLOGIES
</html>
Output
Named frames:
One important aspect of working with frames is using named frames. When wegive frmae a
name , we can use as a target to load new page into the frame.
Example
<html>
<head>
<title>Vertical Frames</title>
</head>
<frameset cols="40%,60%">
<frame src=menu.html>
<frame src=default.html name="display">
</frameset>
</html>
51
WEB TECHNOLOGIES
menu.html
<html>
<head>
<title>Menu</title>
</head>
<body bgcolor="green">
<center><b>Click on below link</b>
<br><a href="page1.html" target="display">Page1
<br><a href="page2.html" target="display">Page2
</center>
</body>
</html>
Defual.html
<html>
<head>
<title>Vertical Frames</title>
</head>
<frameset cols="40%,60%">
<frame src=menu.html>
<frame src=default.html name="display">
</frameset>
</html>
Output
52
WEB TECHNOLOGIES
53
WEB TECHNOLOGIES
54
WEB TECHNOLOGIES
55
WEB TECHNOLOGIES
</tr>
<tr>
<td style=”background-color:yellow”>Yahoo</td>
<td style=”background-color:purple”>JobStreet</td>
</tr>
</table>
</center>
</body>
</html>
Output:
56
WEB TECHNOLOGIES
Example:
<html>
<head>
<title>Embedded Style sheets</title>
<style type=”text/css”>
body{background-color:
pink;}
h1 {
color:orang
e;
text-align:
center;
}
p{
font-family: "Times New
Roman";
font-size: 20px;
}
</style>
</head>
<body>
<h1>Embedded Style Sheets</h1><br>
<p>This is a paragraph
</body>
</html>
Output:
57
WEB TECHNOLOGIES
58
WEB TECHNOLOGIES
59
WEB TECHNOLOGIES
UNIT – II
JAVASCRIPT
INTRODUCTION TO JAVASCRIPT:
Static web pages are useful and can be informative. A number of technologies have been
developed that enable the creation of web applications rather than static web pages. The java
programming language is probably the best known such technology. Few programming languages
other than java have been adapted for use in client-side web applications. One such language that is
used in programming client-side web applications is javascript.
JavaScript originates from a language called Live Script and was developed by Sun
microsystems and Netscape navigator. Scripts are small pieces of code which accomplish a single
relatively simple task. JavaScript is a scripting language that is used for the development of Client-
side-in-browser applications. JavaScript is a simple script-based language which is only suitable
for fairly simple tasks. JavaScript is a language that is best suited to tasks that run for a short time.
Most of the developers experience problems when they try to build web pages which have
embedded JavaScript.
Important things about JavaScript:
1. Javascript is embedded into HTML:
Javascript code is usually embedded into HTML code and is executed within the
HTML document. Javascript has no user interface and it relies on HTML to provide a
means of interaction with the users. Most of the JavaScript objects have HTML tags and
provide event- driven code to execute it.
2. Javascript is browser dependent:
Javascript depends on the web browser to support it. If the browser does not support it
javascript will be ignored. Javascript was given support from I.E 3.0 & N.N 2.0 onwards.
3. Javascript is an interpreted language:
Javascript is interpreted at runtime by the browser before it is executed. It is not
compiled into a separate program like .exe but remains part of HTML file.
4. Javascript is a loosely typed language:
Javascript is very flexible when compared to java. There is no need to specify the data
type of a variable while declaring it. We can declare variables whenever it is necessary i.e.,
60
WEB TECHNOLOGIES
61
WEB TECHNOLOGIES
62
WEB TECHNOLOGIES
63
WEB TECHNOLOGIES
If statement:
It evaluates the content only if expression is true. The signature of JavaScript if statement
is:
if(expression){
//content to be evaluated
}
Example:
<html>
<head>
<title>If statement</title>
</head>
<body bgcolor="pink">
<script type="text/javascript">
var age=parseInt(prompt("Enter age of the person",""));
if(age>60){
document.write("<h1>Senior Citizen</h1>");
}
</script>
</body>
</html>
Output:
64
WEB TECHNOLOGIES
65
WEB TECHNOLOGIES
66
WEB TECHNOLOGIES
Example:
<html>
<head>
<title>if statement</title>
</head>
<body bgcolor="pink">
<script language="javascript">
var m1=parseInt(prompt("Enter
Marks1","0")); var
m2=parseInt(prompt("Enter Marks2","0"));
var m3=parseInt(prompt("Enter
Marks3","0")); var
avg=parseInt((m1+m2+m3)/3); if(avg>70){
document.write("<h1>Distinction</h1>");
}
else if(avg<70&&avg>60){
document.write("<h1>First Class</h1>");
}
else if(avg<60&&avg>50){
document.write("<h1>Second class</h1>");
}
else{
document.write("<h1>Fail</h1>");
}
</script>
</body>
</html>
JavaScript Switch:
The JavaScript switch statement is used to execute one code from multiple expressions. The
signature of JavaScript switch statement is :
67
WEB TECHNOLOGIES
switch(expression){
68
WEB TECHNOLOGIES
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example:
<html>
<head>
<title>Switch</title>
</head>
<body bgcolor="pink">
<script language="javascript">
var a=parseInt(prompt("Enter a value"," "));
var b=parseInt(prompt("Enter b value"," "));
var ch=parseInt(prompt("Enter your choice"," "));
switch(ch){
case 1: document.write("<h1>Addition is:"+(a+b)+"<h1>");
break;
case 2: document.write("<h1>Subtraction is:"+(a-b)+"<h1>");
break;
case 3: document.write("<h1>Multiplication is:"+(a*b)+"<h1>");
break;
case 4: document.write("<h1>Division is:"+(a/b)+"<h1>");
break;
69
WEB TECHNOLOGIES
70
WEB TECHNOLOGIES
Example:
<html>
<head>
<title>Multiplication</title>
</head>
<body bgcolor="pink">
<script language="javascript">
var n=parseInt(prompt("Enter a number",""));
var i;
for(i=1;i<=10;i++){ document.write("<b>"+n+"*"+i+"="+
(n*i)+"<br>");
}
</script>
</body>
</html>
Javascript Events:
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page. When the page loads, it is called an event. When the user clicks a
button, that click too is an event. Events are a part of the Document Object Model (DOM) Level 3
and every HTML element contains a set of events which can trigger JavaScript Code.
Mouse events:
71
WEB TECHNOLOGIES
Keyboard events:
Form Events:
Window/Document events:
72
WEB TECHNOLOGIES
Javascript Functions:
A javascript function contains code that will be executed by an event or by a call to
function. We may call a function from anywhere within a page. Functions can be defined both in
<head> and
<body> section of a document. Syntax to define a function is:
function function_name(var1, var2,…..,varn)
{
//Block of code
}
A function with no parameters must include the parentheses () after function name.
The keyword function must be written in lower case, otherwise javascript error occurs.
Example:
<html>
<head>
<title>functions</title>
<script language="javascript">
function displayMessage(){
alert("This is a function");
}
</script>
73
WEB TECHNOLOGIES
</head>
74
WEB TECHNOLOGIES
<body bgcolor="pink">
<form>
<input type="button" value="Click Me" onClick="displayMessage()">
</form>
</body>
</html>
Function with parameters:
<html>
<head>
<title>Function</title>
</head>
<body onLoad="pinfo('abc',30)">
<script language="javascript">
function pinfo(name,age){
document.write("<center><h1>User Information</h1><br>");
document.write("<h3>Name is:"+name+"</h3>");
document.write("<br><h3>Age is:"+age+"</h3>");
document.write("</center>");
document.close();
}
</script>
</body>
</html>
Objects in Javascript:
Window object:
Various properties & methods supported by window object are:
• open(): It is used to open a new window. Two arguments are provided. URL that specifies
the path of documents which should be loaded in the window and Name of window.
• close(): This method is used to close the current window.
• scroll(): By using this method contents of a given window can be easily scrolled.
75
WEB TECHNOLOGIES
Apart from above methods, window object may also have properties such as toolbar,
location, menubar, scrollbar, resizeable etc..
Examples:
Creating a new window and loading existing page:
<html>
<head>
<title>Window</title>
<script language="javascript">
function showNewPage(){
window.open("login.html");
}
</script>
</head>
<body bgcolor="pink">
<center>
<form>
<input type="button" value="SeeLogin" onClick="showNewPage()">
</form>
</center>
</body>
</html>
Creating a new window:
<html>
<head>
<title>Window</title>
<script language="javascript">
function showNewPage(){
var newWindow=window.open("window.html","height=200,width=450");
newWindow.document.write("<center><h1>This is a new Window</h1></center>");
}
76
WEB TECHNOLOGIES
</script>
</head>
<body bgcolor="pink">
<center>
<form>
<input type="button" value="Open page" onClick="showNewPage()">
</form>
</center>
</body>
</html>
Document object:
Document refers to page which will be displayed as soon as the browser window is opened.
Various methods/properties supported by the document object are:
• write()/writeln(): We can create HTML pages using javascript by using write()/writeln()
methods. Data can also be inserted.
• bgcolor/fgcolor: These are the same properties that can be set in the <body> tag. The only
difference here is that the values can be set from javascript.
• anchors: It is an array holding the names of anchor elements appearing on web page.
• links: It is an array holding all links appearing on web page.
• forms: It is an array that contains all of the HTML forms.
• close(): The document is not completely written until the close() method is called. The
browser keep waiting for more data if user do not call this method.
Form object:
Two aspects of form can be manipulated through javascript.
• Most commonly the data that is entered onto the form can be checked at submission.
• We can actually build forms through
javascript. Various form events are:
• onClick: This event is triggered when the user clicks on an element.
• onSubmit: This event can only be triggered when the form is submitted.
• onReset: This event is triggered when the form is reset by the user.
77
WEB TECHNOLOGIES
78
WEB TECHNOLOGIES
• sqrt(): Displays the square root of the value entered into it.
• sin(): Displays the trigonometric sine value.
• cos(): Displays the trigonometric cosine value.
• tan(): Displays the trigonometric tangent value.
• log(): Displays the logarithmic equivalent value.
Browser object:
The browser object is also called as navigator object. Methods supported by browser
object are:
• navigator.appcodeName: The internal name for the browser.
• navigator.appName: This is the public name of the browser.
• navigator.appversion: The version number, platform on which the browser is running and
the version of navigator with which it is compatible.
• navigator.userAgent: The strings appcodeName and appVersion concatenated together.
• navigator.plugins: An array containing details of all installed plugins.
• navigator.mimeTypes: An array of all supported MIME types.
Date object:
Javascript Date provides functions to perform many different date manipulations. In
javascript dates and times represent the number of milliseconds since 01/01/1970 UTC.
Javascript like most programming systems has two separate notions of time:
• UTC is universal time, also known as Greenwich Mean Time, which is the standard time
throughout the world.
• Local time is the time on the machine which is executing the script.
Date object Methods:
1. Date(): Construct an empty date object.
2. Date(milliseconds): Construct a new date object based upon the number of milliseconds
which have elapsed since 00:00:00 hours on 01/01/1970.
3. Date(String): Create a date object based upon the contents of a text string.
4. Date(year,month,day[hour,minute,second]): Create a new date object based upon
numeric values for year, month and day. Optional time values may also be supplied.
5. Parse(string): Returns the number of milliseconds since midnight on 01/01/1970.
79
WEB TECHNOLOGIES
80
WEB TECHNOLOGIES
81
WEB TECHNOLOGIES
When accessing array elements we need to know how many elements have been stored
into the array. This is done through the length attribute. The index number runs from 0 – length-1.
Example:
<html>
<head>
<title>Arrays</title>
</head>
<body>
<script language=“javascript”>
document.write(“<h1> Looping through the
Array</h1>”); var data =[10,20,30,40];
var len=data.length;
for(var count=0;count<len;count++){
document.write(data[count]+”,”);
}
document.close();
</script>
</body>
</html>
Removing Array elements:
Javascript does not provide a built-in function to remove array members. To remove array elements
we use the following procedure:
1. Read each element in the array.
2. If the element is not the one which we want to delete, copy it to temporary array.
3. If the element is the one we want to delete, do nothing.
4. Increment loop counter.
5. Repeat the process and copy the array elements again into original array.
Example:
<html>
<head>
82
WEB TECHNOLOGIES
<title>Arrays</title>
</head>
<body>
<script language=“javascript”>
document.write(“<h1> Removing Array elements</h1>”);
var data =[10,20,30,40];
var len=data.length;
for(var count=0;count<len;count++){
document.write(data[count]+”,”);
}
var rem=prompt(“Enter item to remove”,””);
var tmp=new Array(data.length-1);
var count2=0;
for(count=0;count<len;count++){
if(data[count]==rem){
}
else{ tmp[count2]=data[count
]; count2++;
}
}
data=tmp;
var len=data.length;
for(var count=0;count<len;count++){
document.write(data[count]+”,”);
}
document.close();
</script>
</body>
</html>
83
WEB TECHNOLOGIES
84
WEB TECHNOLOGIES
</body>
</html>
Dynamic content – Changing web pages:
There are several methods that insert HTML in pages:
1. insertAdjacentHTML.
2. insertAdjacentText.
3. innerText.
4. outerText.
5. innerHTML.
6. outerHTML.
insertAdjacentHTML & insertAdjacentText:
The insertAdjacentHTML method lets us to insert HTML next to an element that
already exists and insertAdjacentText method lets us insert text in the same way.
We can determine where the new text or HTML will go with respect to existing element
by passing the constraints “BeforeBegin, AfterBegin, BeforeEnd or AfterEnd”.
innerText: Let us change the text between the start and end tags.
outerText: Let us change all the text including start and end tags.
innerHTML: Changes the contents of elements between start and end tags.
outerHTML: Changes contents of an element including the start and end tags.
createElement: It is used to create new web page elements and use methods like insertBefore()
and insertAfter() to insert those elements into web page.
Examples:
insertAdjacentHTML():
<html>
<head>
<title>InsertAdjacentHTML</title>
<script language="javascript">
function showMore(){
div1.insertAdjacentHTML('afterend','A New Textfield:<input type="text" value="Hello!">');
}
85
WEB TECHNOLOGIES
</script>
</head>
<body bgcolor="pink">
<div id="div1">
<input type="button" value="Click Me" onClick="showMore()">
</div>
</body>
</html>
Output:
innerText:
<html>
<head>
<title>InnerText</title>
<script language="javascript">
function changeHeader(){
header.innerText="This is new Header";
}
</script>
</head>
86
WEB TECHNOLOGIES
<body bgcolor="pink">
<center>
<h1 id="header" onClick="changeHeader()">Dynamic HTML</h1>
</center>
</body>
</html>
innerHTML:
<html>
<head>
<title>InnerText</title>
<script language="javascript">
function changeHeader(){
header.innerHTML="<marquee>This is new Header</marquee>";
}
</script>
</head>
<body bgcolor="pink">
<center>
<h1 id="header" onClick="changeHeader()">Dynamic HTML</h1>
</center>
</body>
</html>
outerHTML:
<html>
<head>
<title>InnerText</title>
<script language="javascript">
function changeHeader(){
header.outerHTML="<marquee style='font-size:50'>This is new Header</marquee>";
}
87
WEB TECHNOLOGIES
</script>
</head>
<body bgcolor="pink">
<center>
<h1 id="header" onClick="changeHeader()">Dynamic HTML</h1>
</center>
</body>
</html>
createElement() & createTextNode():
<html>
<head>
<title>createElement</title>
<script language="javascript">
function showMore(){
var newDiv,newTextfield,newText;
newDiv=document.createElement("DIV");
newDiv.id="div1";
newTextfield=document.createElement("INPUT");
newTextfield.type="text";
newTextfield.value="Hello!";
newText=document.createTextNode("A New Textfield");
newDiv.insertBefore(newText,null);
newDiv.insertBefore(newTextfield,null);
document.body.insertBefore(newDiv,null);
}
</script>
</head>
<body bgcolor="pink">
<h1 align="center">CreateElement Method</h1><br>
<input type="button" value="Click Me" onClick="showMore()">
88
WEB TECHNOLOGIES
</body>
</html>
Output:
89
WEB TECHNOLOGIES
<body bgcolor="pink">
<center>
<h1>Dynamic Tables</h1>
<table id="table1" border="2">
<tr>
<th>ABC</th>
<th>DEF</th>
<th>GHI</th>
</tr>
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
</tr>
<tr>
<td>aaa</td>
<td>bbb</td>
<td>ccc</td>
</tr>
</table>
<input type="button" value="Add Row" onClick="addRow()">
</center>
</body>
</html>
Output:
90
WEB TECHNOLOGIES
91
WEB TECHNOLOGIES
{
var uid = document.form1.userid;
var passid = document.form1.passid;
var uname = document.form1.username;
var uadd = document.form1.address;
var uzip = document.form1.zip;
var uemail = document.form1.email;
if(userid_validation(uid,5,12))
{
if(userid_validation(passid,7,12))
{
if(allLetter(uname))
{
if(alphanumeric(uadd))
{
if(allnumeric(uzip))
{
if(ValidateEmail(uemail))
{
}
}
}
}
}
}
return false;
}
function userid_validation(uid,mx,my)
{
var uid_len = uid.value.length;
92
WEB TECHNOLOGIES
93
WEB TECHNOLOGIES
{
alert('Please input alphanumeric characters only');
uadd.focus();
return false;
}
}
function allnumeric(uzip)
{
var numbers = /^[0-9]+$/;
if(uzip.value.match(numbers))
{
return true;
}
else
{
alert('Please input numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(uemail.value.match(mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
94
WEB TECHNOLOGIES
uemail.focus();
return false;
}
}
</script>
</head>
<body>
<form name='form1' onsubmit='return formValidation()' >
<table width="500" cellpadding="3" style="border-collapse: collapse;">
<tr>
<td>User id </td>
<td><input type="text" name="userid" size="12" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="passid" size="12" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="username" size="50" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" size="50" /></td>
</tr>
<tr>
<td>ZIP Code </td>
<td><input type="text" name="zip" /></td>
</tr>
<tr>
95
WEB TECHNOLOGIES
<td>Email</td>
<td><input type="text" name="email" size="50" /></td>
</tr>
<tr>
<td>Sex</td>
<td><input type="radio" name="msex" value="Male" /> Male
<input type="radio" name="fsex" value="Female" /> Female</td>
</tr>
<tr>
<td>Language preference</td>
<td><input type="checkbox" name="en" value="en" checked />English
<input type="checkbox" name="nonen" value="noen" />Non English</td>
</tr>
<tr>
<td>Write about yourself<br>
(optional)</td>
<td><textarea name="desc" rows="4" cols="40"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Submit" /></td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
Output:
96
WEB TECHNOLOGIES
97
WEB TECHNOLOGIES
UNIT – III
XML
Introduction:
XML stands for “Extensible Markup Language”. XML is a text-based markup language. A
markup language is a set of instructions often called as tags which can be added to text files. When
the file is processed by a suitable application the tags are used to control the structure and
presentation of data contained in the file. Most commonly tags are used by application when
presenting data.
XML is more than HTML because, HTML only deals with presentation and carries no
information about the data, whereas XML deals with the representation of data and carries
information about the data. In XML, we create our own tags and also syntax for those tags that can
let the document structure follow the data structure. As we are defining our own tags and there are
no predefined tags, XML is defined to be “self-descriptive”. Using scripting languages like
javascript we can reach to various elements of an xml page and make use of data.
When compared with HTML, XML provides a way of structuring the data and store data
with focus on “What data is”, where HTML was designed to display data with focus on “How data
looks”.
XML is nothing special, it is just a plain text. Software that can handle plain text
can also handle XML. XML is a software/hardware independent tool for carrying information.
Advantages of XML:
• Readability:
XML document is plain text and human readable.
• Hierarchal:
XML document has a tree like structure which is enough to express complex data as
simple as possible.
• Language Independent:
XML documents are language neutral. For example, a java program can generate an
XML which can be parsed by a program written in C++ or perl.
• Platform Independent:
XML files are operating system independent.
98
WEB TECHNOLOGIES
Uses of XML:
• XML is used to describe the contents of a document.
• XML is used in messaging, where applications exchange data between them.
• The data can be extracted from the database, can be preserved with original information
and can be used in more than one application in different ways.
Important points about XML:
• XML is case sensitive.
• All the XML files are stored with .xml extension.
• Every XML document begin with <?xml version=“1.0”?>
Example: XML to store customer information of a supermarket.
<?xml version=”1.0”?>
<document>
<customer>
<name>
<firstname>aaa</firstname>
<lastname>bbb</lastname>
</name>
<date>01 jan 2017</date>
<orders>
<item>
<product>Chocolates</product>
<number>777</number>
<price>250</price>
</item>
<item>
<product>Sweets</product>
<number>888</number>
<price>450</price>
</item>
99
WEB TECHNOLOGIES
</orders>
</customer>
</document>
Valid & Well-formed XML document:
An XML document is said to be valid only if it is associated with a “Document Type
Definition” or “XML schema”.
An XML document is said to be well-formed only if it satisfies the below constraints:
• All tags must have corresponding end tag.
Most of the XML parsers require XML documents to be well-formed, but not necessarily valid.
Document Type Definition(DTD):
• Document Type Definition specifies syntax for XML document i.e., it specifies rules that
apply to the data.
• The XML document contains data, whereas DTD contains rules that apply to the data.
• A DTD defines the document structure with a list of legal elements and attributes.
100
WEB TECHNOLOGIES
Syntax of DTD:
<!DOCTYPE ROOTELEMENT[
<!ELEMENT ELEMENT_NAME1(subelement1,subelement2….)>
<!ELEMENT ELEMENT_NAME2(subelement1,subelement2….)>
.
.
<!ELEMENT ELEMENT_NAMEn(subelement1,subelement2….)>
]>
There are two types of DTD:
1. Internal DTD.
2. External DTD.
Internal DTD is the one in which we specify the DTD within the XML document. The
scope of Internal DTD is limited to one document only.
Example:
<?xml version=”1.0”?>
<!DOCTYPE document[
<!ELEMENT document (customer)*>
<!ELEMENT customer (name,date,orders)>
<!ELEMENT name (firstname,lastname)>
<!ELEMENT firstname(#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT orders (item)*>
<!ELEMENT item (product,number,price)>
<!ELEMENT product (#PCDATA)>
<!ELEMENT number (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>
101
WEB TECHNOLOGIES
<document>
<customer>
<name>
<firstname>aaa</firstname>
<lastname>bbb</lastname>
</name>
<date>01 jan 2017</date>
<orders>
<item>
<product>Chocolates</product>
<number>777</number>
<price>250</price>
</item>
<item>
<product>Sweets</product>
<number>888</number>
<price>450</price>
</item>
</orders>
</customer>
</document>
External DTD is the one where DTD is specified as a separate file and is saved with .dtd
extension and contains only set of rules. To import the DTD file into XML we include the below
statement in XML file:
<!DOCTYPE ROOT_ELEMENT SYSTEM “filename.dtd”>
Example:
Extern.dtd:
<!ELEMENT document (customer)*>
<!ELEMENT customer (name,date,orders)>
<!ELEMENT name (firstname,lastname)>
102
WEB TECHNOLOGIES
<!ELEMENT firstname(#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT orders (item)*>
<!ELEMENT item (product,number,price)>
<!ELEMENT product (#PCDATA)>
<!ELEMENT number (#PCDATA)>
<!ELEMENT price (#PCDATA)>
Cust.xml:
<?xml version=”1.0”?>
<!DOCTYPE document SYSTEM “extern.dtd”>
<document>
<customer>
<name>
<firstname>aaa</firstname>
<lastname>bbb</lastname>
</name>
<date>01 jan 2017</date>
<orders>
<item>
<product>Chocolates</product>
<number>777</number>
<price>250</price>
</item>
<item>
<product>Sweets</product>
<number>888</number>
<price>450</price>
</item>
</orders>
103
WEB TECHNOLOGIES
</customer>
</document>
Specifying attributes in a DTD:
We can specify the attributes of the elements in DTD by using <!ATTLIST> element. This
element holds a list of attributes for an element. We can specify default values for the attribute and
also can specify whether the attribute is necessary for an element or not. The format of defining an
attribute in DTD is:
<!ATTLIST ELEMENT_NAME ATTRIBUTE_NAME TYPE DEFAULT_VALUE>
The value supplied for attribute can be:
Value – The default value of an attribute.
#REQUIRED – The attribute is required.
#IMPLIED – The attribute is not required.
#FIXEDVALUE – The attribute value is fixed.
The default type used for attributes is unparsed character data.
Example:
<?xml version=”1.0”?>
<!DOCTYPE document[
<!ELEMENT document (customer)*>
<!ELEMENT customer (name,date,orders)>
<!ELEMENT name (firstname,lastname)>
<!ELEMENT firstname(#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT date (#PCDATA)>
<!ELEMENT orders (item)*>
<!ELEMENT item (product,number,price)>
<!ELEMENT product (#PCDATA)>
<!ELEMENT number (#PCDATA)>
<!ELEMENT price (#PCDATA)>
<!ATTLIST customer nationality CDATA “INDIAN”
Age CDATA #IMPLIED
104
WEB TECHNOLOGIES
105
WEB TECHNOLOGIES
<name>aaa</name>
<dept>CSE</dept>
</staff>
<student>
<name>bbb</name>
<dept>CSE</dept>
</student>
</college>
In the above example the XML elements <name> and <dept> of both staff and student have
the common element names. This could provide naming collisions. To solve such problems in
XML documents, we use the “XML Namespaces”. The XML namespaces allows us to prevent
collision by differentiating the elements with same names by using namespace prefixes.
The xmlns attribute:
XML namespaces use the keyword xmlns to create namespace prefixes and assign
corresponding URI that uniquely identifies the namespace. For the above example we can define
the namespace prefixes to avoid naming collisions.
<?xml version=”1.0”>
<college xmlns:staff=”web technologies:staffInfo”
xmlns:student=”web technologies:studentInfo”>
<staff>
< staff:name>aaa</ staff:name>
< staff:dept>CSE</ staff:dept>
</staff>
<student>
< student:name>bbb</ student:name>
< student:dept>CSE</ student:dept>
</student>
</college>
XML Schema:
An XML schema describes the structure of an XML document. XML schema is an XML-
106
WEB TECHNOLOGIES
Limitations of DTD:
1. DTD’s do not have the angled bracket syntax.
2. We cannot use multiple DTD’s to validate one XML document.
3. DTD’s have very limited basic types.
4. DTD’s are not object oriented.
An XML schema language is also referred to as “XML Schema Definition(XSD)”. An XML
schema begins by declaring the XML schema namespace as follows:
<xsd:schema xmlns:xsd=http://www.w3.org/2001/XMLSchema>
Defining an Element:
There are two types of elements defined in an XML schema. They are:
1. Simple elements.
2. Complex elements.
1. Simple Elements:
Simple elements can contain only data and they cannot have sub elements or
attributes. The text they contain can be of various data types. The format for defining a
simple element is:
<xsd:element name=”element_name” type=”xsd:type”/>
2. Complex Elements:
Complex elements can contain sub elements or attributes. The complex elements are
made up of simple elements. The format of defining a complex element is:
<xsd:complexType name=”element_name”>
<xsd:sequence>
<xsd:element name=”element_name” type=”xsd:type”/>
<xsd:element name=”element_name” type=”xsd:type”/>
</xsd:sequence>
</xsd:complexType>
107
WEB TECHNOLOGIES
Defining an Attribute:
An attribute provides additional information used by an element besides the element’s
content. The format for defining an attribute in XML schema is:
<xsd:complexType name=”element_name”>
<xsd:complexContent>
<xsd:extension>
<xsd:attribute name=”attribute_name” type=”xsd:type”/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
Example:
<xsd:complexType name=”employee”>
<xsd:complexContent>
<xsd:extension>
<xsd:attribute name=”gender” type=”xsd:string”/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
An XML schema is a file that we can create using any text editor. The file must be saved
with .xsd extension and the contents of the file must confirm to the XML schema language.
Referencing an XML schema:
We link an XML schema by referencing the XML schema file in the <root> tag of the
XML document. The format of <root> is:
<root xmlns:xsi=http://www.w3.org/2000.10.XMLSchema-instance xsi:schemalocation=”URI”>
Example of XML schema:
St.xsd:
<?xml version=”1.0”?>
<xsd:schema xmlns:xsd=http://www.w3.org/2001/XMLSchema>
108
WEB TECHNOLOGIES
<xsd:complexType name=”student”>
<xsd:sequence>
<xsd:complexType name=”studentType”>
<xsd:sequence>
<xsd:element name=”rollnumber” type=”xsd:string”/>
<xsd:element name=”name” type=”xsd:string”/>
<xsd:element name=”marks” type=”xsd:integer”/>
<xsd:element name=”result” type=”xsd:string”/>
</xsd:sequence>
</xsd:complexType>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
studentInfo.xml:
<?xml version=”1.0”?>
<root xmlns:xsi=http://www.w3.org/2000.10.XMLSchema-instance xsi:schemalocation=”st.xsd”>
<student>
<studentType>
<rollno>95A0</rollno>
<name>aaa</name>
<marks>500</marks>
<result>Firstclass</result>
</studentType>
<studentType>
<rollno>95A1</rollno>
<name>bbb</name>
<marks>450</marks>
<result>Firstclass</result>
</studentType>
</student>
109
WEB TECHNOLOGIES
Presenting XML:
In order to present the data in XML documents we use web presentation technologies.
Presenting data is again dependent to a specific technology. It is better to separate the data from the
presentation technology and stored in XML document and the extensible stylesheet language
(XSL) is used to present the data.
Extensible stylesheet language (XSL):
The extensible stylesheet is a language used to express stylesheets which are then used to
present XML documents. XSL stylesheets are not same as HTML stylesheets. Rather than creating
a style for a particular XML element or class of elements with XSL, a template is created. This
template is used to format XML elements which match a specific pattern.
The XSL transformation language (XSLT) is used to transform one XML document from
one form to another. The result of applying XSLT to an XML document could be another XML,
HTML text or any other document.
Example:
People.xml:
<?xml version=”1.0”?>
<?xml-stylesheet type=”text/xsl” href=”people.xsl”?>
<people>
<person born=”1993”>
<name>
<firstname>aaa</firstname>
<lastname>bbb</lastname>
</name>
<profession>Software Engineer</profession>
</person>
<person born=”1982”>
<name>
<firstname>ccc</firstname>
110
WEB TECHNOLOGIES
<lastname>ddd</lastname>
</name>
<profession>Project Manager</profession>
</person>
</people>
People.xsl:
<?xml version=”1.0”?>
<xsl:stylesheet version=”1.0” xmlns:xsl=http://www.w3.org/1999/XSL/Transform>
<xsl:output method=”html” omit-xml-declaration=”no”/>
<xsl:template match=”/”>
<html>
<head>
<title>XSLT</title>
</head>
<body>
<table border=”2”>
<tr>
<th>Born</th>
<th>FirstName</th>
<th>LastName</th>
<th>Profession</th>
</tr>
<xsl:for-each select=”people/person”>
<tr>
<td><xsl:value-of select=”@born”/></td>
<td><xsl:value-of select=”name/firstname”/></td>
<td><xsl:value-of select=”name/lastname”/></td>
<td><xsl:value-of select=”profession”/></td>
</tr>
</xsl:for-each>
111
WEB TECHNOLOGIES
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
The XSL stylesheet begins with a tag called stylesheet which binds with namespace prefix
xsl to the URI http://www.w3.org/1999/XSL/Transform which uniquely identifies the XSL
namespace.
The <xsl:output> is used to write a XHTML document type declaration to the result tree.
Attribute omit-xml-declaration specifies whether the transformation should write the XML
declaration to the result tree. <xsl:template> element describes how to transform a particular node
from the source tree into the result tree. The match is used to select the document root of the source
document.
The element <xsl:for-each> is used to iterate through the source XML document and search
for person element. The attribute select specifies the node on which the <xsl:for-each> operates.
The element <xsl:value-of>is used to retrieve value of the attribute and elements. The @ symbol
specifies that we need to retrieve an attributes value.
Document Object Model (DOM):
There are two models that are commonly used for XML parsers:
1. SAX (Simple API for XML).
2. DOM (Document Object Model).
SAX parser is mainly used when we are dealing with streams of data i.e., the data the XML
is passing from one place to another with parser acting as an intermediate way point. Typically this
model is used when passing XML data across a network between applications and is widely used
by java programmers. SAX based parsers does not have to build any static models of the document
in memory and are intended to run quickly.
The SAX parser is not suitable to use in websites where repeated querying and updating of
XML document is required. Here it is sensible to build some sort of representation which can be
held in memory for the duration of the use of application. In such cases the DOM based parser is a
better choice.
112
WEB TECHNOLOGIES
DOM stands for Document Object Model and is an API for XML documents. Basically an
API is a set of data items and operations which can be used by the developers of application
programs. For example, the Microsoft windows environment has a very rich API which is used by
the developers when creating windows programs.
The DOM API specifies the logical structure of XML documents and the ways in which
they can be accessed and manipulated. The DOM API is just a specification. There isn’t a single
reference piece of software associated with it which everyone must use. DOM complaint
applications include all of the functionality that is needed to handle XML documents. They can
build static documents, navigate and search through them, add new elements, delete elements and
modify the content of existing elements.
DOM views XML document as a tree, but this is very much logical view of the document.
Each XML element is modelled as an object. This means that the node encompass both data and
behaviour and that the whole document can be seen as a single complex object. Object oriented
theory lets each object have a unique identity. If each node has a unique identity then the tree can
be searched for individual nodes. DOM exposes the whole document to application so that the
application can manipulate individual nodes.
Accessing XML data using DOM
object: School.xml:
<?xml version="1.0"?>
<school>
<class>
<title>XML</title>
<students>
<student>
<first_name>aaa</first_name>
<last_name>bbb</last_name>
</student>
<student>
<first_name>aaa</first_name>
<last_name>bbb</last_name>
113
WEB TECHNOLOGIES
</student>
</students>
</class>
</school>
School.html:
<html>
<head>
<title>Accessing XML data</title>
<script type="text/javascript">
function getStudentData()
{
var xmldoc;
xmldoc=new ActiveXObject("Microsoft.XMLDOM");
xmldoc.load("school.xml");
nodeSchool=xmldoc.documentElement;
nodeClass=nodeSchool.firstChild;
nodeStudents=nodeClass.lastChild;
nodeStudent=nodeStudents.lastChild;
nodeFirstname=nodeStudent.firstChild;
nodeLastname=nodeFirstname.nextSibling;
outputMessage="Name:"+nodeFirstname.firstChild.nodeValue+'
'+nodeLastname.firstChild.nodeValue;
message.innerHTML=outputMessage;
}
</script>
</head>
<body bgcolor="pink">
<center>
<h1>Accessing XML Data</h1>
<div id="message"></div>
114
WEB TECHNOLOGIES
115
WEB TECHNOLOGIES
UNIT – IV
WEB SERVERS & SERVLETS
JSP APPLICATION DEVELOPMENT
Introduction:
Java Servlet is a server side program that is called by the user interface or another J2EE in
component and contains the business logic to process a request. The Java Servlet can call other
components such as EJB that handle processing.
J2EE applications use a light weight client, typically a browser that contains little (or) no
processing logic. Consider a request for a static web page. A user enters a Uniform Resource
Locator (URL) into a browser. The browser generates an HTTP request to the appropriate Web
server. The web server maps this request to a specific file. That file is returned in an HTTP
response to the browser. The HTTP header in the response indicates the type of the content. The
Multi Purpose Internet Mail Extension (MIME) are used for this purpose. For example, ordinary
ASCII text has a MIME type of text/plain. The Hypertext Markup Language source code of a web
page has a MIME type of text/HTML.
Now consider the dynamic content. Assuming that an online store uses a database to
store information about business, This would include items for sale, prices, availability, orders and
so on. It wishes to make this information accessible to customer via web pages. The contents of
those web pages must be dynamically generated in order to reflect the largest information in the
database.
In the early days of web, a server could be dynamic construct a page by creating a separate process
to handle each client request. The process would open connecting to one or more database in order
to obtain the necessary information. It communicated within the web server buyer and interface
known as Common Gateway Interface(CGI). CGI allowed the separate process to read data from
the HTTP request write the data to the HTTP response. A variety of different languages were used
to build CGI programs. These include C, C++, Perl etc. However, CGI suffered serious
performance problems. It was expensive in terms of processor and memory resources to create a
separate process for each client request. It was also expensive to open and close database
connections for each client request. In addition, CGI programs were not platform - independent.
116
WEB TECHNOLOGIES
117
WEB TECHNOLOGIES
118
WEB TECHNOLOGIES
persistent
119
WEB TECHNOLOGIES
store. The memory allocated for the servlet and its objects can then be garbage collected.
A Simple Servlet:
To create and test a simple servlet we have to follow the following steps:
1. Create a project folder hierarchy as follows:
P1
|
WEB-INF
|
Classes
2. Open notepad and write servlet class as follows:
Source Code:
import java.io.*;
import javax.servlet.*;
public class MyServlet extends GenericServlet{
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException{
response.setContentType(“text/html”);
PrintWriter pw = response.getWriter();
pw.println(“<html><head><title>This is My Servlet </title>”);
pw.println(“</head><body><h1>Hi This message came from my
server</h1>”); pw.println(“</body></html>”);
plw.close();
}
}
Above code imports “javax.servlet” package. This package contains the classes and interfaces
required to build servlets. The program defines “MyServlet” as a subclass of “GenericServlet”. The
GenericServlet class provides functionality that makes it is easy to handle requests and responses.
Inside MyServlet, “service()” is overridden. This method handles requests from a client. The first
argument “ServletRequest” object that enables the servlet to read data that is provided via client
requests. The second argument is a “ServletResponse” object that enables the servlet to formulate a
120
WEB TECHNOLOGIES
121
WEB TECHNOLOGIES
http://localhost:8080/P1/hello
Where P1=name of the
application Hello= url-pattern of
MyServlet
9. Servlet executes one generates the response to clients as:
10. Hi, this message came from MyServlet in client’s browser window.
The Servlet API:
Two packages contain the classes and interfaces that are required to build servlets. These are:
1. Javax.servlet
2. Javax.servlet.http
The above two packages constitute the servlet API. These two packages are not part of the java
core packages. Instead they are standard extensions. Therefore, they are not included in the Java
Software Development Kit. We must download tomcat to obtain their functionality.
The javax.servlet Package:
The javax.servlet package contains a number of interfaces and classes that establish the framework
in which the servlets operate.
List of Interfaces:
Interface Description
Servlet Declares lifecycle methods for a servlet
ServletConfig Allows servlet to get initialization parameters.
ServletContext Enables servlet to events and access information about their
environment
ServletRequest Used to read data from a client request
ServletResponse Used to write data to a client response
SingleThreadModel Indicates that the Servlet is thread safe
1. The Servlet Interface:
All Servlets must implement the “Servlet” interface. It declares the init(), service and destroy()
methods that are called by server during the life cycle of servlet. A method is also provided that
allows a servlet to obtain any initialization parameters. Various methods designed by the servlet
interfaces are:
122
WEB TECHNOLOGIES
Method Description
void destroy() Called when the servlet is unloaded
ServletConfig getServletConfig() Returns a ServletConfig object that contains any
initialization parameters
String getServletInfo() Returns a string describing the servlet
void init(ServletConfig sc) throws Called when the servlet is initialized.
ServletException Initialization parmeters for the servlet can be
obtained from sc. An unavilable Exception
should be thrown if the servlets cannot be
initialized.
void service(ServletRequest req, Called to process a request from a client .The
ServletResponse res) throws ServletException, request from req and the response to the client
IoException can be written res. An exception is generated if
a servlet (or) Io problem occurs.
The init(), servlet() and destroy() methods are the life cycle methods of the server. These are
invoked by the server the getServeltConfig() method is called by the servlet to obtain imitialize
paramaters. A servlet devloper overrides getServletInfo() method to provide a string useful
information.
2. The ServletConfig Interface:
The servletConfig interface is implemented by the server. It allows a servlet to obtain configuration
data when it is loaded. The methods declared by this interface are:
Method Description
servletContext getServletContext() Returns the context of the servlet.
string getInitParameter(String param) Returns the value of the initialization parameter
named param.
string getServletParameterName() Returns an enumeration of all initialization
parameter names.
string getServletName() Returns the name of the invoking servlet.
3. The ServletContext Interface:
The servletContext interface is implemented by the server it enables servlet to obtain information
123
WEB TECHNOLOGIES
124
WEB TECHNOLOGIES
Method Description
String getCharacterEncoding() Returning the character encoding for the
response
ServletOutputStream getOutputStream() Returns a ServletOutputStream that can be
throws IOException used to write binary data to a response. An
IlleagalStateException is thrown if getWriter()
has already been invoked for this request
PrintWriter getWriter() throws IOException Returns a PrintWriter that can be used to write
character data to the response. An
IllegalStateException is thrown if
getOutputStream() has already been invoked
for
this request
Void SetContentLength(int size) Sets the content length for the response to size
Void SetContentType(string type) Sets the content type for the response to type.
The various core classes that are provided in the javax.servlet Package are:
Class Description
GenericServlet Implement the servlet and servletConfig
Interfaces.
ServletInputStream Provides an input stram for reading request from
a client.
ServletOutputStream Provides an outputStream for writing responses
to a client.
ServletException Indicates a servlet error has occures.
Unavailable Exception Indicates a servlet in unavailable.
The SingleThread Model Interface:
This interface is used to indicate that only a single thread will execute the servlet() metod of a
servlet at a given time. It defines no constants and declares no methods.
If a servlet implements this interface, the server has two options:
1. It can create servlet instances of the servlet when a client request arrives it is dent to an available
125
WEB TECHNOLOGIES
126
WEB TECHNOLOGIES
Interface Description
HttpServletRequest Enables Servlet to read data from a HTTP Request
HttpServletResponse Enables Servlet to write data to an Http Response
HttpSession Allows session data to be read or written
HttpSessionBindingListener Informs an object that is bound to (or) unbound from a session.
1. The HttpServerRequest Interface:
The HttpServletRequest interface is implemented by the server and it enables a servlet to obtain
information about a client request. Several methods defined by this interface are:
Method Description
Cookie[] getCookies() Returns an array of cookies in this request
Long getDateHeader(String field) Returns the value of the date header field named field
String getHeader(string field) Returns the value of the header field named field
Enumeration getHeaderNames() Returns an enumeration of the header names
String getQueryString() Returns any query string in the URL
StringBuffer getRequestURL() Returns the URL
HttpSession getSession() Returns session for this request. If a session does not
exist, one is created and then returned.
2. The HttpServletResponse interface:
The HttpServletResponse interface is implemented by the server. It enables a servlet to formulate
an Http Response to a client. Several constraints are defined. These correspond to the different
status codes that can be assigned to an Http Response. Several methods of this interface are:
Methods and it’s Description:
void addCookie(Cookie cookie) : adds cookie to the HTTPresponse
String encodeURL(String url) : determines if the session ID must be encoded in the URL
identified as URL. If so it returns the modified version of URL. Otherwise returns URL. All
URL’s generated by a servlet should be processed by this method
void sendError(int c) throws IOExecption : sends the error code c to the client.
void sendError(int c, String S) throws IOExecption : sends the error code c and message S to
the client.
127
WEB TECHNOLOGIES
128
WEB TECHNOLOGIES
129
WEB TECHNOLOGIES
void service(HttpServletRequest req, Called by the server, When an HTTP request arrives
HttpServletResponse res)throws for the servlet. The arguments provide access to
IOException, ServletException HTTP request and response
3) The HttPSessionEvent Class:
The HttpSessionEvent Class encapsulates session events.It extends EventObject and is generated
when a change occurs to the session.It defines a constructor. HttpSessionEvent(HttpSession
session):- Here,Session is the source of the event.
130
WEB TECHNOLOGIES
131
WEB TECHNOLOGIES
<center>
132
WEB TECHNOLOGIES
133
WEB TECHNOLOGIES
pw.println(pname+”=”);
String pvalue=req.getParameter(pname);
Pw.println();
}
pw.close();
}
}
The getParameterNames() method return an enumeration of the parameter names. The parameter
value is obtained through the getParameter() method. The output will be the parameter name and
value are displayed to the client.
Place the html file in P1 folder and .class file in classes folder and web.xml in WEB-INF folder
and follow the following steps:
1. Start Tomcat
2. Display the web page in the browser
3. Enter employee name and phone number in the text fields
4. Submit the web page
The browser will display the response that is dynamically generated by the servlets.
Reading Initialization Parameters:
The Initialization Parameters are supplied by server developer in the development descriptor i.e
web.xml. The Initialization Parameters are given to a server as follows:
<init-parameter>
<param-name>name</param-name>
<param-value>value</param-value>
</init-parameter>
The servlet container reads the parameters and supplies them to the servlet using servletConf8g
object. We call the getParameter() method on the ServletConfig object in the Servlet to receive the
parameter values .
For ex: init() method can be implemented as follows.
public void init(ServletConfig con) throws ServletException
{
String value=con.getInitParameter("name");
134
WEB TECHNOLOGIES
}
Whatever name is given to the parameter in the deployment descriptor file that name should be
supplied to the getInitParameter() .
It receives the value specified the deployment descriptor file as as string object .
We can supply any number of Initialization Parameters to the Servlet.
Installing the Java Software development kit(JSDK):
1. Download the Java development kit from the sun's website https://java.sun.com/
2. Double click on the downloaded jdk installer to start JDK and now we could see the window as
license agreement. Change the 4adio button option for selecting accepting terms and conditions.
3.Now just click on the next button then cases for the description folder where we go to install the
Java. By default it 8s installed in c drive
C:/Program Files/java/jdk1.5.0_01
4.Now click the next button and the installation progresses that will take few minutes.
After the installation of Java we need to set the environment variables. The steps are:
1. Go to desktop find MyComputer icon and right click on it
2. From the pop up menu select properties option
3. Click on the advanced which appears on the top right corner.
4. Click on environment variables button and we could see a window which contains the user
variables and system variables.
5. Now click on the new variable button in the user variable option to create the PATH
variable Variable Name: PATH
Variable Value:C:\Program files\Java\jdk1.5.0.
Then click on OK button.
6. Now again click on the new variable button in the user variable option to set the JAVA_HOME
Variable as:
Variable Name: JAVA_HOME
Variable Value:C:\Programfiles\Java\jdk1.5.0
7. Click on ok button.
Handling HTTP Requests and Responses:
The HttpServlet class provides specialized methods that handles the various types of Http
requests. A servlet developer typically overrides one of these methods. However, the GET and
POST methods are commonly used when handling from input.
Handling HTTP GET Requests and Responses:In GET method the servlet container must write
the headers before committing the response, because in Http the header must be sent before the
135
WEB TECHNOLOGIES
response body. If the response is incorrectly formatted, do Get returns an Http “Bad Request”
message.
Example:
Here we will develop a servlet that handles an HTTP GET request. The Servlet is invoked
when a form on a web page is submitted. The example contains two files. A web page is defined
and a servlet is defined.
ColorGet.html:
<html>
<head>
<title>Handling GET Request</title>
</head>
<body>
<center>
<form name=”form1” method=”GET” action= http://localhost:8080/p1/ColorGetServlet>
<b>Color:
<select name=”Color” size=”1”>
<option value=”red”>Red</option>
<option value=”Green”>Green</option>
<option value=”Blue”>Blue</option>
</select><br><br>
<input type=”submit” value=”submit”>
</form>
</center>
</body>
</html>
The above html defines a select element and a submit button .The action of the form tag specifies a
URL that identifies a servlet to process the HTTP GET request.
ColorGetServlet.java:
Import java.io.*;
Import javax.servlet.*;
136
WEB TECHNOLOGIES
Import javax.servlet.http.*;
Public class ColorGetServlet extends HttpServlet{
Public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException, IoException{
String color=req.getParameter(“color”);
Res.setContentType(“text/html”);
PrintWriter pw= res.getWriter();
Pw.println(“<b> The Selected color is:”);
Pw.println(color);
Pw.close();
}
}
Compile the servlet and perform these steps to test this example:
1. Start Tomcat.
2. Display web page in the
browser. 3.Select a color.
4. Submit the web page.
After Completing these steps ,the browser will display the response that is dynamically generated
by the servlet. The Parameters for an HTTP GET request are included as part of URL. That is
sent to the web server. For example, assuming that the user selects red option and submits the
form. The URL sent from the browser to the server is : http://localhost:8080/p1/ColorGetServlet?
color=Red. The Characters to the right of the question mark are known as “Query String” .
Handling HTTP POST Request and Responses:
The HTTP POST method allows the client to send data of unlimited length to the webserver at a
time .The servlet container must write the headers before committing the responses, because in
HTTP the header must be sent before the response body. If the HTTP POST Request is incorrectly
formatted,doPost returns an HTTP “Bad Request” message.
Example:
Here we will devlop a servlet that handles an HTTP POST request. The Servlet is invoked when a
form on a web page is submitted. The example contains two files. A webpage is defined and a
137
WEB TECHNOLOGIES
servlet
138
WEB TECHNOLOGIES
is defined.
ColorPost.html:
<html>
<head>
<title>Handling post req</title>
</head>
<body>
<center>
<form name=”form1” method=”POST” action=http://localhost:8080/p1/ColorPostServlet>
<b>Color:
<select name=”color” size=”1”>
<option value=”red”> Red</option>
<option value=”Blue”>Blue</option>
</select><br><br>
<input type=”submit” value=”submit”>
</form>
</center>
</body>
</html>
ColorPostServlet.java:
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class ColorPostServlet extends HttpServlet{
Public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException{
String color=req.getParameter(“color”);
Res.setContentType(“text/html”);
PrintWriter pw=res.getWriter();
pw.println(“<b> the selected color is:”);
139
WEB TECHNOLOGIES
pw.println(color);
pw.close();
}
}
Parameters for an HTTP POST request are not included as part of URL that is sent to web server
URL sent will be: http://localhost:8080/p1/ColorPostServlet.
Handling Cookies:
AddCookie.html:-
<html>
<head>
<title> Cookies demo </title>
</head>
<body>
<center>
<form name=”form1” method=”Post”
action=”http://localhost:8080/P1/AddCookieServlet”>
<b>Enter a value for my cookie:
<input type=”text” name=”data” size=25 value=” ”>
<br><input type=submit value=”submit”>
</form>
</center>
</body>
</html>
The above page contains a text field in which a value can be entered. There is also a submit
button on the page when this button is pressed, the value in the text field is sent to
AddCookieServlet via an HTTP POST request.
AddCookieServlet.Java:-
import java.io.*;
import javax.Servlet.*;
import javax.Servlet.http.*;
140
WEB TECHNOLOGIES
141
WEB TECHNOLOGIES
pw.println(“<b>”);
for(int i=0;i<cookies.length;i++)
{
String name=cookies[i].getName();
String value=cookies[i].getValue();
pw.println(“name=”+name+”;value=”+value);
}
pw.close();
}
}
Compile the servlet and perform these steps:-
1. Start Tomcat
2. Display AddCookie.html in the bottom
3. Enter a value for my cookie
4. Submit the webpage
After completing these steps we will observe that a feedback message is displayed by the
browser.
Next request the following URL via browser. http://localhost:8000/p1/GetCookiesServlet
The name and value of the cookie will be displayed in the browser.
Session Tracking:
Http is a stateless protocol. Each request is independent of the previous one. However in some
applications it is necessary to save state information so that information can be collected from
several interactions between a browser and a server sessions provide such a mechanism.
A session can be defined as a series of related interactions between a single client and the web
server, which take place over a period of time.
A session can be created via the getSession() method of HttpServerRequest. An HttpSession
object is requested this object can store a set of bindings that associate names in objects the
SetAttribute(), getAttribute(), getAttributeNames() and removeAttributes() methods of HttpSession
manage these bindings. It is important to note that session state is shared among all the servlets that
are associated with a particular client.
142
WEB TECHNOLOGIES
Example:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
res.setContentType(“text/html”);
HttpSession hs=req.getSession(true);
PrintWriter pw=res.getWriter();
pw.print(“<b>”);
Date d=(Date)hs.getAttribute(“date”);
If (d!=null){
Pw.print(“Last accessed date:”+d+”<br>”);
}
date = new Date();
hs.setAttribute(“date”,d);
pw.print(“current date:”+d);
pw.close();
}
143
WEB TECHNOLOGIES
144
WEB TECHNOLOGIES
145
WEB TECHNOLOGIES
Out:
This object is used for writing content to the client. It has several methods which can be used for
properly formatting output message to the browser.
Differences between JSP writer and PrintWriter:
Every JSP Writer is associated with 8kb of the internal buffer. Whereas PrintWriter doesn’t
associated with any buffer.
The methods of the JSPWriter class are designed to throw java.io.IOException whereas
methods of PrintWriter class doesn’t throw any exception.
JSPWriter is an abstract class present in the javax.servlet package.
PrintWriter is a class defined in java.io package.
Example:
<html>
<body>
<% int a=10; Int b=20;
Int sum=a+b;
out.print(“a value is:”+a);
out.print(“b value is:”+b);
out.print(“sum is:”+sum); %></body></html>
Request:
The main purpose of request implicit object is to get data on a JSP page which has entered by
the user on the previous JSP page.
Example:
<% string name=request.getParameter(“vid”);
out.print(“Welcome”+name); %>
Response:
It is basically used for modifying on dealing with the response which is being sent to the client
after processing the request.
Example:
request.setContentType(“text\html”);
146
WEB TECHNOLOGIES
out.print(name);
Session:
It is most frequently used implicit object, which is used for storing the user’s data to make it
available on the other JSP pages till the uses session is awake.
Example:
<html><body>
<form action=”/welcome”>
<input type=”text” name=”uname”>
<input type=”submit” value=”submit”>
</form></body></html>
Welcome.jsp:
<html><body><% string
name=request.getParameter(“uname”);
out.print(“Welcome:”+name);
session.setAttribute(“user”,name);
< a href=”showuserinfo.jsp”>Show underable </a> %>
</body>
</html>
Showuserinfo.jsp:
<html><body> <% string name=(string)session.getAttribute(“user”);
out.print(“Hello”+name);
%></body></html>
Application:
This is used for getting application wide initialization processing and to maintain useful data
across whole JSP application.
Exception:
Exception implicit object is used in exception handling for exploring the error messages. This
object is only available to the JSP pages which has ErrorPage set to true.
<% @page isErrorPage=”true” %>
<html><body><%= exception %></body></html>
147
WEB TECHNOLOGIES
Page:
148
WEB TECHNOLOGIES
Page is implicit object used to represent the servlet instance i.e. converted servlet, generated
during translation phase from a JSP page.
<% =page.getServletInfo() %>
Config:
This is a Servlet configuration object and mainly used for accessing getting configuration
information such as ServletContext, Servlet name,configuration parameters etc.
Conditional Processing:
Stud.html:
<html><body><h3>Conditional Processing </h3>
<form method=”get” action=”http://localhost:page/p1/con.jsp”>
<b>Enter Student Name:<input type=”text” name=”t1”><br>
<b>Enter Student Marks:<input type=”text” name=”t2”><br>
<input type=”submit” value=”Result”>
</form></body></html>
Con.jsp:
<html><body>
<%! String name;
String marks1;
Int marks;
%>
<b>Following is the Student Result
<%
name=request.getParameter(“t1”);
marks1=request.getParameter(“t2”);
marks=Integer.ParseInt(marks1);
if(marks>70)
out.println(“Distinction”);
else if(marks>60 && marks<70)
out.println(“First Class”);
else if(marks>50 && marks<60)
149
WEB TECHNOLOGIES
out.println(“Second class”);
else
out.println(“Failed”);
%>
<% out.println(“<b>Student name:”+name);
out.println(“<b>Student marks are:”+marks); %>
</body></html>
Declaring Variables are Methods:
Declaration tag is a block of java code for declaring class wide variables, methods and classes.
<%! Declaration %>
Example:
<html><head><title>Declaration Tag</title></head>
<% String name=”abc”
int age=30; %>
<b> The Name is:<%= name %><br>
<b>The age is:<%= age %><br>
<%! int sum(int num1,int num2,int num3){
return num1+num2+num3;
} %>
<b>The Result is: <%= sum(10,40,50) %>
</body></html>
Displaying values using an expression to set an attribute:
<html><head><title>JSP Expression</title></head>
<body><h2>JSP Expression </h2>
<ul>
<li>current time: <%= new java.util.Date()%>
<li>host name: <%= request.getResponseHost()%>
<li>Session id: <%= session.getId() %>
</ul></body></html>
150
WEB TECHNOLOGIES
151
WEB TECHNOLOGIES
A JSP declaration lets us define methods or variables in a JSP page. The methods and variables
become direct members of the containers generated servlet code. We can define both instance and
static members in a declaration. A declaration has the following form:
Example:
<%! private int count=1;
Static int total;
Int getcount(){
return count;
}
static int getTotal(){
return total;
}
%>
(1) In a declaration we can define a static block of variables and a class also.
(2) In a JSP page we can have any number of declarations in any number of declaring in any
order.
(3) Variables declared in a declaration are initialized to java default values.
2. Expressions:
An Expression scripting element is an embedded java.expr that is evaluated and converted to text
string. The resulting text string is placed in a JSP output in the location where the element appear.
Expressions act as Placeholders for java language expressions. An Expression is evaluated each
time the page is accessed and in the value is then embedded into the output HTML.
Example:
<%= a+b %>
<%= new java.util.Date()%>
(1) Expressions are inserted into the service method of the container generated servlet.
(2) We can have any number of expression per page.
(3) Embedded Java expression should not be terminated with a semicolon.
(4) We can print the value of any object of any primitive datatype to the output stream usng an
expression.
152
WEB TECHNOLOGIES
(5) We can also use as expression in a JSP action attribute. In this case the value of the
expression does not go to the output Stream. It is evaluated at the request time and its value
is assigned to the attribute. An expression used in this way is known as request time
attribute expression.
3. Scriptlets:
A scriptlet is used to include complete fragments of java code in the body of JSP page. This
Scripting element differs from others in two ways:
(1) It is not limited to the declaration of methods and variables.
(2) It does not generate a string output directly as expressions do.
<% int sum=0;
for(int i=0;i<10;i++)
sum++;
%>
(1) Scriptlet can be placed anywhere within the jsp body.
(2) We can place any number of scriptlet number of scriptlet in JSP.
(3) Each Scriptlet is inserted into the service method of container generated servlet.
(4) The scriptlet is executed each time the page is requested.
(5) The scriptlets contain any java code, they are used for embedding computing logic withing
a JSP page.
Comments in a JSP:
In JSP there are three kinds of comments:
(1) Java Comments/ Scripting Comments
(2) HTML Comments/ Content Comments
(3) JSP Comments/ Hidden Comments
In a Declaration or a scriptlet we can have single line multiline java
comments. HTML Comment is of the form <! >
A JSP Comment is of the form <%--------->
Simple JSP that makes use of the all Scripting Elements:
<html><head><title>Example JSP</title></head>
<body><unset><h1>Example JSP</h1>
153
WEB TECHNOLOGIES
154
WEB TECHNOLOGIES
155
WEB TECHNOLOGIES
UNIT – V
STRUTS
Introduction to Struts:
Definition:
156
WEB TECHNOLOGIES
2. It is based on MVC
3. It stores application routing information and request mapping information in a single core
file called struts-config.xml.
Struts Architecture:
All the incoming requests are intercepted by the struts servlet controller. The struts-config.xml file
is used by the controller to determine the routing information. The flow consists of an alteration
between two transitions:
1. From View-to-Action.
2. From Action-to-View.
Struts Components:
Various Struts components are:
Controller:
This receives all incoming requests. Its primary function is the mapping of a request URL
to an action class.
Struts-config.xml:
This file contains all of the routing and configuration information for the struts application.
Action classes:
Action classes act as a bridge between user-invoked URI’s and business services.
View resources:
View resources consists of JSP’s, HTML, Java script and stylesheet files etc..
157
WEB TECHNOLOGIES
ActionForms:
ActionForms greatly simplify user form validation by capturing user data from the HTTP
request.
Struts Request Lifecycle:
158
WEB TECHNOLOGIES
<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/config/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<load-on-startup>:
When the user request is received for the first time, then to read struts-config.xml from
deployment descriptor through init() method and loading into memory is time consuming process.
In order to avoid this delay we specify <load-on-startup> as 1 that instructs the servlet container to
retrieve struts-config file directly into memory.
The second task the ActionServlet performs is to intercept HTTP request based on the URL pattern
and handle appropriately. The URL pattern can either be a path or suffix. This is specified in
web.xml as shown below:
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
RequestProcessor:
ActionServlet intercepts the HTTP request and it delegates it to another class called
RequestProcessor by invoking its process() method. RequestProcessor first retrieves the
appropriate XML block from struts-config.xml to map the request to corresponding Action class.
This process is done through ActionMapping.
ActionMapping:
ActionMapping is the class that holds the mapping between a URL and Action. A sample
ActionMapping from the struts-config.xml file looks as follows:
<action path=“/login” type=“LoginAction”>
159
WEB TECHNOLOGIES
ActionForm:
ActionForm is the class that reads data from user form and provides it to Action class.
Action:
The Action class provides an entry point where we can start with our application code to
process the request.
RequestProcessor instantiates the Action class specified in the ActionMapping and invokes
the execute() method. The signature of execute() method is as follows:
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest
req,HttpServletResponse res)throws Exception
ActionForward:
The execute() method returns the next view shown to the end user. ActionForward is the
class that encapsulates the next view information. The findForward() method on the
ActionMapping instance retrieves the ActionForward as follows:
ActionForward forward=mapping.findForward(“success”);
“success” is the logical name that is passed as the keyword in findForward().
The findForward() method searches for the logical name success and retrieves the corresponding
view to be displayed to the user.
Struts Configuration file:
<struts-config>
<data-sources>
</data-sources>
<form-beans>
<form-bean name=“bean1” type=“com.example.FormBeanOne”/>
<form-bean name=“bean2” type=“com.example.FormBeanTwo”/>
</form-beans>
<global-exceptions>
<exception type=“com.example.SomeException”
path=“/WEB-INF/jsp/error.jsp”>
</global-exceptions>
<global-forwards>
160
WEB TECHNOLOGIES
161
WEB TECHNOLOGIES
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.example.form.HelloWorldForm;
public class HelloWorldAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest
request, HttpServletResponse response) throws Exception {
HelloWorldForm hwForm = (HelloWorldForm) form;
hwForm.setMessage("Hello World");
return mapping.findForward("success");
}
}
struts-config.xml:
<struts-config>
<form-beans>
<form-bean name="helloWorldForm" type="com.example.form.HelloWorldForm"/>
</form-beans>
<global-forwards>
<forward name="helloWorld" path="/helloWorld.do"/>
</global-forwards>
<action-mappings>
<action path="/helloWorld“
type="com.example.action.HelloWorldAction" name="helloWorldForm">
<forward name="success" path="/helloWorld.jsp" />
</action>
</action-mappings>
</struts-config>
web.xml:
<web-app>
<servlet>
162
WEB TECHNOLOGIES
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp:
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<logic:redirect forward="helloWorld"/>
helloWorld.jsp:
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<bean:write name="helloWorldForm" property="message"/>
</body>
</html>
163
WEB TECHNOLOGIES
164
WEB TECHNOLOGIES
165
WEB TECHNOLOGIES
UNIT – VI
DATABASE ACCESS & AJAX
Introduction:
Every enterprise application is required to access a database either for retrieving the data to
be processed (or) to store the processed data. Java offers a simple approach for database
connectivity through JDBC using which a java application can be connected virtually to any
database.
JDBC is not a s/w product. It is an API which defines interfaces and classes for writing
database applications in java. In fact, JDBC is one of the service API’s in the J2EE. The java.sql &
javax.sql packages provide the necessary library support for the database aware java applications.
JDBC Architecture:
Java Application:
It can be a standalone java program (or) an applet (or) a servlet (or) an EJB, which uses the JDBC
API to get connected and perform operations on the data present in database.
JDBC API:
It is a set of classes & interfaces used in a Java Program for database operations. The java.sql &
javax.sql packages provide the necessary library support.
Driver Manager:
The primary purpose of the driver manager is to load specific drivers on behalf of user application.
166
WEB TECHNOLOGIES
JDBC Driver:
It is a s/w that translates the JDBC method calls into vendor-specific API calls.
ODBC Driver:
ODBC driver is dynamically loaded by the ODBC driver manager for making connection to target
database.
Database:
The real-time it is the database server.
The programmer needs a specific driver to connect to a specific database. Driver implementation
come in four types:
1. Type 1: JDBC-ODBC Bridge Driver (Bridge)
2. Type 2: Native-API / Partly Java Driver (Native)
3. Type 3: All Java / Net - Protocol Driver (Middleware)
4. Type 4: All Java / Native – Protocol Driver (Pure)
1.Type 1: JDBC – ODBC Bridge Driver (Bridge):
Type 1 driver allows an application to access database through an intermediate ODBC driver. It
provides a gateway to the ODBC API, since in purpose is to translate JDBC methods into the
ODBC function calls. Here ODBC acts as a mediating layer between the JDBC driver and the
vendors (Client libraries).
Advantages:
ODBC drivers are commonly available; hence it can work with huge number of ODBC drivers.
Disadvantages:
1. A ODBC binary code must be loaded on each client machine that uses this driver.
167
WEB TECHNOLOGIES
Advantages:
Type 2 driver offers significantly better performance than type 1 driver.
Disadvantages:
The vendor database library needs to be loaded on each client machine consequently. Type 2
drivers cannot be used for internet.
3. Type 3: All Java / Net – Protocol Driver (Middleware):
Type 3 driver translation JDBC calls into the middleware vendor’s protocol which is subsequently
translated to a DBMS protocol by middleware server. The Middleware provides connectivity to
many different databases. The types of drivers are best suited for environment that need to provide
connectivity to a variety of DBMS servers and heterogenous databases.
168
WEB TECHNOLOGIES
Advantages:
The Type 3 driver is server based. So, there is no need for any vendor database library to be present
on client machines.
Disadvantages:
Type 3 drivers require database specific coding be done in the middle tier.
4. Type 4: All Java / Native – Protocol driver (Pure):
Type 4 driver talks directly to the database using Java sources. These type of drivers are
completely implemented in java to achieve platform independence and eliminate deployment
issues.
Advantages:
Performance is significantly better.
Disadvantages:
The user needs a different driver for each database.
Database Programming using JDBC:
In order to query a database using JDBC we need to follow the below steps:
1. Loading the JDBC driver
2. Defining a connection URL
3. Establishing a connection
4. Creating a statement object
5. Executing a query
6. Process the results
7. Close the Connection
1. Loading the JDBC driver:
To load a driver we specify the class name of the database driver in the class.forName() method.
169
WEB TECHNOLOGIES
By doing so, we automatically create a driver instance and register it and the JDBC driver
manager.
170
WEB TECHNOLOGIES
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2. Defining the connection URL:
In JDBC, a connection URL specifies the server host port and database name with which we have
to establish the connection
String url=”jdbc: oracle: thin:@localhost:1521:XE”;
3. Establishing the connection:
With the connection URL, username and password, a network connection to the database can be
established and once the connection is established, database queries can be performed entities the
connection is closed.
Connection con=DriverManager.getConnectio(Url,username,password);
4. Create a statement Object:
Creating a statement object enables us to bend queries and commands to databases.
Statement st=con.Statement();
5. Executing a query:
Given a statement object we can send SQL statements to the database by using execute(),
executeQuery(), executeUpdate() or executeBatch() methods.
st.executeQuery(“select * from customer”);
6. Process the Results:
When a database query is executed , a result set object is returned. The Result set represents a set
of rows and columns that we can process by using various methods.
ResultSet rs=st.executeQuery(“select * from customer”);
String first_name,last_name;
boolean records=rs.next();
if(!records){
system.out.println(“No records reference”);
}
else{
do{
first_name=rs.getString(“first_name”);
last_name=rs.getString(“last_name”);
171
WEB TECHNOLOGIES
172
WEB TECHNOLOGIES
Creating a table:
<%@ Page import=”java.sql.*” %>
<html><head><title>Creating a table</title></head>
<body bgcolor=”pink”>
<center><h1>Creating a table</h1><br>
<%try {
Class.forName(“jdbc.oracle.driver.OracleDriver”);
String url=”jdbc:oracle:thin:@localhost:1521:XE”;
Connection con=DriverManager.getConnection(url,”nvn”,”nvn”);
Statement st=con.createStatement();
String cmd=”create table stafflist(ID(integer), name varchar2(30), Dept varchar2(30), Designation
varchar2(30);”;
St.executeUpdate(cmd);
System.out.println(“<b> Table created Successfully “);
}
Catch(Exception e){
Out.println(“An error occurred”);
}
%>
</center></body></html>
Inserting Data into a table:
<%@ Page import= “java.sql.*” %>
<html><head><title>Inserting Data </h1><br>
<% try {
Class.forName(“jdbc.oracle.driver.OracleDriver”);
String url=”jdbc:oracle:thin:@localhost:1521:XE”;
Connection con=DriverManager.getConnection(url,user,pwd);
Statement st=con.createStatement();
String cmd=”Insert Into stafflist values(1,’abc’,’cse’,”Asst.post”);”;
St.executeUpdate(“cmd”);
173
WEB TECHNOLOGIES
174
WEB TECHNOLOGIES
175
WEB TECHNOLOGIES
can retrieve the Data Source object to create a connection to the physical Data Source it represents.
A Data Source Object can be implemented to work with the middle tier infrastructure so that the
connections it provides will be pooled for reuse.
b) Connection Pooling:
Connections made via a Data Source object are implemented to work with a middle tier.
Connection Pool Manager participate in connection pooling. Connection Pooling allows a
connection to be used and reused thus cursing down substantially the need of making new
connections.
Connection Pooling is totally transparent. It is done automatically in the middle tier of a J2EE
configuration and so there is no need of change in code from application point of view. An
Application simply uses the Data Source.getConnection() method to get the pooled connection
and uses it the same way it uses any connection object. The classes are interfaces used for
connection pooling are:
(1) Connection Pool DataSource
(2) Pooled Connection
(3) Connection Event
(4) Connection Event Listener
c) Distributed Transactions:
As with pooled connections, connections made via a Data Source objects are implemented to
with the middle tier infrastructure may also participate in distributed transactions.
This gives an application the ablility to involve data sources on multiple servers in a single
transaction.
d) RowSets:
The Rowset interface works with the various other classes & interfaces. These can be grouped
into three categories:
i) Event Notification
ii) Meta data
iii) The Reader / Writer facilities.
176
WEB TECHNOLOGIES
Event Notifications:
(a) Rowset Listener:
A Rowset object is a JavaBean is a Java Bean Component and it has participates in the Java
Bean event notification mechanism. The Rowset Listener interface is implemented by a
component that wants to be notified about the events that occur to a particular Rowset object.
(b) Rowset Event:
A Rowset Object creates an instance of Rowset of Rowset Event and passes it to the listener.
The listener can use this Rowset Event object to find which Rowset had the event.
1. Meta Data:
Data about Data (Information about Data)
1. RowSetMetaData:
This interface is derived from the Resultset MetaData and provides information about the
columns in a Rowset object. It provides methods for setting information about columns.
2. The Reader / Writer facility:
A Rowset object that implements the Rowset Internal interface can call on the Rowset
Reader object associated with it to populate itself with data.
It can also call on the Rowset writer object associated with it to write any changes to
its rows back to the datasource from which it originally got the rows.
177