You are on page 1of 104

BRJ001

UNIT-1

HTML

WEB TECHNOLOGIES

(HYPER TEXT MARKUP LANGUAGE)

INTRODUCTION TO HTML
HTML, or Hyper Text Markup Language is designed to specify the logical organisation of a document,
with important hypertext extensions.
HTML allows you to mark selections of text as titles or paragraphs, and then leaves the interpretation
of these marked elements up to the browser.
For example: one browser may indent the beginning of a paragraph, while another may only leave a
blank line.
HTML instructions divide the text of a document into blocks called elements.
These can be divided into two broad categories -- those that define how the BODY of the document is to
be displayed by the browser, and those that define information `about' the document, such as the title
or relationships to other documents. The detailed rules for HTML (the names of the tags/elements,
how they can be used) are defined using another language known as the standard generalized markup
language, or SGML. SGML is wickedly difficult, and was designed for massive document collections.
Fortunately, HTML is much simpler! However, SGML has useful features that HTML lacks. For this
reason, markup language and software experts have developed a new language, called XML (the
eXtensible markup language) which has most of the most useful features of HTML and SGML.

History of HTML
HTML was originally developed by Tim Berners-Lee while at CERN, and popularized by the Mosaic
browser developed at NCSA. During the course of the 1990s it has blossomed with the explosive growth
of the Web. During this time, HTML has been extended in a number of ways. The Web depends on Web
page authors and vendors sharing the same conventions for HTML. This has motivated joint work on
specifications for HTML.
HTML 2.0 (November 1995) was developed under the aegis of the Internet Engineering Task Force
(IETF) to codify common practice in late 1994.HTML 3.0 (1995) proposed much richer versions of
HTML. Achieving interoperability lowers costs to content providers since they must develop only one
version of a document. If the effort is not made, there is much greater risk that the Web will devolve
into a proprietary world of incompatible formats, ultimately reducing the Web's commercial potential
for all participants. Each version of HTML has attempted to reflect greater consensus among industry
players so that the investment made by content providers will not be wasted and that their documents
will not become unreadable in a short period of time. HTML has been developed with the vision that all
manner of devices should be able to use information on the Web: PCs with graphics displays of varying
resolution and color depths, cellular telephones, hand held devices, devices for speech for output and
input, computers with high or low bandwidth, and so on.
Advantages of HTML:
First advantage it is widely used.
Every browser supports HTML language.
Easy to learn and use.
It is by default in every windows so you don't need to purchase extra software.

Disadvantages of HTML:
It can create only static and plain pages so if we need dynamic pages then HTML is not useful.
Need to write lot of code for making simple webpage.
Security features are not good in HTML.
If we need to write long code for making a webpage then it produces some complexity.
Important points

Tags are delimited by angled brackets.


They are not case sensitive i.e., <head>, <HEAD> and <Head> is equivalent.
If a browser not understand a tag it will usually ignore it.
Some characters have to be replaced in the text by escape sequences.
White spaces, tabs and newlines are ignored by the browser.
1

BRJ002

Web Technologies By BRJ

Structure of an HTML document:


All HTML documents follow the same basic structure.
They have the root tag as <html>, which contains <head> tag and <body> tag.
The head tag is used for control information by the browser and the body tag contains the
actual user information that is to be displayed on the screen.
The basic document is shown below.
<html>
<head>
<title> Basic HTML document </title>
</head>
<body>
<h1> Welcome to the world of Web
Technologies</h1>
<p> A sample html program </p>
</body>
</html>

Besides head and body tag, there are some other tags like title, which is a sub tag of head, that
displays the information in the title bar of the browser. <h1> is used to display the line in its own
format i.e., bold with some big font size. <p> is used to write the content in the form of paragraph.
Comments in HTML documents start with <! and end with >. Each comment can contain as many
lines of text as you like. If comment is having more lines, then each line must start and end with -and must not contain -- within its body.

Basic HTML tags Body tag :


Body tag contain some attributes such as bgcolor, background etc.
" bgcolor" is used for background color, which takes background color name or hexadecimal number
and #FFFFFF and background attribute will take the path of the image which you can place as the
background image in the browser.
Example: <body bgcolor=#F2F3F4 background= c:\btech\imag1.gif>
Paragraph tag:
Most text is part of information.
Each paragraph is aligned to the left, right or center of the page by using an attribute called as align.
Example: <p align=left | right | center>
Heading tag:
HTML is having six levels of heading that are commonly used.
The largest heading tag is <h1> .
The different levels of heading tag besides <h1> are <h2>, <h3>, <h4>, <h5> and <h6>.
These heading tags also contain attribute called as align.
Example: <h1 align=left | right | center> .
<h2>

BRJ003

Web Technologies By BRJ

...

HR TAG:
This tag places a horizontal line across the system.
These lines are used to break the page.
This tag also contains attribute i.e., width which draws the horizontal line with the screen size of the
browser. This tag does not require an end tag.
Example: <hr width=50%>.
FONT TAG: This sets font size, color and relative values for a particular text. <font size=10 color=#f1f2f3>
BOLD TAG: This tag is used for implement bold effect on the text <b> . </b>
ITALIC TAG: This implements italic effects on the text. <i>.</i>
STRONG TAG: This tag is used to always emphasized the text <strong>.</strong>
SUB AND SUP TAG: These tags are used for subscript and superscript effects on the text.
Example: <sub> .</sub> <sup>..</sup>
BREAK TAG: This tag is used to the break the line and start from the next line. <br>
&amp &lt &gt &nbsp &quot These are character escape sequence which are required if you want to display
characters that HTML uses as control sequences. Example: < can be represented as &lt.
ANCHOR TAG: This tag is used to link two HTML pages, this is represented by <a> .
Example: <a href= path of the file> some text </a> href is an attribute which is used for giving the path of a
file which you want to link.

HTML COMMON TAGS

1) LISTS:
One of the most effective ways of structuring a web site is to use lists.
Lists provides straight forward index in the web site.
HTML provides three types of list i.e., bulleted list, numbered list and a definition list.
Lists can be easily embedded easily in another list to provide a complex but readable
structures.
The different tags used in lists are as follows. <li> ..</li> The ordered(numbered) and
unordered(bulleted) lists are each made up of sets of list items.
Unordered Lists:
This tag is used to write list items <ul type=disc | square | circle > ..</ul>
This tag is used for basic unordered list which uses a bullet in front of each tag, everything
between the tag is encapsulated within <li> tags.

Ordered Lists:
This tag is used to write list items <ol type=1 | a | I start=n>..</ol>
This tag is used for ordered list which uses a number in front of each list item or it uses any
element which is mentioned in the type attribute of the <ol> tag, start attribute is used for
indicating the starting number of the list.

Definition Lists:
This tag is used to write list items <dl>.. </dl> This tag is used for the third category i.e.,
definition list, where numbers or bullet is not used in front of the list item, instead it uses
definition for the items.
<dt>..</dt> This is a sub tag of the <dl> tag called as definition term, which is used for
marking the items whose definition is provided in the next data definition.
<dd> .</dd> This is a sub tag of the <dd> tag, definition of the terms are enclosed within
these tags. The definition may include any text or block.

BRJ004

Web Technologies By BRJ

Example Program on Lists:Output:-

2) TABLES:

Table is one of the most useful HTML constructs.


Tables are find all over the web application.
The main use of table is that they are used to structure the pieces of information and to
structure whole web page.
Below are some of the tags used in table.
Syntax:<table align=center | left | right border=n width=n% cellpadding=n
cellspacing=n></table>

Every thing that we write between these two tags will be within a table.
The attributes of the table will control in formatting of the table.
Cell padding determines how much space there is between the contents of a cell and its border,
cell spacing sets the amount of white space between cells.
Width attribute sets the amount of screen that table will use.
<tr> .. </tr> This is the sub tag of <table> tag, each row of the table has to be delimited by
these tags.
<th></th> This is again a sub tag of the <tr> tag. This tag is used to show the table heading .
<td>..</td> This tag is used to give the content of the table.

BRJ005

Web Technologies By BRJ

Example Program on Tables:Output:-

3) IMAGES TAG:
The HTML img element inserts an image in the document, which location is set in the "src"
attribute.
Images are great for displaying information that sometimes is hard to explain with text.
by using "alt" attribute which should be used by authors to provide an alternative textual
version for the information displayed in the image.
Img Attributes
src
This attribute contains a URI that is supposed to point to the location of the image resource.
This is the element's most important attribute, and it is mandatory, because without it there
would be no image to display.
<img src="img/treasure-map.jpg" />
alt
The value of this attribute provides a textual alternative for the image's content, and therefore
must describe exactly what the image intends to show.
This is vital when the development of the website needs to reach visually impaired audiences.
<img src="img/treasure-map.jpg" alt="This map displays the route to the treasure. You should
turn right twice and follow straight until you find it." />
5

BRJ006

Web Technologies By BRJ

width
Specifies the width of the image.
This can be different to the real width of the image, and browsers should resize it as needed.
However, specifiyng a different width may cause pixelated images (when bigger) or longer load
periods (when smaller).
<img src="img/treasure-map.jpg" width="100" />
height
Specifies the height of the image.
This can be different to the real height of the image, and browsers should resize it as needed.
However, specifiyng a different height may cause a pixelated images (when bigger) or longer
load periods (when smaller).
<img src="img/treasure-map.jpg" height="50" />
align
This attribute has been deprecated in HTML 4.01.
Therefore its use is no longer recommended.
It specifies the position of the image with respect to the surrounding content.
It can take the following case-insentive values:
top: The top side of the image is vertically aligned with the baseline.
middle: The image is vertically centered with respect to the baseline.
bottom: The bottom side of the image is vertically aligned with the baseline. This is the default
value.
left: The image is floated to the left margin.
right: the image is floated to the right margin.
<img src="img/picture.png" align="center" />
border
This attribute has been deprecated in HTML 4.01.
Therefore its use is no longer recommended.
This attribute sets the border width in number of pixels.
<img src="img/picture.png" border="2" />

Example Program on Images:-

Output:-

Example Program On Image Tags:<html>


<body>
<p>Click on one of the planets to watch it closer:</p>
<img src="planets.jpg" width="500" height="400" usemap="#planetmap">
<map id="planetmap" name="planetmap">
<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.html">
<area shape="circle" coords="90,58,3" alt="Mercury" href="mercury.html">
<area shape="circle" coords="124,58,8" alt="Venus" href="venus.html">
</map>
6

BRJ007

Web Technologies By BRJ

<p><b>Note:</b> The "usemap" attribute in the img element refers to the "id" or "name" (browser
dependant) <br>attribute inthe map element, therefore we have added both the "id" and "name"
attributes to the map element.</p>
</body>
</html>
Output:-

4)HTML FORMS
A webform on a web page allows a user to enter data that is sent to a server for processing.
Forms can resemble paper or database forms because web users fill out the forms using
checkboxes, radio buttons, or text fields.
Example: forms can be used to enter shipping or credit card data to order a product, or can be used to
retrieve search results from a search engine.
When a visitor reaches the form, he only needs to fill the fields and send the form, usually with a
submit button. The sent form is received and processed by a processing agent (usually a server side
script) specified in the value of the "action" attribute of the form element.

The <form> tag is used to create an HTML form for user input.
Form attributes are:
name: This is the name of the form.
action: Here you will specify any script URL which will receive uploaded data.
method: Here you will specify method to be used to upload data. It can take various values but most
frequently used are GET and POST.
There are different types of form controls that you can use to collect data from a visitor to your site.
Text input controls
Buttons
Checkboxes and radio buttons
Select boxes
File select boxes
Hidden controls
Submit and reset button
HTML Forms - Text Input Controls:
There are actually three types of text input used on forms:
Single-line text input controls: Used for items that require only one line of user input, such as
search boxes or names. They are created using the <input> element.
Password input controls: Single-line text input that mask the characters a user enters.
Multi-line text input controls: Used when the user is required to give details that may be longer
than a single sentence. Multi-line input controls are created with the <textarea> element.
7

BRJ008

Web Technologies By BRJ

The <input> tag specifies an input field where the user can enter data.
An <input> element can vary in many ways, depending on the type attribute.
An <input> element can be of type text field, checkbox, password, radio button, submit button, and
more.
Syntax for Input:
<input type=text/password/submit/button/reset/radio/checkbox name=name value=value
[size=n] [maxlength=n]>
Ex: <input type=text name=ename>
Syntax for Textarea:
<textarea name=textarea name cols=n rows=n>
Ex: <textarea name=description cols=30 rows=5> </textarea>

There are 3 types of buttons


submit: This creates a button that automatically submits a form.
reset: This creates a button that automatically resets form controls to their initial values.
button: This creates a button that is used to trigger a client-side script when the user clicks
that button.
Ex: <input type=submit value=submit>
Checkbox:
Checkboxes are used when more than one option is required to be selected. They are created using
<input> tag as shown below.
Ex: <input type="checkbox" name="course" value="oracle" checked> oracle
<input type="checkbox" name="course" value="java"> Java

Radio button
Radio Buttons are used when only one option is required to be selected. They are created using
<input> tag as shown below:
Ex: <input type="radio" name="branch" value="cse" /> cse
<input type="radio" name="branch" value="ece" /> ece
List box
Drop Down Box is used when we have many options available to be selected but only one or two will
be selected..
Syntax: <select name=name multiple size=n >
<option value=value1>
<option value=valuen>
</select>
Ex: <select name="subjects">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
Form for accepting Firstname and Lastname.
<form action="/cgi-bin/hello_get.cgi" method="get">
First name: <input type="text" name="first_name" /><br>
Last name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
8

BRJ009

Web Technologies By BRJ

EXAMPLE PROGRAM ON HTML FORMS

<Html>
<body>
<form action="" method=post name=form1>
<table align="center" border=1 cellpadding=0 cellspacing=5 width="80%">
<tr> <td>Name</td>
<td><input type="text" name="name1" value="John" size="20" maxlength="15" ></td>
</tr>
<tr> <td>Password</td>
<td><input type="password" name="password1" size="20" maxlength="12"></td>
</tr>
<tr> <td>Free Mails for</td>
<td><select name="freestuff" multiple size="3">
<option value="I">Investements
<option value="B"selected>EBusiness
<option value="M">Movies
<option value="U">Music
<option value="T">Technical
</select>
</tr>
</td>
<tr> <td>text area</td>
<td><textarea name="freemails" rows =5 cols= 50> This is free mailing service, you can send your comments by typing in
this text box
</textarea></td>
</tr>
<tr> <td>Information by email</td>
<td><input type="checkbox" name="email" checked></td>
</tr>
<tr> <td>EMails </td>
<td><input type="radio" name="period" value="daily"> daily
<input type="radio" name="period" value="weekly">weekly
<input type="radio" name="period" value="monthly">monthly </td>
</tr>
</tr><tr> <td><input type="submit" name=submit1 value="submit register" id=submit1></td>
<td><input type="reset" name=reset1 value="clear" id=reset1></td>
</tr>
</table>
</form>
</body>
</html>

OUTPUT:

BRJ010

Web Technologies By BRJ

5) FRAMES
Frames allow an author to divide a browser window into multiple (rectangular) regions. Multiple
documents can be displayed in a single window, each within its own frame. Graphical browsers allow
these frames to be scrolled independently of each other, and links can update the document displayed
in one frame without affecting the others. You can't just "add frames" to an existing document. Rather,
you must create a frameset document that defines a particular combination of frames, and then
display your content documents inside those frames. The frameset document should also include
alternative non-framed content in a NOFRAMES element.
Process for coding frames
1. Code the first page with the layout the windows that subdivide your screen (frameset
command)
2. Name each window. This is refered to as a window-target.
3. Code each separate page (individual files) that will be the content of each window. These are
called the source files.
4. Code a "No Frames" option for noframes browsers.
To make a page use frames, add a <frameset> tag immediately after <head> this tag takes two
attributes, cols and rows, which specify the space taken by each frame in the form of a comma
separated list.
You can specify either the number of pixels to use, a percentage, or "*" to mean the rest of the space
once the other values have been worked out. For instance,<frameset rows="40,20%,*"> would divide
the window into three rows, the top-most being 40 pixels deep, the middle one taking 20% of the
window, and the bottom one taking the remainder of the space.
<frameset> has the following attributes
Cols -Specifies no. and size of columns in a frameset either in pixels or % or *
Rows- Specifies no. and size of rows in a frameset either in pixels or % or *
Once you've specified how the window is to be divided up with the <frameset> tag, you then describe
the contents of each frame using <frame>.
This tag takes the following attributes:
src="URL": specifies the URL of the page to be loaded in this frame.
name="name": specifies the name of this window, to be used with <a target>.
marginwidth="value", marginheight="value": sets the size of the margin in the frame. Seriously
optional.
scrolling="yes, no or auto": decides whether the frame will scroll. "Auto" is the default value.
noresize: don't allow the user to resize this frame.
The following special values can also be used as names:
_blank: opens the link in a new unnamed window.
_self: opens the link in the current frame. Useful for overriding a standard target set in <base>
_parent: opens the link in the current frame's parent <frameset>.
_top: gets rid of all frames; the linked page takes up the entire window. Especially appropriate
if the page you're linking to is an external site, and hence nothing to do with your frame
structure.
Frameset which allows a user to see 3 frames at a time.
<html>
Output:
<frameset cols="25%,*,25%">
Frame A
Frame B
Frame C
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset></html>

10

BRJ011

Web Technologies By BRJ

Example Programs on Frames

<html>
<frameset rows="25%,50%,25%">
<frame src="frame_a.html">
<frame src="frame_b.html">
<frame src="frame_c.html">
</frameset>
</html>

<html>
<frameset cols="25%,50%,25%">
<frame src="frame_a.html">
<frame src="frame_b.html">
<frame src="frame_c.html">
</frameset>
</html>

<html>
<frameset rows="50%,50%">
<frame src="frame_a.html">
<frameset cols="25%,75%">
<frame src="frame_b.html">
<frame src="frame_c.html">
</frameset>
</frameset>
</html>

11

BRJ012

Web Technologies By BRJ

JAVA SCRIPT

INTRODUCTION TO JAVA SCRIPT


JavaScript is a scripting language designed primarily for adding interactivity to Web pages and
creating Web applications. The language was first implemented by Netscape Communications Corp. in
Netscape Navigator 2. Client-side JavaScript programs, or scripts, can be embedded directly in HTML
source of Web pages. Depending on the Web developer's intent, script code may run when user opens
the Web page, clicks or drags some page element with the mouse, types something on the keyboard,
submits a form, or leaves the page. One can do things with few lines of JavaScript that will
significantly reduce the load on your server, give the user better feed back, and enhance the
appearance of your web pages.
JavaScript is an object-oriented language with prototypal inheritance. The language supports
several built-in objects, and programmers can create or delete their own objects. Prototypal
inheritance makes JavaScript very different from other popular programming languages such as C++,
C#, or Java featuring classes and classical inheritance. JavaScript does not have classes in the C++ or
Java sense. In JavaScript, objects can inherit properties directly from each other, forming the object
prototype chain.
JavaScript is an interpreted language, with optional JIT-compilation support. JavaScript was a
purely interpreted language. This means that scripts execute without preliminary compilation, i.e.
without conversion of the script text into system-dependent machine code. The user's browser
interprets the script, that is, analyzes and immediately executes it.
JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! JavaScript is usually
embedded directly into HTML pages
BENEFITS OF JAVASCRIPT
It is widely supported in browser
It is also an easy language to get started using.
It gives easy access to document object and can manipulate most of them.
JavaScript can give interesting animations with many multimedia datatypes.
Special plug-in are not required to use JavaScript
JavaScript is secure language
JavaScript code resembles the code of C language, The syntax of both the language is very close
to each other. The set of tokens and constructs are same in both the language.

DISADVANTAGES OF JAVASCRIPT
Different versions of Netscape will behave differently depending on the language features you use.
It is possible to write JavaScript programs that use advanced JavaScript features but do not cause
problems on older browsers. However, doing this is can be a complex and labour intensive process.
Unfortunately, even the same version of Netscape may behave differently depending on the operating
system it is run on. The language is very new and still evolving. Few software development tools exist
to help you write and debug your scripts. And while you can do a lot with JavaScript, some things like
animation, scrolling/animated banners and notices, and complex programming are often better done
using animated GIFs, Netscape Plugins such as Flash, or Java applets.
JavaScript is used for the following purposes:
JavaScript is also an easy language to get started using.
JavaScript was designed to add interactivity to HTML pages
build small but complete client side programs.
build forms that respond to user input without accessing a server;
validate user input in an HTML form before sending the data to a server;
change the appearance of HTML documents and dynamically write HTML into separate
Windows;
manipulate HTML "layers" including hiding, moving, and allowing the user to drag them
around a browser window;
12

BRJ013

Web Technologies By BRJ

A JavaScript can be set to execute when something happens, like when a page has finished
loading or when a user clicks on an HTML element
A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load
another page specifically designed for that browser
A JavaScript can be used to store and retrieve information on the visitor's computer

JAVASCRIPT AND JAVA


A common misconception is that JavaScript is similar or closely related to Java; this is not so.
Both have a C-like syntax, are object-oriented, are typically sandboxed and are widely used in
client-side Web applications, but the similarities end there. Java has static typing; JavaScript's
typing is dynamic

Java is loaded from compiled bytecode; JavaScript is loaded as human-readable code. C is their
last common ancestor language.
Nonetheless, JavaScript was designed with Java's syntax and standard library in mind. In
particular, all Java keywords are reserved in JavaScript, JavaScript's standard library follows
Java's naming conventions

What are the different datatypes in JavaScript?


Numbers
"no explicit distinction between integers and real" numbers though integers may be stored differently
than floating point or real numbers. Here are some literal numbers being assigned to a variable (not a
complete sampling):
x=8
//integer
x = .7343 //floating point
x = -4.3e3 //same as -4.3 103
x = 4.3e-3 //same as 4.3 10-3
Boolean Values
true or false are the two boolean values
Examples when true or false values result from an expression (not a complete sampling):
10 < 11 //will be evaluated to result in the value true
10 > 11 //will be evaluated to false

Strings
strings can be created by assigning a literal value to a variable or by creating a String object
initialized with a literal string.
msg = "I there is no end to the details I have to remember?"
msg = new String("Is there is not end to the details I have to remember?")
null
null - "special key word denoting a null value"
x = null

What are the different controls in Javascript?


In JavaScript we have the following conditional statements:
if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
if...else if....else statement - use this statement to select one of many blocks of code to be
executed
switch statement - use this statement to select one of many blocks of code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax:
13

BRJ014

Web Technologies By BRJ

if (condition)
{
code to be executed if condition is true
}
else
{
Code to be executed if condtion is not true
}

Ex:
If (a>b)
{ document.writeln(a is greatest);
}
Else
{
Document.writeln(b is greatest);
}

Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
Ex:
var day=new Date().getDay();
switch (day)
{
case 0:
x="Today is Sunday";
break;
case 1:
x="Today is Monday";
break;
-------------default:
x="Today is Saturday";
break;
}

Loops
Loops are handy, if you want to run the same code over and over again, each time with a different
value.
The for loop is often the tool you will use when you want to create a loop.
for (statement 1; statement 2; statement 3)
{
14

BRJ015

Web Technologies By BRJ

the code block to be executed


}

Statement 1 is executed before the loop (the code block) starts.


Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.
Example
for (var i=0; i<5; i++)
{
x=x + "The number is " + i + "<br>";
}

For/in Loop
The JavaScript for/in statement loops through the properties of an object:
var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (var x in person)
{
txt=txt + person[x];
}

While loop
The while loop loops through a block of code as long as a specified condition is true.
while (condition)
{
code block to be executed
}
Example
The loop in this example will continue to run as long as the variable i is less than 5:
Example
while (i<5)
{
x=x + "The number is " + i + "<br>";
i++;
}

The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do
{
code block to be executed
}
while (condition);
Example
The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:

15

BRJ016

Web Technologies By BRJ

Example
do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);

WHAT CAN A JAVASCRIPT DO?


JavaScript gives HTML designers a programming tool - HTML authors are normally not
Programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put
small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something happens, like
when a page has finished loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and change the content of
an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is
submitted to a server. This saves the server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed for that
browser
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer
SCRIPT TAGS:
The <Script> tag alarms a program that javascript code takes after.
It is ordinarily inserted in the html programs.
Syntax:
<SCRIPT Language= JavaScript>
Java Script code
</ SCRIPT>
EMBEDDING JAVASCRIPT
Java Script can be embedded in 3 ways
1) Embedding in the html programs
2) Inline code
3) External File
1) Embedding in the html programs
<html><head>
<title>Java Script</title>
</head>
<body bgcolor=red>
<script language="JavaScript">
alert("My First Java Script Page");
</script>
</body>
</html>
16

BRJ017

Web Technologies By BRJ

2) Inline code
<html><head>
<title>Java Script</title>
</head>
<body bgcolor=red>
<form>
<script language="JavaScript">
function inline()
{
alert("My First JavaScript Page");
}
</script>
<input type="button" value="Click Me" onclick="inline()">
</form>
</body>
</html>

3) External File
You can utilize the SRC characteristic of the <script> tag to call javascript code from an outside
content record. This is helpful when you want to decrease the length of your code.
Syntax:
<SCRIPT SRC=script.js Language =JavaScript> ....</SCRIPT>
Example:
First open the notepad and write the script content
Alert ("My External Script File");
Save it as script.js
<html><head>
<title>Java Script</title>
</head>
<body bgcolor=red>
<script language="JavaScript" src=script.js>
</script>
</body>
</html>

OBJECTS IN JAVASCRIPT
JavaScript supports programming with objects.
Objects are a way of organizing the variables.
The different screen elements such as Web pages, forms, text boxes, images, and buttons are
treated as objects.
JavaScript code is not compiled, but parsed.
This allows for flexibility when it comes to creating or altering objects.

Every object has its own properties and methods.


Properties define the characteristics of an object.
Examples: color, length, name, height, width
Methods are the actions that the object can perform or that can be performed on the object.
Examples: alert, confirm, write, open, close

JavaScript provides 3 kind of objects:


1. Built-in objects- Math,Date,String
2. Document objects
17

BRJ018

Web Technologies By BRJ

3. Window objects

1)Built-in objects- Math,Date,String


Math Object
The Math object provides methods for many mathematical calculations, including: abs(), log(),
pow(), random(), round(), sqrt()
Format: Math.method(#)
For eg, document.writeln (Math.sqrt(900.0)); // /it returns 30.0
EXAMPLE:

OUTPUT

<html><head>
<title>Example on properties</title>
</head>
<body bgcolor=red>
<form name="f1">
<script language="JavaScript">
function calc(txt)
{
var num=txt
round=Math.round(num)
alert("rounded number is: "+round);
}

function calc1(txt)
{
var num=txt
round=Math.sqrt(num)
alert("Square Root of a number is: "+round);
}

</script>
Please Enter the Float Number: <Input type="text" name="t1" id="t1"><br>
<input type="button" value="Round Off" onClick="calc(f1.t1.value)"><br>
<input type="button" value="SquareRoot" onClick="calc1(f1.t1.value)">
</form>
</body>
</html>

Date Object
The Date object provides the day, date, and time information.
Format: dateObject.method()
var today = new Date();
document.write(today);
Produces:
wed Feb 12 09:41 EST 2014
Example:

<html><head>
<title>Example on properties</title>
</head>
<body bgcolor=violet>
<form name="f1">
<script language="JavaScript">
function jsdate()
{
var year=new Date()
alert(year);
}
</script>
<input type="button" value="Show Today's Date and Time"

18

BRJ019

Web Technologies By BRJ

onClick="jsdate()">
</form>
</body>
</html>

String Object
The String object provides methods and properties for string manipulation and formatting.
Format: stringName.method()
Eg, var name = Ruchi;
document.write(name.length);
2) Document Object:

The Document object represents the Web page that is loaded in the browser window, and the
content displayed on that page, including text and form elements.
Document Methods
Here are the most common document methods:
write() - write a string to the Web page
open() - opens a new document
close() - closes the document

3) Window Object:

The window object represents the browser window. You can use it to open a Web page in a
new window and to set the attributes for the window. There are only two main window
properties.
Window Methods
The window methods are mainly for opening and closing new windows.
alert() - to display a message box
confirm() - to display a confirmation box
open() - to open a new window
close() - to close a opened window.

Dynamic HTML using JavaScript


Dynamic HTML, or DHTML, is an umbrella term for a collection of technologies used together to
create interactive and animated web sites by using a combination of a static markup language (such
as HTML), a client-side scripting language, a presentation definition language (such as CSS), and
the Document Object Model.
DHTML allows scripting languages to change variables in a web page's definition language, which in
turn affects the look and function of otherwise "static" HTML page content, after the page has been
fully loaded and during the viewing process. Thus the dynamic characteristic of DHTML is the way it
functions while a page is viewed, not in its ability to generate a unique page with each page load.

DHTML is differentiated from Ajax by the fact that a DHTML page is still request/reload-based. With
DHTML, there may not be any interaction between the client and server after the page is loaded; all
processing happens in JavaScript on the client side. By contrast, an Ajax page uses features of DHTML
to initiate a request to the server to perform actions such as loading more content.
JavaScript (more on JavaScript in a bit) is a programming language that both Netscape Navigator and
Internet Explorer can understand, making it a good choice for cross-browser DHTML.
DHTML Means showing the dynamic content on the web page rather than the static content.
19

BRJ020

Web Technologies By BRJ

Examples on DHTML:

<html>
<head><title>Dymamic</title></head>
<body bgcolor=red>
<p onclick="this.style.fontSize='90px'">Click me to Increase the size</p>
</body>
</html

<html>
<head><title>Dymamic</title></head>
<body bgcolor=red>
<p onclick="this.style.color='white'">Click me to change the color</p>
</body>
</html>

20

BRJ021

Web Technologies By BRJ

XML(eXtensible Markup Language)


INTRODUCTION TO XML

XML can be used to simplify data storage and sharing. With XML, data is separated from HTML. So you
can create HTML layouts for displaying data. When the data changes, you don't have to recreate your
HTML file. With XML, data can also be easily exchanged between computer and database systems;
even they are incompatible in any other ways. Because XML data is stored in text format, this makes it
easier to export data from a system to an XML file, and then import it into another system.

What is XML?

XML stands for EXtensible Markup Language, which became a W3C Recommendation on 10. February
1998. XML is a markup language which is like HTML. XML and HTML both use tags. But there are
some differences between them:
HTML was designed for how to display data. And XML was designed for how to store data.
HTML tags are predefined (for example "<p>", "<table>", etc.). But XML tags are not predefined.
You must define your own tags
The following example is product information, stored as XML:
<product>
<name>
Garmin Oregon 300 3 inch' Touch screen Handheld GPS Unit with a Built-in Base
map and Shaded Relief
</name>
<category>GPS</category>
<brand>Garmin</brand>
<price>529.99</price>
<description>
Handheld GPS navigator for use outdoors, in a car, or on a boat 3 inch LCD touch
screen display (240 x 400 pixels) with built-in picture viewer
</description>
</product>
As you can see, it is just pure information wrapped in tags, which are not like HTML tags ("<table>",
"<tr>", etc.) are predefined. You can create your own tags, like the ones in the above example, for your
XML file.
XML can be used to simplify data storage and sharing. With XML, data is separated from HTML. So you
can create HTML layouts for displaying data. When the data changes, you don't have to recreate your
HTML file. With XML, data can also be easily exchanged between computer and database systems,
even they are incompatible in any other ways. Because XML data is stored in text format, this makes it
easier to export data from a system to an XML file, and then import it into another system. Before we
have XML, the task of exchanging data between incompatible systems was not easier and complicated
due to the different data formats. Now XML greatly reduces this complexity, and we can be easily
expand or upgrade our operating systems and applications without losing data.

XML FORMAT AND STRUCTURE

A XML document is consist of tags and data. All data in an XML document is wrapped by the tags.
EXAMPLE:
<?xml version="1.0" encoding="ISO-8859-1"?>
<customer>
<firstname>Michael</firstname>
<lastname>Smith</lastname>
<gender>male</gender>
<address>
<street>197 West Park Ave.</street>
<city>New York</city>
21

BRJ022

Web Technologies By BRJ

<state>NY</state>
<zip>11375</zip>
<country>US</country>
</address>
<phone>718-235-5670</phone>
<email>msmith278@yahoo.com</email>
</customer>
The first line is the XML declaration. It defines the XML version (1.0) and the character set (ISO-8859).
The next line uses tag "<customer>". It is the root element of the document. The next four lines
describe the child elements () of the root: Please note that, except the first line, all tags in the
document are used in pair: opening tag and closing tag. You can assume, from the above example, a
pair of tags provide a "container", and data or child tags are stored inside.
Also, you can assume, the structure of an XML document is defined by the relationship between these
"containers": a large container contains smaller containers. Or you can assume the structure of an
XML file as a "tree" that starts at the root tag "customer" and branches to the leaves tags "firstname",
"lastname", "gender", "address", "phone" and "email":
customer ->
firstname
lastname
gender
address ->
street
city
state
zip
country
phone
email
Please note, an XML document must contain a pair of root tags for the "parent" element, whcih
contains all other elements. You cannot have two roots in a single XML document. All elements can
have child elements:
<root>
<child1>......</child1>
<child2>

<subchild1>.....</subchild1>

<subchild2>.....</subchild2>

</child2>
</root>

XML Namespace

Namespaces have two purposes in XML:


1. To distinguish between elements and attributes from different vocabularies with different
meanings and that happen to share the same name.
2. To group all the related elements and attributes from a single XML application together so that
software can easily recognize them.

WHAT IS AN XML NAMESPACE?

An XML namespace is a collection of names that can be used as element or attribute names in an XML
document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts
between elements with the same name. The namespace is identified by some Uniform Resource
22

BRJ023

Web Technologies By BRJ

Identifier (URI), either a Uniform Resource Locator (URL), or a Uniform Resource Number (URN), but
it doesn't matter what, if anything, it points to. URIs is used simply because they are globally unique
across the Internet.
Namespaces can be declared either explicitly or by default. With an explicit declaration, you define a
shorthand, or prefix, to substitute for the full name of the namespace. You use this prefix to qualify
elements belonging to that namespace. Explicit declarations are useful when a node contains elements
from different namespaces. A default declaration declares a namespace to be used for all elements
within its scope, and a prefix is not used.

WHY IS IT NECESSARY?

As an example, let's assume we have an RDB with a table of the following structure (employeeTable,
sectionTable). What kind of SQL statement would you create to obtain a list of Employee ID, Employee
Department Name, and Employee Name? If we merged employeeTable and sectionTable with the
secID column, then we would be able to obtain a list of employee IDs, employee departments and
employee names. However, since the name column and secID column exist in both tables, we would
have to designate the table name before the name and secID columns, or designate the alias of the
table in order to clarify the table of the name and secID columns in question.

So, what happens when this data is expressed in an XML document? Let's take two XML documents,
and see how we can create a list showing employee ID, employee department and employee name
using XML.
First, we will create a root element (employeeList element) and an element (personList element) to
summarize employee information for one individual. You might have thought about creating an
employee ID element (empID element in employeeXML document), department name element (name
element in sectionXML document) and an employee name element (name element in employeeXML
document) as child elements, but there's a problem with this method. The problem is an "element
name conflict." The name element in the employee XML document is defined as an element
representing the employee's name, whereas the name element of the section XML document is
defined as an element representing a department name. In merging these two XML documents, you
will get a name element that has two separate meanings. While a human might be able to tell the
difference between these two "name" elements and what they represent, computer systems cannot
23

BRJ024

Web Technologies By BRJ

determine what these name elements are supposed to mean. The XML 1.0 specification never
considered the merging of different types of XML documents (vocabularies) to create a new XML
document, which led to this type of name conflict problem.
employeeXML Document
<employee>
<personInfo>
<empID>E0000001</empID>
<secID>S001</secID>
<name>John Smith</name>
</personInfo>
<personInfo>
<empID>E0000002</empID>
<secID>S002</secID>
<name>Ichiro Tanaka</name>
</personInfo>

</employee>
sectionXML Document
<section>
<sectionInfo>
<secID>S001</secID>
<name>Sales</name>
</sectionInfo>
<sectionInfo>
<secID>S002</secID>
<name>Development</name>
</sectionInfo>

</section>

employeeListXML Document
<employeeList>
<personList>
<empID>E0000001</empID>
<name>Sales</name>
<name>John Smith</name>
</personList>
<personList>
<empID>E0000002</empID>
<name>Development</name>
<name>Ichiro Tanaka</name>
</personList>

24

BRJ025

Web Technologies By BRJ

</employeeList>

The name element expressing employee name and the name element expressing department
name conflict!

Avoiding Element Name Conflicts

Perhaps some of you out there had the idea that element name conflicts can be avoided by applying
the same type of alias used for RDB table merge explained above to an XML document. The W3C
recommended a specification called "Namespaces in XML," whereby XML vocabularies are mutually
differentiated, allowing for the re-use of a vocabulary. Utilizing this XML namespace allows us to avoid
any element name conflicts.
Here, we will add an XML namespace declaration and description in both the employee data XML
document and section data XML document. Next, we will merge these two XML documents, and create
a new employeeList data XML document. As a result, we can differentiate the "emp:name element" of
the employeeList data XML document as an element representing employee name, and the "sec:name
element" as an element representing department name. It might be easiest to think of one namespace
as an aggregation of elements and attributes.
Employee XML Document
<emp:employee xmlns:emp="urn:corp:emp">
<emp:personInfo>
<emp:empID>E0000001</emp:empID>
<emp:secID>S001</emp:secID>
<emp:name>John Smith</emp:name>
</emp:personInfo>
<emp:personInfo>
<emp:empID>E0000002</emp:empID>
<emp:secID>S002</emp:secID>
<emp:name>Ichiro Tanaka</emp:name>
</emp:personInfo>

</emp:employee>
section XML Document
<sec:section xmlns:sec="urn:corp:sec">
<sec:sectionInfo>
<sec:secID>S001</sec:secID>
<sec:name>Sales</sec:name>
</sec:sectionInfo>
<sec:sectionInfo>
<sec:secID>S002</sec:secID>
<sec:name>Development</sec:name>
</sec:sectionInfo>

</sec:section>
employeeList XML Document
<list:employeeList
xmlns:list="urn:corp:list"
xmlns:emp="urn:corp:emp"
25

BRJ026

Web Technologies By BRJ

xmlns:sec="urn:corp:sec">

<list:personList>
<emp:empID>E0000001</emp:empID>
<sec:name>Sales</sec:name>
<emp:name>John Smith</emp:name>
</list:personList>
<list:personList>
<emp:empID>E0000002</emp:empID>
<sec:name>Development</sec:name>
<emp:name>Ichiro Tanaka</emp:name>
</list:personList>

</list:employeeList>

NAMESPACE DECLARATION

Write a namespace declaration according to the following description method, describing the element
start tag:

If the element and/or attribute belong to a namespace, a colon (":") is placed between the namespace
prefix and the element name/ attribute name.
As a test, let's take the previous employeeList XML document as an example, and provide a namespace
declaration and an element belonging to the namespace.
<emp:employee
xmlns:emp="urn:corp:emp">
<emp:personInfo>
omitted
</emp:personInfo>
</emp:employee>
In this example, we have declared the namespace prefix as "emp", and the namespace identifier (URI)
as "urn:corp:emp". This means that element names and attribute names with the "emp" prefix
(including the employee element) all belong to the urn:corp:emp namespace.

If the namespace prefix is not provided for an element and/ or attribute name, except for cases where
a default namespace is declared (to be discussed later), the element name and/ or attribute name do
not belong to a namespace. While the namespace declaration is described as a start tag attribute, this
is different than a regular attribute. Elements having only an "xmlns:~" description have a namespace
declaration, but no attribute.
26

BRJ027

Web Technologies By BRJ

Any arbitrary text string can be used as a namespace prefix; since there is no special meaning, any text
string will do. However, the URI must be universally unique. Quite often a URL beginning with
"http://~" is used in practice. Since the URL is not actually accessed, it is not a problem if the file, etc.
does not really exist. Understand that a URI represents nothing more than a logical namespace name.

DEFAULT NAMESPACES

A "default namespace" is a namespace declaration that does not use a namespace prefix (See Figure
for notation method). The scope of the default namespace is the element for which the namespace was
declared and the related content, just as with the namespace scope discussed earlier. The benefit of
using a default namespace is that the namespace prefix can be omitted.

For example, when adding a new namespace to an existing XML document, writing a namespace prefix
for each element to which the new namespace will be applied involves a tremendous amount of
tedious work. The larger the XML document, the greater the labor involved, and the greater the
likelihood of notation errors. In this type of situation, adding only a default namespace declaration to
the XML document in question eliminates the need to write a namespace prefix for each and every
element, saving a lot of time.
On the other hand, there are drawbacks. One drawback is that omitting the namespace prefix makes it
more difficult to understand which element belongs to which namespace, and which namespace is
applicable. In addition, programmers should remember that when a default namespace is declared,
the namespace is applied only to the element, and not to any attributes.

A default namespace can be overwritten partially by declaring a completely different default


namespace within the scope of the original default namespace. A default namespace can be canceled
using the following notation method:

27

BRJ028

Web Technologies By BRJ

NOTATION TO CANCEL A DEFAULT NAMESPACE


elementname xmlns=""
The xmlns="" designation frees an element within the namespace scope from belonging to any
namespace. A namespace using a namespace prefix can be designated within the scope of a default
namespace.

THE NEED FOR XML DOCUMENT SCHEMA


XML documents are used for many different purposes today. Order processing, invoices, estimates,
travel expense reports, meeting minutes, accounting forms, manuals, and other data used on a daily
basis at work are only the tip of the iceberg. Now, we see XML used for personal data such as journals,
household finances, and other applications. Virtually any data can be created using XML format, since
XML allows a user to freely define element names and hierarchical structure.
In this volume, we will be looking both at writing XML documents simply according to XML syntax
(well-formed XML documents), as well as writing XML documents to be used as business-to-business
data, or in other words, a data format to be shared between and among different companies.
For example, if requested to create an XML document to serve as a purchase order to be sent to Mr. Y
at Company X, what kind of XML document would you create? The following are three XML document
examples, created by three different individuals. Ms. A has created very semantic element names. Mr.
B has opted for rather abbreviated element names, and Ms. C has created elements having a
hierarchical structure.

Even a simple request to create an XML document to serve as a purchase order to be sent to Mr. Y at
Company X can take on a number of different XML document patterns. Any of the three examples
above can be considered to be proper XML documents. As long as the information required for a
purchase order is included, likely any XML document you could create would be a valid XML
document for the purpose.
But what would change if you approached the task from Mr. Y's perspective? Assume that Mr. Y uses
the three XML documents above, or your XML document, for order processing. Having received XML
documents with different element names and hierarchical structures, Mr. Y would have to open each
XML document in an editor, confirm whether all of the required information was present, and then
process the purchase order. In this case, every purchase order would have to be processed by hand,
and the entire system could never be automated.
But what would happen if all XML documents sent had the same element names and hierarchical
structure? With standard element names and structures, a system could be created to handle all
incoming XML documents, and order processing could be automated, without Mr. Y having to verify
the content of each individual document.
28

BRJ029

Web Technologies By BRJ

A "Schema" is what is required to allow the acceptance (or creation) of XML documents with a
standardized element name and hierarchy structure. We know that in the RDB world, a schema is
defined when designing tables to stipulate category (column) data types and data sizes, set the
primary key, associate tables with other tables, etc. Under XML Schema, a user notates element names,
orders of occurrence, and number of occurrences. When XML is used for specific purposes, a schema
will first be defined, and then XML documents will be created in accordance with that schema. In
doing so, anyone can create an XML document having the same exact element names and hierarchical
structure.
Let's take another look at the task for creating an XML document to be used for a purchase order.
Assume that Mr. Y sends to Ms. A, Mr. B, and Ms. C a schema document for purchase orders (XML
document). Ms. A, Mr. B., and Ms. C then each create an XML document based on Mr. Y's schema. The
element names and hierarchical structure of the XML documents they send to Mr. Y are completely
identical.
Mr. Y can now use an XML parser to verify whether the documents have been created according to the
schema, so there is no need to open each file and check element names and hierarchy structures. This
reduces Mr. Y's workload significantly.
TYPES OF XML DOCUMENT SCHEMA
There are many different types of XML document schema. While the following type of narrative
format can be considered a type of schema, there is the chance that different people will interpret the
narrative differently. This is why, in general, XML document schema is created using Schema
Definition Language. Schema Definition Language is specialized definition language for noting schema,
and leaves no room for interpretive differences.

PURCHASE ORDER XML SCHEMA


[1] The root element is "orderform"
[2] The content of "orderform" is a "customer" element and a "product" element in that order.
"customer" occurs once, and "product" may occur zero or more times.
[3] The content of "customer" is the "name", "address", and "tel" elements, each occurring once in
order
[4] The content of "name" and "address" is a text string
[5] The content of "tel" is the "portable" and "home" elements, with either one or the other
occurring
[6] The content of "portable" and "home" is a text string
[7] The content of "product" is the "product_name" and "num" elements, each occurring once in
order
[8] The content of "product_name" is a text string
[9] The content of "num" is a numeric value
There is more than one Schema Definition Language out there. The Schema Definition Language
defined under the XML 1.0 specification is the "DTD (Document Type Definition)." An even more
strictly defined Schema Definition Language is the "XML Schema" determined by the W3C. Different
vendors also have defined various Schema Definition Languages.
DTD SCHEMA DEFINITION
Under DTD, the main categories comprising the XML document are declared. Declarations come under
one of the following four categories:
Element Type Declaration
Attribute List Declaration
Entity Declaration
Notation Declaration
Here, we will discuss the most important of these, the "Element Type Declaration."
Element Type Declarations declare elements contained within an XML document. The following shows
the syntax for an Element Type Declaration.
29

BRJ030

Web Technologies By BRJ

The Content Model is very important in the Element Type Declaration. It defines whether the element
content is a text string or numeric value (character data), whether only child elements occur (element
content), etc.

WHEN CONTENT IS TEXT STRING OR NUMERIC VALUE


When the element content is a text string or numeric value, the Content Model is designated as
#PCDATA. Under DTD, there is no difference between numeric type data and text type data. For
example, the following describes the Element Type Declaration that designates the content of
"product_name" as a text string:
<!ELEMENT product_name (#PCDATA)>
The correct element description that conforms to this Element Type Declaration is
<product_name>television</product_name>. Describing a child element such as
<product_name><abc/></product_name> will cause an error.
The following describes the Element Type Declaration that designates the content of "num" as a
numeric value:
<!ELEMENT num (#PCDATA)>
The correct element description for this definition is <num>10</num>. As discussed earlier, both text
strings and numeric values for element content are designated as #PCDATA under DTD, so
<num>Jenny</num> is a correct notation. The application must perform a check to see whether the
content of an element is actually a number.
When content is a child element
When a child element occurs as the content of an element, the element name of the child element
occurring is designated in the Content Model. However, the order of occurrence and number of
occurrences of the child element must also be defined.
Defining the order of occurrence

When there are a multiple number of child elements, you must designate the order of occurrence.
There are two ways to notate the order of occurrence. Using a comma (,) between the child element
name and the next child element name indicates that the child elements will occur in the order given.
Using a vertical line (|) means that either one or the other child element will occur.
","

"|"

Occurs in the order given

Either one or the other child element occurs

In the following example, the content of "product" is the "product_name" and "num" elements,
occurring once each in that order.
<!ELEMENT product (product_name,num)>
30

BRJ031

Web Technologies By BRJ

The following is a valid element description for this type of Element Type Declaration:
<product>
<product_name>television</product_name>
<num>10</num>
</product>
Because "," defines the order of occurrence as the order in which the child element was written, the
following would be examples of invalid notation:

To describe an Element Type Declaration where either the "portable" or "home" element (child
elements of "tel") occurs:
<!ELEMENT tel (portable|home)>
In this case, the following would be an error when describing both the portable and home elements:
tel
portable/portable
home/home
/tel

Defining the number of occurrences


In addition to the order of occurrence for child element names, the number of occurrences is also
defined in the Content Model. The number of occurrences is designated with one of three symbols: "*",
"+" or "?". The "*" symbol means "may occur zero or more times." The "+" symbol means "may occur
one or more times." The "?" symbol means "may occur zero times or one time."
As with the notation examples for the Element Type Declaration
<!ELEMENT product product_name,num>
shown earlier, not providing an symbol for the number of occurrences means "must occur once."
"*"

May occur 0 or more times

" "

May occur zero times or once

May occur one or more times

" "

No designation

One time

Under DTD, a programmer may not designate a specific number of occurrences (e.g. three times,
between two and five times, etc.).
For example, output the "customer" and "product" elements (content of "orderform") in that order.
To describe an Element Type Declaration designating one occurrence for "customer" and zero or
more occurrences for "product", use the following notation:
<!ELEMENT orderform (customer,product*)>
Now, let's describe all of the elements, referencing the notation examples above.
Use the "dtd" extension when actually creating the document. The following shows a file named
"order.dtd", describing the Purchase Order XML schema DTD:
order.dtd
<!ELEMENT orderform (customer,product*)> [1][2]
<!ELEMENT customer (name,address,tel)> [3]
<!ELEMENT name (#PCDATA)>
[4]
<!ELEMENT address (#PCDATA)>
[4]
<!ELEMENT tel (portable | home)>
[5]
31

BRJ032

Web Technologies By BRJ

<!ELEMENT portable (#PCDATA)>


[6]
<!ELEMENT home (#PCDATA)>
[6]
<!ELEMENT product (product_name,num)>
[7]
<!ELEMENT product_name (#PCDATA)>
[8]
<!ELEMENT num (#PCDATA)>
[9]
LIST1 Valid XML Document for DTD
orderform.xml
<!DOCTYPE orderform SYSTEM "order.dtd">
<orderform>
<customer>
<name>Jenny</name>
<address>Tokyo</address>
<tel>
<portable>555-5555-5555</portable>
</tel>
</customer>
<product>
<product_name>washing machine</product_name>
<num>1</num>
</product>
<product>
<product_name>television</product_name>
<num>2</num>
</product>
</orderform>

Declaration to Associate an XML Document and Schema Document


The <!DOCTYPE> at the beginning of LIST1 is called the "Document Type Declaration," and
designates the DTD that defines the structure of the XML document. There are two types of notation
methods, one being an "internal subset" describing the Element Type Declaration and individual
declarations within the Document Type Declaration, and the other being an "external subset" (used
here) where the Element Type Declaration and individual declarations are designated in an external
file. In this volume, we will discuss the notation method for an external subset.
The location for the Document Type Declaration is predetermined, coming above the start tag of the
root element. The Document Type Declaration syntax is described as shown below, and then the root
element name and file name are designated:
Validating the XML Document
Once the schema document and XML document have been created, we can verify whether the XML
document has been created in accordance with the schema document. This validation can be
performed using an XML parser, eliminating the need for manual verification or creating a separate
validation program.
In the prior volume, we explained how to use Internet Explorer ("IE") to verify whether an XML
document has been correctly written. However, the XML parser incorporated within IE cannot verify
whether an XML document has been created in accordance with a particular schema document.
Accordingly, we will use a verification XML processor.
Let's verify the XML document we created against the schema document.
Next, create the XML document as shown in LIST2, and conduct the same operation as before. An
error message should result.
32

BRJ033

Web Technologies By BRJ

LIST2Invalid XML Document with respect to a DTD


orderform_err.xml
<!DOCTYPE order form SYSTEM "order.dtd" >
<orderform>
<customer>
<name>Jenny</name>
<address>Tokyo</address>
</customer>
<product>
<product_name>washing machine</product_name>
<num>1</num>
</product>
<product>
<product_name>television</product_name>
<num>2</num>
</product>
</orderform>
The reason that this type of error occurred is that the tel element does not occur in the XML document
in LIST2, while the schema document requires that the "name", "address" and "tel" elements (content
of "customer") occur once in that order. Use the error message in the dialog box as a clue to check the
line before and after the error, and make the necessary edits.
Entity Declaration
In the prior volume, we discussed using predefined entity references, since "<" and "&" characters
cannot be used directly as the content of an element. Since the <calculation>a1<b2</calculation>
statement
causes an
error to occur,
we
rewrote
the
statement to read
<calculation>a1&lt;b2</calculation>. There are five types of predefined entity references provided
under the XML 1.0 specification.
<Table> Predefined Entity References
Entity

Entity Name

Symbol Notation

lt

&lt;

&

amp

&amp;

gt

"

quot

'

apos

&gt;

&quot;

&apos;

When using a DTD entity declaration, you can define your own entity references in addition to the five
types above.

What is XML Schema?


In previous, we discussed well-formed XML documents, valid XML documents using DTDs, and XML
parsers. DTD has a characteristically simple syntax for functions and content definition. We see,
however, that DTD functions and definitions have limitations when it comes to using XML for a variety
of complex purposes.
Traditionally, DTD has been the standard for XML schema definition; however, XML usage has
expanded dramatically in core application systems, being tailored for a wide range of purposes for
which DTD is not fully capable of supporting. Given this development, the W3C recommended "XML
Schema" as a schema definition language to replace DTD. The recommendation of XML Schema has
spurred its adoption as a standard schema definition language.
33

BRJ034

Web Technologies By BRJ

DIFFERENCES BETWEEN XML SCHEMA AND DTD DEFINITIONS


What differences are there between XML Schema and DTD definitions? We will explain these
differences using an XML document related to employee information as an example.
When defining XML Schema, the content you wish to put into an XML document must first be
summarized. The next step is to create a tree structure.

Content to put into the XML document:


1. The root element is "Employee_Info"
2. As the content for "Employee_Info," "Employee" occurs 0 or more times
3. As content of "Employee," "Name," "Department," "Telephone," and "Email" elements occur
once in respective order
4. "Name," "Department," "Telephone," and "Email" content are text strings
5. "Employee" has an attribute called "Employee_Number"
6. "Employee_Number" content must be int type

This provides us with an understanding of the hierarchical structure of the XML document. Now, we
can provide a schema definition using actual schema definition language.
LIST1 is an example using DTD and providing a schema definition for the content above, while LIST2
is an example using XML Schema to provide a schema definition (employee.xs).
LIST1: Employee Information DTD
<!ELEMENT Employee_Info (Employee)*>
<!ELEMENT Employee (Name, Department, Telephone, Email)>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT Department (#PCDATA)>
<!ELEMENT Telephone (#PCDATA)>
<!ELEMENT Email (#PCDATA)>
<!ATTLIST Employee Employee_Number CDATA #REQUIRED>

LIST2Employee Information XML Schemaemployee.xs


01 <?xml version="1.0"?>
02 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" >
03
04 <xs:element name="Employee_Info" type="EmployeeInfoType" />
05 <xs:complexType name="EmployeeInfoType">
06 <xs:sequence>
07 <xs:element ref="Employee" minOccurs="0" maxOccurs="unbounded" />
08 </xs:sequence>
09 </xs:complexType>
10
11 <xs:element name="Employee" type="EmployeeType" />
12 <xs:complexType name="EmployeeType">
13 <xs:sequence >
14 <xs:element ref="Name" />
15 <xs:element ref="Department" />
16 <xs:element ref="Telephone" />
34

BRJ035

Web Technologies By BRJ

17 <xs:element ref="Email" />


18 </xs:sequence>
19 <xs:attribute name="Employee_Number" type="xs:int" use="required"/>
20 </xs:complexType>
21
22 <xs:element name="Name" type="xs:string" />
23 <xs:element name="Department" type="xs:string" />
24 <xs:element name="Telephone" type="xs:string" />
25 <xs:element name="Email" type="xs:string" />
26
27 </xs:schema>

(Line numbers have been added for reference, and are not necessary in the actual code.)
As you see, the syntax is completely different between the two. For the DTD, a unique syntax is
written, whereas the XML Schema is written in XML format conforming to XML 1.0 syntax. LIST3 is an
example of a valid XML document for the LIST2 XML Schema (employee.xml).

LIST3: Valid XML Document for XML Schema (employee.xml)


<?xml version="1.0"?>
<Employee_Info
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="employee.xs">
<Employee Employee_Number="105">
<Name>Masashi Okamura</Name>
<Department>Design Department</Department>
<Telephone>03-1452-4567</Telephone>
<Email>okamura@xmltr.co.jp</Email>
</Employee>
<Employee Employee_Number="109">
<Name>Aiko Tanaka</Name>
<Department>Sales Department</Department>
<Telephone>03-6459-98764</Telephone>
<Email>tanaka@xmltr.co.jp</Email>
</Employee>
</Employee_Info>
For DTD, a DOCTYPE declaration is used to associate with the XML document; but, in the case of XML
Schema, the specification does not particularly determine anything with respect to the association of
the XML document. Accordingly, the implementation method of the validation tool actually used is
followed. However, under the XML Schema specification, there is a defined method for writing a hint
to associate with the XML document. The following content is inserted into the root element of the
XML document.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="employee.xs"
XML SCHEMA STRUCTURE
From here, using the LIST2 employee.xs file as an example, we will explain the method for writing
XML schema.
XML SCHEMA ROOT ELEMENT
The schema element is used as the root element, and the XML Schema "Namespace" is declared.
Namespace is a specification used to avoid the duplication of attribute and element names defined
under XML, and is normally designated using URL format.
35

BRJ036

Web Technologies By BRJ

Under LIST2, the "xmlns:xs="http://www.w3.org/2001/XMLSchema" section at Line 2 is a


Namespace declaration. The "xs" designation is called the "Namespace Prefix," and can be used with
an element and a child element. Generally, the "xs" prefix is used most often.

ELEMENT DECLARATION
When declaring an element, an ELEMENT keyword is used under DTD; however, under XML Schema,
the element element is used. The declaration method is different depending on whether the element
element has a child element or not. When no child element is present, the element name is designated
with the name attribute, and the data type is designated using the type attribute.

Under DTD, not much more than being able to show an optional text string called #PCDATA as the
element content was possible; however, under XML Schema, a variety of data types can be defined.
Data types can be designated using pre-defined embedded simple type (Note), including string type,
int type and date type shown in a table, as well as ID type and NMTOKEN type that are compatible
with DTD. These can be combined and extended or restricted to create new, unique data types.
Table : Main XML Schema Data Types
General Data Types
Name

Explanation

xs:integer

xs:positiveInteger

Integers (infinite precision)

xs:negativeInteger

Positive integers (infinite precision)

Negative integers (infinite precision)

xs:nonPositiveInteger Negative integers


precision)
xs:nonNegativeInteger Positive integers
precision)

including

including

xs:byte

Integer represented by 8 bits

xs:short

Integer represented by 16 bits

xs:unsignedByte
xs:unsignedShort
xs:int

xs:unsignedInt
xs:long

xs:unsignedLong
xs:decimal
xs:float

xs:double
36

(infinite

(infinite

Integer represented by 8 bits (no symbols)


Integer represented by 16 bits (no symbols)
Integer represented by 32 bits

Integer represented by 32 bits (no symbols)


Integer represented by 64 bits

Integer represented by 64 bits (no symbols)


Decimal number (infinite precision)

Single-precision floating-point number (32bit)


Double-precision floating-point number (64bit)
BRJ037

Web Technologies By BRJ

xs:Boolean
xs:string

Boolean value

Arbitrary text string

Types Representing Dates and Times


Name

Explanation

xs:time

Time of day

xs:date

Date

xs:dateTime
xs:gYear

xs:gYearMonth
xs:gMonth

xs:gMonthDay
xs:gDay

Date and time of day


Year

Year and month


Month

Month and day


Day

DTD-Compatible Types
Name

Explanation

xs:ID

XML 1.0 Specification ID type

xs:IDREFS

XML 1.0 Specification IDREFS type

xs:IDREF

xs:ENTITY

xs:ENTITIES

xs:NOTATION
xs:NMTOKEN

xs:NMTOKENS

XML 1.0 Specification IDREF type

XML 1.0 Specification ENTITY type

XML 1.0 Specification ENTITIES type

XML 1.0 Specification NOTATION type


XML 1.0 Specification NMTOKEN type

XML 1.0 Specification NMTOKENS type

Meanwhile, if the element has a child element, a new data type must first be designated for the
element (Line 11): <xs:element name="Employee" type="EmployeeType" />
This "EmployeeType type" designated by the type attribute is a Complex Data Type. Lines 11 through
20 are Complex Type declarations. In the actual content of the Complex Type, EmployeeType type is
designated with the name attribute of the complexType element, and the Model Group (settings
method for the occurrence order of the child element) is designated in the child element. In the Model
Group, use the sequence element to output occurrences in the order written (equivalent to the "," in
DTD), and use the choice element to output the occurrence of any given element (equivalent to the "|"
in DTD).
Meaning of the Model Group

XML Schema

Output the element in the written order in sequence element


the exact number of occurrences designated
Output any one element in the exact number choice element
of occurrences designated

DTD

For Model Group element declarations, the most common method is to designate the ref attribute of
the element element, referencing the element declared in a separate location (LIST4).
37

BRJ038

Web Technologies By BRJ

LIST4: Element Declaration Reference for a Model Group Element

The element reference syntax is as follows:

ATTRIBUTE DECLARATIONS
When declaring an attribute, the ATTLIST keyword is used under DTD, while the attribute element is
used under XML Schema. The syntax is as shown below. As mentioned previously in connection with
Complex Type declarations, when describing an attribute, the convention is to describe it after the
Complex Type definition content (after the Model Group) (Line 19).
Designations related to Occurrences

XML Schema

DTD

Attribute description is required

required

#REQUIRED

Attribute description may be omitted


Attribute description is prohibited
38

optional

prohibited

BRJ039

#IMPLIED
None

Web Technologies By BRJ

<xs:attribute name="Employee_Number" type="xs:int" use="required"/>


The attribute name is designated using the name attribute and the data type is designated using the
type attribute. The use, default, and fixed attributes can be designated as options. The use attribute is
a designation related to occurrences, and can be used to designate "required" (equivalent of
#REQUIRED in DTD) or "optional" (equivalent to #IMPLIED in DTD). When nothing is written, the
setting is "optional." The default attribute is used to designate initial values, while the fixed attribute is
used to designate a fixed value (equivalent to #FIXED in DTD).
Table : XML Schema and DTD Differences related to Attribute Declarations
DESIGNATING REPEAT COUNT
Under DTD, designating a repeat count was only possible by designating the minimum value as (*) for
0 or more times, or (+) for one or more times. However, under XML Schema, the minOccurs and
maxOccurs attributes can be used to designate detailed repeat counts, such as "from one to three" or
"between three and unlimited." For an unlimited upper limit, set the maxOccurs attribute to
"unbounded." Be sure to remember that if the minOccurs and maxOccurs attributes are omitted, both
default to a value of 1. Repeat count designations can be used within element references, attribute
declarations and within Model Groups.

XML SCHEMAS
XML schema is an XML based alternative to DTD. Which describes the structure of an XML
document.
The XML schema language is also referred as XML Schema Definition (XSD).
The purpose of an XML schema is to define the legal building blocks of an XML document like a
DTD.
An XML schema defines :
elements and attributes that can appear in a document
which elements are child elements, the order of child elements
the number of child elements and whether an element is empty or can include text
data types for elements and attributes
default and fixed values for elements and attributes
XML Schemas are the Successors of DTDs
XML Schemas will be used in most Web applications as a replacement for DTDs because :
XML Schemas are richer and more powerful than DTDs
XML Schemas are extensible to future additions
XML Schemas are written in XML, also support data types and namespaces
XML Schema is W3c recommendation.
As XML Schemas Support Data Types
It is easier to describe allowable document content
It is easier to validate the correctness of data
It is easier to work with data from a database
It is easier to define restrictions on data
It is easier to define data patterns/formats
It is easier to convert data between different data types
39

BRJ040

Web Technologies By BRJ

Using XML schema we can provide the secured data communication between sender and
receiver.
As XML Schemas use XML Syntax
No need to learn a new language
We can use an XML editor to edit Schema files
we can use XML parser to parse Schema files
we can manipulate Schema with the XML DOM
As XML Schemas are extensible we can reuse the schema in other schemas we can provide
reference of multiple schemas in the same document.
Simple XML Document
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Simple DTD Document
<!DOCTYPE note
[<!ELEMENT note (to ,from ,heading ,body)>
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)> ]>

XML Schema Document


<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified>
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Reference to DTD
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM http://www.w3schools.com/dtd/note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
40

BRJ041

Web Technologies By BRJ

Reference to XML Schema


<?xml version="1.0"?>
<note xmlns="http://www.w3schools.com"
xmlns:xsi ="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3schools.com note.xsd">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

XML DOM (Document Object Model)

The DOM is a W3C (World Wide Web Consortium) standard.


The DOM defines a standard for accessing documents like XML and HTML
"The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the content,
structure, and style of a document."
The DOM is separated into 3 different parts / levels:
Core DOM - standard model for any structured document
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
The DOM defines the objects and properties of all document elements, and the methods
(interface) to access them.
The HTML DOM defines the objects and properties of all HTML elements, and the methods
(interface) to access them.
The XML DOM defines the objects and properties of all XML elements, and the methods
(interface) to access them.
The XML DOM is:
A standard object model for XML
A standard programming interface for XML
Platform- and language-independent
A W3C standard.
The XML DOM is a standard for how to get, change, add, or delete
XML elements.
In XML DOM everything in a xml document is treated as a node.
The DOM says:
The entire document is a document node
Every XML element is an element node
The text in the XML elements are text nodes
Every attribute is an attribute node
Comments are comment nodes

DOM Example (books.xml)


<?xml version="1.0" encoding="ISO-8859-1"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
41

BRJ042

Web Technologies By BRJ

<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

The root node in the XML above is named <bookstore>. All other nodes in the document are
contained within <bookstore>, which holds four <book> nodes.
The first <book> node holds four nodes: <title>, <author>, <year>, and <price>,which contains
one text node each, "Everyday Italian", "Giada De Laurentiis","2005", and "30.00".
Text is Always Stored in Text Nodes
A common error in DOM processing is to expect an element node to contain text.
However, the text of an element node is stored in a text node.
In this example: <year>2005</year>, the element node <year>, holds a text node with the
value "2005, 2005" is not the value of the <year> element!
XML DOM views an XML document as a tree structure which is called as a nodetree. All the
nodes in the tree have a relationship with each other.
All nodes can be accessed through the tree. Their contents can be modified or deleted, and new
elements can be created.
The node tree shows the set of nodes, and the connections between them. The tree starts at the
root node and branches out to the text nodes at the lowest level of the tree

42

BRJ043

Web Technologies By BRJ

Parent, Child and Siblings:


The terms parent, child, and sibling are used to describe the relationships. Parent nodes have
children. Children on the same level are called siblings who have the same parent.
In a node-tree, the top node is called the root
Every node, except the root, has exactly one parent node
A node can have any number of children
A leaf is a node with no children
Siblings are nodes with the same parent
Element <book> is parent node to <title>, <author>, <year>, <price> and is child node to root node
element named <bookstore>.
<bookstore>
// element <bookstore> is root
<book category="children">
<title lang="en">Harry Potter</title> //element <title> is first child of <book>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
//element <price> is last child of <book>
</book>
</bookstore>
Presenting XML
Presenting XML
XML documents are presented using Extensible Stylesheet which expresses stylesheets.

XSL stylesheet are not the same as HTML cascading stylesheets. They create a style for a
specific XML element, with XSL a template is created.

XSL basically transforms one data structure to another i.e., XML to HTML.

Example Here is the XSL file for the XML document of Example

This line must be included in the XML document which reference stylesheet
<?xml:stylesheet type = text/xsl href = student.xsl?>

Here goes the XSL file..

<xsl:stylesheet smlns:xsl =uri:xsl.


<xsl:template match=/>
<html>
<body>
<h1> Student Database </h1.
<xsl:for-each select = college>
<xsl:for-each select = studetail>
<xsl:value-of select = regno/>
<xsl:for-each select = name>
<xsl:value-of select = firstname/>
<xsl:value-of select = lastname/>
</xsl:for-each>
<xsl:value-of select=country/@name />
<xsl:value-of select = branch/>
</xsl:for-each>
</xsl:for-each>
</body>
</xsl:template>
</xsl:stylesheet>
43

BRJ044

Web Technologies By BRJ

SAX PARSER
Simple API for XML- SAX
Fast and Efficient
It will Fires Event handlers at Start Tag, Tag Body and End Tag.
e.g: <to> jk </to> respectively.
SAX is Read Only API therefore it cannot be used to Update XML
documents.
It is good for large documents to process as it requires less memory.
It process the document sequentially.
SAX allows us to abort processing at any time.
It is useful to retrieve small amount of information.
<?xml version="1.0" encoding="UTF-8"?>
<parts>
<part> TurboWidget </part>
</parts>
StartDocument( )
StartElement( "parts" )
StartElement( "part" )
Characters( "TurboWidget" )
EndElement( "part" )
EndElement( "parts" )
EndDocument( )

Advantages of SAX:
SAX reduces memory and CPU usage because it only processes one section
of an XML document at a time.
SAX is customizable because when an event is triggered, only the associated
application receives data about the triggering event.
SAX is streamlined, fast, and supports pipelining due to the reason that the
parser can produce output while the document is being parsed.
Drawbacks of SAX:
The SAX parser is unidirectional because It can only parse forwards in
a document.
As it can hold only a portion of the XML document in memory at any
time, it is difficult to add or edit nodes using SAX. If this functionality is
required, then DOM should be considered.
SAX can only work with a fully formed XML document. It cannot be
used to process partial XML documents.
It wont support dynamic access of data in a document.
It is difficult to implement complex searches.
SAX support is not built-in in Microsoft Internet Explorer.

DOM( Document Object Model ) PARSER


The Java binding for DOM provided a tree-based representation of the XML documents allowing random access and modification of the underlying XML data. Not very difficult to
deduce that it would be slower as compared to SAX.
The event-based callback methodology was replaced by an object-oriented in-memory
representation of the XML documents. Though, it differs from one implementation to another if
the entire document or a part of it would be kept in the memory at a particular instant, but the
44

BRJ045

Web Technologies By BRJ

Java developers are kept out of all the hassle and they get the entire tree readily available
whenever they wish.

JAXP - Java API for XML Parsing


The creators and designers of Java realized that the Java developers should not be XML gurus
to use the XML in Java applications.
The first step towards making this possible was the evolution of JAXP, which made it easier to
obtain either a DOM Document or a SAX-compliant parser via a factory class.
This reduced the dependence of Java developers over the numerous vendors supplying the
parsers of either type. Additionally, JAXP made sure that an interchange between the parsers
required minimal code changes.

Differences between DOM and SAX


Main differences between SAX and DOM, which are the two most popular APIs for processing
XML documents in Java, are: Read v/s Read/Write: SAX can be used only for reading XML documents and not for the
manipulation of the underlying XML data whereas DOM can be used for both read and write of
the data in an XML document.
Sequential Access v/s Random Access: SAX can be used only for a sequential processing of
an XML
document whereas DOM can be used for a random processing of XML docs. So what to do if you
want a random access to the underlying XML data while using SAX? You got to store and manage that
information so that you can retrieve it when you need.
Call back v/s Tree: SAX uses call back mechanism and uses event-streams to read chunks of
XML data into the memory in a sequential manner whereas DOM uses a tree representation of
the underlying XML document and facilitates random access/manipulation of the underlying
XML data.
XML-Dev mailing list v/s W3C: SAX was developed by the XML-Dev mailing list whereas
DOM was
developed by W3C (World Wide Web Consortium).
Information Set: SAX doesn't retain all the info of the underlying XML document such as
comments whereas DOM retains almost all the info. New versions of SAX are trying to extend
their coverage of information.

45

BRJ046

Web Technologies By BRJ

JAVA BEANS
UNIT-II
Sno

Contents

Page No

JAVA BEANS
1

Introduction to Java Beans

BDK Introspection

2
4
5
6

Advantages of Java Beans

Developing a simple Bean Using the BDK

10

Using Bean Info Interface.

17

Using Bound properties

Java Beans by BRJ

BRJ047

13

INTRODUCTION TO JAVA BEANS


1) A Java Bean is a software component that has been designed to be reusable in a variety of
different environments.
2) There is no restriction on the capability of a Bean.
3) It may perform a simple function, such as checking the spelling of a document, or a complex
function, such as forecasting the performance of a s t o c k portfolio.
4) A Bean may be visible to an end user.
5) One example of this is a button on a graphical user interface.
6) A Bean may also be invisible to a user.
7) Software to decode a stream of multimedia information in real time is an example of this type
of building block.
8) Finally, a Bean may be designed to work autonomously on a users workstation or to work in
cooperation with a set of other distributed comp on e n t s .
9) Software to generate a pie chart from a set of data points is an example of a Bean that can
execute locally.
10)However, a Bean that provides real-time price information from a stock or commodities
e x c h a n g e would need to work in cooperation with other distributed software to obtain its
data.
11)You will see shortly what specific changes a software developer must make to a class so that it is
usable as a J a v a Bean.
12)However, one of the goals of the Java designers was to make it easy to use this technology

ADVANTAGES OF JAVA BEANS


A software component architecture provides standard mechanisms to deal with software building
blocks. The following list enumerates some of the specific benefits that Java technology provides for a
component developer:
A Bean obtains all the benefits of Javas write-once, run-anywhere paradigm.
The properties, events, and methods of a Bean that are exposed to an application builder tool
can be controlled.
A Bean may be designed to operate correctly in different locales, which makes it useful in
global m a r k e t s .
Auxiliary software can be provided to help a person configure a Bean. This software is only
needed when the design-time parameters for that component are being set. It does not need to
be included in the run-time environment.
The configuration settings of a Bean can be saved in persistent storage and restored at a later
time.
A Bean may register to receive events from other objects and can generate events that are sent
to other objects.

FEATURES OF JAVABEANS
1 ) Compact and Easy: JavaBeans components are simple to create and easy to use.
This is an important goal of the JavaBeans architecture. It doesn't take very much to write a simple
Bean, and such a Bean is lightweight, it doesn't have to carry around a lot of inherited baggage just

Java Beans by BRJ

BRJ048

2)
3)

4)

5)

to support the Beans environment.


Portable: Since JavaBeans components are built purely in Java, they are fully portable to any
platform that supports the Java run-time environment. All platform specifics, as well as support for
JavaBeans, are implemented by the Java virtual machine.
Introspection: Introspection is the process of exposing the properties, methods, and events that
a JavaBeans component supports. This process is used at run-time, as well as by a visual
development tool at design-time. The default behavior of this process allows for the automatic
introspection of any Bean. A low-level reflection mechanism is used to analyze the Bean's class to
determine its methods. Next it applies some simple design patterns to determine the properties
and events that are supported. To take advantage of reflection, you only need to follow a coding
style that matches the design pattern. This is an important feature of JavaBeans. It means that you
don't have to do anything more than code your methods using a simple convention. If you do, your
Beans will automatically support introspection without you having to write any extra code.
Customization: When you are using a visual development tool to assemble components into
applications, you will be presented with some sort of user interface for customizing Bean
attributes. These attributes may affect the way the Bean operates or the way it looks on the screen.
The application tool you use will be able to determine the properties that a Bean supports and build
a property sheet dynamically. This property sheet will contain editors for each of the properties
supported by the Bean, which you can use to customize the Bean to your liking. The Beans class
library comes with a number of property editors for common types such as float, boolean, and
String. If you are using custom classes for properties, you will have to create custom property
editors to associate with them.
Persistence: It is necessary that Beans support a large variety of storage mechanisms. This way,
Beans can participate in the largest number of applications. The simplest way to support
persistence is to take advantage of Java Object Serialization. This is an automatic mechanism for
saving and restoring the state of an object. Java Object Serialization is the best way to make sure
that your Beans are fully portable, because you take advantage of a standard feature supported by
the core Java platform. This, however, is not always desirable. There may be cases where you want
your Bean to use other file formats or mechanisms to save and restore state. In the future,
JavaBeans will support an alternative externalization mechanism that will allow the Bean to have
complete control of its persistence mechanism.

THE BEAN DEVELOPER KIT (BDK)

The Bean Developer Kit (BDK), available from the JavaSoft site, is a simple example of a tool that
enables you to create, configure, and connect a set of Beans. There is also a set of sample Beans with
their source code
Installing the BDK
The JDK must be installed on your machine for the BDK to work. Confirm that the JDK tools are
accessible from your environment.
Starting the BDK
To start the BDK, follow these steps:
1. Change to the directory c:\\bdk\\beanbox.
2. Execute the batch file called run.bat. This causes the BDK to display the three windows shown
below . ToolBox lists all of the different Beans that have been included with the BDK. Bean Box provides
an area to lay out and connect the Beans selected from the Toolbox.
Properties provide the ability to configure a selected Bean.
Java Beans by BRJ

BRJ049

Using the BDK


This section describes how to create an application by using some of the Beans provided with the
BDK. First, the Molecule Bean displays a three-dimensional view of a molecule.
It may be configured to present one of the following molecules: hyaluronic acid, benzene,
cyclohexane, ethane, or water.
This component also has methods that allow the molecule to be rotated in space along its X or Y
axis.
Second, the OurButton Bean provides a push-button functionality.
We will have one button labeled "Rotate X" to rotate the molecule along its X axis and another
button labeled "Rotate Y to rotate the molecule along its Y axis.
Figure: The Molecule and OurButton Beans

Create and Configure an Instance of the Molecule Bean


Follow these steps to create and configure an instance of the Molecule Bean:
1. Position the cursor on the ToolBox entry labeled Molecule and click the left mouse
button. You should see the cursor change to a cross.
2. Move the cursor to the BeanBox display area and click the left mouse button in
Approximately the area where you wish the Bean to be displayed.
You should see a rectangular region appear that contains a 3-D display of a molecule.
This area is surrounded by a hatched border, indicating that it is currently selected.
3. You can reposition the Molecule Bean by positioning the cursor over one of the
Hatched borders and dragging the Bean.
Java Beans by BRJ

BRJ050

4. You can change the molecule that is displayed by changing the selection in the Properties
window. Notice that the Bean display changes immediately when you change the selected
molecule.
5. Go to the menu bar of the BeanBox and select Edit | Events | action |actionPerformed. You should
now see a line extending from the button to the cursor.
Notice that one end of the line moves as the cursor moves.
However, the other end of the line remains fixed at the button.
6. Move the cursor so that it is inside the Molecule Bean display area, and click the left mouse
button. You should see the Event Target Dialog dialog box.
7. The dialog box allows you to choose a method that should be invoked when this button is clicked.
Select the entry labeled "rotateOnX" and click the OK button.
You should see a message box appear very briefly, stating that the tool is
"Generating and compiling adaptor class.
Test the application. Each time you press the button, the molecule should move a few degrees around
one of its axes.
Now create another instance of the OurButton Bean. Label it "Rotate Y" and map its action event to
the "rotateY" method of the Molecule Bean.
The steps to do this are very similar to those just described for the button labeled "Rotate X".
Test the application by clicking these buttons and observing how the molecule moves.
JAR Files
Before developing your own Bean, it is necessary for you to understand JAR (Java Archive) files,
because tools such as the BDK expect Beans to be packaged within JAR files.
A JAR file allows you to efficiently deploy a set of classes and their associated resources.
For example, a developer may build a multimedia application that uses various sound and
image files.
A set of Beans can control how and when this information is presented. All of these pieces can be
placed into one JAR file.
Also, the elements in a JAR file are compressed, which makes downloading a JAR file much faster
than separately downloading several uncompressed files.
Manifest Files
A developer must provide a manifest file to indicate which of the components in a JAR file are
Java Beans.
An example of a manifest file is provided in the following listing. It defines a JAR file that contains
four .gif files and one .class file. The last entry is a Bean.
Name: sunw/demo/slides/slide0.gif
Name: sunw/demo/slides/slide1.gif
Name: sunw/demo/slides/slide2.gif
Name: sunw/demo/slides/slide3.gif
Name: sunw/demo/slides/Slides.class
Java-Bean: True
A manifest file may reference several .class files. If a .class file is a Java Bean, its entry must be
immediately followed by the line "Java-Bean: True".
The JAR Utility
A utility is used to generate a JAR file. Its syntax is shown here:
jar options files
jar -cfm Xyz.jar Yxz.mf *.class *.gif
Java Beans by BRJ

BRJ051

Creating a JAR File


The following command creates a JAR file named Xyz.jar that contains all of the .class and .gif
files in the current directory.
OPTION

DESCRIPTION

A new archive is to be created.

Change directories during command execution.

The first element in the file list is the name of the archive that is to be

The second element in the file list is the name of the external manifest file.

Manifest file not created.

The archive contents should be tabulated.

Update existing JAR file.

Verbose output should be provided by the utility as it executes.

Files are to be extracted from the archive. (If there is only one file, that is

created or accessed.

the name of the archive, and all files in it are extracted. Otherwise, the first
element in the file list is the name of the archive, and the remaining

elements in the list are the files that should be extracted from the archive.)
jar cf Xyz.jar *.class *.gif
If a manifest file such as Yxz.mf is available,
it can be used with the following command:
jar cfm Xyz.jar Yxz.mf *.class *.gif
Tabulating the Contents of a JAR File
The following command lists the contents of Xyz.jar:

jar tf Xyz.jar
Extracting Files from a JAR File
The following command extracts the contents of Xyz.jar and places those files in the current
directory:
jar xf Xyz.jar

Updating an Existing JAR File


The following command adds the file file1.class to Xyz.jar:
jar -uf Xyz.jar file1.class

Recursing Directories
The following command adds all files below
directoryX to Xyz.jar:
jar -uf Xyz.jar -C directoryX *
Java Beans by BRJ

BRJ052

BDK INTROSPECTION

Introspection is the process of analyzing a Bean to determine its capabilities.


This is an essential feature of the Java Beans API, because it allows an application builder tool to
present information about a component to a software designer.
Without introspection, the Java Beans technology could not operate.
There are two ways in which the developer of a Bean can indicate which of its properties, events,
and methods should be exposed by an application builder tool.
1. Simple naming conventions are used.
These allow the introspection mechanisms to infer information about a Bean.
2. An additional class is provided that explicitly supplies this information.

1) Simple Naming Conventions

The following sections indicate the design patterns for properties and events that enable the
functionality of a Bean to be determined.
Introspection is the process of exposing the properties, methods, and events that a JavaBeans
component supports.
This process is used at run-time, as well as by a visual development tool at design- time.
The default behavior of this process allows for the automatic introspection of any Bean.
A low-level reflection mechanism is used to analyze the Bean's class to determine its methods.
Next it applies some simple design patterns to determine the properties and events that are
supported.
To take advantage of reflection, you only need to follow a coding style that matches the design
pattern.
This is an important feature of JavaBeans.
It means that you don't have to do anything more than code your methods using a simple
convention.
If you do, your Beans will automatically support introspection without you having to write any
extra code.

Design Patterns for Properties


A property is a subset of a Beans state.
The values assigned to the properties determine the behavior and
component.
This section discusses three types of properties:
1) simple,
2) Boolean,
3) Indexed.
1) Simple Properties
A simple property has a single value.
It can be identified by the following design patterns

appearance of that

public T getN( );
public void setN(T arg);

Where N is the name of the property and T is its type

A read/write property has both of these methods to access its values.


A read-only property has only a get method.
A write-only property has only a set method.
The following listing shows a class that has three read/write simple properties:
Java Beans by BRJ

BRJ053

public class Box


{
private double depth, height, width;
public double getDepth( )
{
return depth;
}
public void setDepth(doubled)
{
depth = d;
}
public double getHeight()
{
return height;
}
public void setHeight(double h)
{
height = h;
}
public double getWidth()
{
return width;
}
public void setWidth(double )
{
width = w;
}
}

2) Boolean Properties
A Boolean property has a value of true or false.
It can be identified by the following design patterns,
public boolean isN( );
public boolean getN( );
public void setN(boolean value);

Where N is the name of the property.

Either the first or second pattern can be used to retrieve the value of a Boolean property.
However, if a class has both of these methods, the first pattern is used.
The following listing shows a class that has one
Boolean property:
public class Line
{
private boolean dotted = false; public boolean isDotted( )
{
return dotted;
}
public void setDotted(boolean dotted)
{
this.dotted = dotted;
}
}

Java Beans by BRJ

BRJ054

3) Indexed Properties
An indexed property consists of multiple values.
It can be identified by the following design patterns,
public T getN(int index);
public void setN(int index, T value);
public T[ ] getN( );
public void setN(T values[ ]);

Where N is the name of the property and T is its type.

The following listing shows a class that has one read/write indexed property:
public class PieChart
{
private double data[ ];
public double getData(int index)
{
return data[index];
}
public void setData(int index, double value)
{
data[index] = value;
}
public double[ ] getData( )
{
return data;
}
public void setData(double[ ] values)
{
data = new double[values.length];
System.arraycopy(values, 0, data, 0, values.length);
}
}

Design Patterns for Events


Beans use the delegation event model that was discussed earlier in this book.
Beans can generate events and send them to other objects.
These can be identified by the following design patterns,
public void addTListener(TListener eventListener);
public void addTListener(TListener eventListener) throws TooManyListeners;
public void removeTListener(TListener eventListener);

Where T is the type of the event.

These methods are used by event listeners to register an interest in events of a specific type.
The first pattern indicates that a Bean can multicast an event to multiple listeners.
The second pattern indicates that a Bean can uncast an event to only one listener.
The third pattern is used by a listener when it no lon ge r wishes to receive a specific type of
event notification from a Bean.
The following listing outlines a class that notifies other objects when a temperature value moves
outside a specific range. The two methods indicated here allow other objects that implement the
TemperatureListener interface to r e c e i v e notifications when this occurs.
Java Beans by BRJ

BRJ055

public class Thermometer


{
public void addTemperatureListener(TemperatureListener tl)
{
...
}
public void removeTemperatureListener(TemperatureListener tl)
{
...
}
}

Design Patterns for Methods


JavaBean properties are accessed through two methods in the JavaBeans implementation class:
Method

Description

getPropertyName() For example, if property name is firstName, your method


name would be getFirstName() to read that property.
This method is called accessor.
setPropertyName()

and a

For example, if property name is firstName, your method


name would be setFirstName() to write that property.
This method is called mutator.

A read-only attribute will have only a getPropertyName() method,


write-only attribute will have only a setPropertyName() method.
Design patterns are not used for naming nonproperty methods.
The introspection mechanism finds all of t h e public methods of a Bean.
Protected and private methods are not presented.

2) An Additional Class Implements the BeanInfo Interface

design patterns were used to determine the information that was provided to a Bean user.
This section describes how a developer can use the BeanInfo interface to explicitly control this
process.
This interface defines several methods, including these:
PropertyDescriptor[ ] getPropertyDescriptors( )
EventSetDescriptor[ ] getEventSetDescriptors( )
MethodDescriptor[ ] getMethodDescriptors( )

They return arrays of objects that provide information about the properties, events, and methods
of a Bean.
By implementing these methods, a developer can designate exactly what is presented to a user.
SimpleBeanInfo is a class that provides default implementations of the BeanInfo interface,
including the three methods just shown

DEVELOPING A SIMPLE BEAN USING THE BDK

Our new component is called the Colors Bean. It appears as either a rectangle or ellipse that
is filled with a color.
A color is chosen at random when the Bean begins execution.
A public method can be invoked to change it. Each time the mouse is clicked on the Bean,
another random color is chosen.

Java Beans by BRJ

BRJ056

10

There is one boolean read/write property that determines the shape.


The BDK is used to lay out an application with one instance of the Colors Bean and one instance
of the OurButton Bean. The button is labeled "Change." Each time it is pressed, the color
changes.

CREATE A NEW BEAN

Here are the steps that you must follow to create a new Bean:
1. Create a directory for the new Bean.
2. Create the Java source file(s).
3. Compile the source file(s).
4. Create a manifest file.
5. Generate a JAR file.
6. Start the BDK.
7. Test.
STEP: 1 Create a Directory for the New Bean
You need to make a directory for the Bean.
c:\\bdk\\demo\\sunw\\demo\\colors.
Then change to that directory.

STEP: 2 Create the Source File for the New Bean


It is located in the file Colors.java.
This file must be located in a subdirectory named sunw\\demo\\colors relative to the
CLASSPATH environment variable.
// A simple Bean.
package sunw.demo.colors;
import java.awt.*;
import java.awt.event.*;
public class Colors extends Canvas
{
transient private Color color;
private boolean rectangular;
public Colors()
{
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me)
{ change(); }});
rectangular = false;
setSize(200, 100);
change();
}
public boolean getRectangular()
{
return rectangular;
}
public void setRectangular(boolean flag)
{
this.rectangular = flag;
repaint();
}
public void change()
{
color = randomColor();
repaint();
}

Java Beans by BRJ

BRJ057

11

private Color randomColor()


{
int r = (int)(255*Math.random());
int g = (int)(255*Math.random());
int b = (int)(255*Math.random());
return new Color(r, g, b);
}
public void paint(Graphics g)
{
Dimension d = getSize();
int h = d.height;
int w = d.width;
g.setColor(color);
if(rectangular)
{
g.fillRect(0, 0, w-1, h-1);
}
else
{
g.fillOval(0, 0, w-1, h-1);
}
}
}

STEP: 3 Compile the Source Code for the New Bean


javac Colors.java.

STEP: 4 Create a Manifest File


First, switch to the c:\\bdk\\demo directory. This is the directory in which the manifest files
for the BDK demos are located.
Put the source code for your manifest file in the file colors.mft. It is shown here:
Name: sunw/demo/colors/Colors.class
Java-Bean: True
This file indicates that there is one .class file in the JAR file and that it is a Java Bean.
Notice that the Colors.class file is in the package sunw.demo.colors and in the subdirectory
sunw\\demo\\colors relative to the current directory.
STEP: 5 Generate a JAR File
Beans are included in the ToolBox window of the BDK only if they are in JAR files in the directory
c:\\bdk\\jars.
These files are generated with the jar utility. Enter the following:
jar cfm ..\\jars\\colors.jar colors.mft
sunw\\demo\\colors\\*.class
This command creates the file colors.jar and places it in the directory c:\\bdk\\jars.

STEP: 6 Start the BDK


Change to the directory c:\\bdk\\beanbox and type run. This causes the BDK to start
Create an Instance of the Colors Bean
create an instance of the Colors Bean in the BeanBox window. Test your new component by
pressing the mouse anywhere within its borders. Its color Immediately changes.
Use the Properties window to change the rectangular property from false to true. Its shape
immediately changes.
Java Beans by BRJ

BRJ058

12

STEP: 7 Test
Create and Configure an Instance of the OurButton Bean
Create an instance of the OurButton Bean in the BeanBox window. Then follow these steps:
1. Go to the Properties window and change the label of the Bean to "Change". You should see that the
button appearance changes immediately when this property is changed.
2. Go to the menu bar of the BeanBox and select Edit | Events | action | actionPerformed.
3. Move the cursor so that it is inside the Colors Bean display area, and click the left mouse button. You
should see the Event Target Dialog dialog box.
4. The dialog box allows you to choose a method that should be invoked when this button is clicked.
Select the entry labeled "change" and click the OK button. You should see a message box appear very
briefly, stating that the tool is "Generating and compiling adaptor class.
5. Click on the button. You should see the color change.

USING BOUND PROPERTIES

A property with listeners" is called a bound property.


Sometimes when a Bean property changes, another object may want to be notified of the change,
and react to the change. Whenever a bound property changes, notification of the change is sent to
interested listeners
A Bean containing a bound property must maintain a list of property change listeners, and alert
those listeners when the bound property changes.
The convenience class PropertyChangeSupport implements methods that add and remove
PropertyChangeListener objects from a list, and fires PropertyChangeEvent objects at those
listeners when the bound property changes. Your Beans can inherit from this class, or use it as an
inner class.
An object that wants to listen for property changes must be able to add and remove itself from
the listener list on the Bean containing the bound property, and respond to the event notification
method that signals a property change. By implementing the PropertyChangeListener interface
the listener can be added to the list maintained by the bound property Bean, and because it
implements the PropertyChangeListener.propertyChange method, the listener can respond to
property change notifications.
Implementing Bound Property Support Within a Bean
To implement a bound property, take the following steps:
Import the java.beans package. This gives you access to the PropertyChangeSupport
class.
Instantiate a PropertyChangeSupport object:
private PropertyChangeSupport changes = new PropertyChangeSupport(this);

This object maintains the property change listener list and fires property change events. You can
also make your class a PropertyChangeSupport subclass.

Implement methods to maintain the property change listener list. Since


PropertyChangeSupport implements these methods, you merely wrap calls to the
property-change support object's methods:

Java Beans by BRJ

BRJ059

13

public void addPropertyChangeListener( PropertyChangeListener l)


{
changes.addPropertyChangeListener(l);
}
public void removePropertyChangeListener( PropertyChangeListener l)
{
changes.removePropertyChangeListener(l);
}

Modify a property's setter method to fire a property change event when the property is
changed. OurButton's setLabel method looks like this:
public void setLabel(String newLabel)
{
String oldLabel = label;
label = newLabel;
sizeToFit();
changes.firePropertyChange("label", oldLabel, newLabel);
}

Note that setLabel stores the old label value, because both the old and new labels must be passed
to firePropertyChange.
public void firePropertyChange(String propertyName, Object oldValue,Object newValue)
The firePropertyChange method bundles its parameters into a PropertyChangeEvent object,
and calls propertyChange(PropertyChangeEvent pce) on each registered listener.
The old and new values are treated as Object values.
Implementing Bound Property Listeners
So to make your class able to listen and respond to property change events, you must:
1. Implement the PropertyChangeListener interface.
public class MyClass implements java.beans.PropertyChangeListener
java.io.Serializable

2. Implement the propertyChange method in the listener.


This method needs to contain the code that handles what you need to do when the listener
receives property change event.
Very often, for example, this is a call to a setter method in the listener class: a property
change in the source Bean propagates a change to a property in a listener Bean.
3. To register interest in receiving notification about a Bean property change, the listener
Bean calls the listener registration method on the source Bean.
For example: button.addPropertyChangeListener(aButtonListener);

EXAMPLE: A Sample Bean with Bound Properties


The TickTock Bean is supplied with the BDK.
It generates a property change event every N seconds.
N is a property of the Bean that can be changed via the Properties window of the BDK.
The next example builds an application that uses the TickTock Bean to automatically
control the Colors Bean.
STEPS:
Start the BDK and create an instance of the Colors Bean in the BeanBox window.
Create an instance of the TickTock Bean.
The Properties window should show one property for this component. It is "Interval" and its
initial value is 5.
This represents the number of seconds that elapse between property change events generated by
the TickTock Bean.
Change the value to 1.
Java Beans by BRJ

BRJ060

14

Now you need to map events generated by the TickTock Bean into method calls on the Colors
Bean.
Follow these steps:
1. Go to the menu bar of the BeanBox and select Edit | Events | propertyChange |
propertyChange.
You should now see a line extending from the button to the cursor.
2. Move the cursor so that it is inside the Colors Bean display area, and click the left
mouse button.
You should see the Event Target Dialog dialog box.

3. The dialog box allows you to choose a method that should be invoked when this event
occurs. Select the entry labeled "change" and click the OK button. You should see a
message box appear very briefly, stating that the tool is "Generating and compiling
adaptor class."

4. You should now see the color of your component change every second

Java Beans by BRJ

BRJ061

15

Constrained Properties //constrained properties are optional these properties are not in our syllabus
A Bean property is constrained when any change to that property can be vetoed. Usually an
outside object exercises the right to veto, but the Bean itself can also veto a property change.
There are three parts to constrained property implementations:
A source Bean containing one or more constrained properties.
Listener objects that implement the VetoableChangeListener interface. This object accepts
or rejects proposed changes to a constrained property in the source Bean.
A PropertyChangeEvent object containing the property name, and its old and new values.
This is the same class used for bound properties.
Implementing Constrained Property Support Within a Bean
A Bean containing constrained properties must
Allow VetoableChangeListener objects to register and unregister their interest in
receiving notification that a property change is proposed.
Fire property change events at those interested listeners when a property change is
proposed. The event should be fired before the actual property change takes place. This
gives each listener a chance to veto the proposed change. The PropertyChangeEvent is
fired by a call to each listeners vetoableChange method.
If a listener vetoes, then make sure that any other listeners can revert to the old value.
This means reissuing the vetoableChange call to all the listeners, with a
PropertyChangeEvent containing the old value.
The VetoableChangeSupport utility class is provided to implement these capabilities. This class
implements methods to add and remove VetoableChangeListener objects to a listener list, and a
method that fires property change events at each listener in that list when a property change is
proposed. This method will also catch any vetoes, and resend the property change event with the
original property value. Your Bean can either inherit from VetoableChangeSupport, or use an
instance of it.
Note that, in general, constrained properties should also be bound properties. When a
constrained property change does occur, a PropertyChangeEvent can be sent via
PropertyChangeListener.propertyChange to signal all VetoableChangeListener Beans that the
change has taken effect. This lets all the vetoable change listeners know that the change was not
vetoed by any listener.
Here's the steps to implement constrained properties in your Beans:
1) Import the java.beans package. This gives you access to the VetoableChangeSupport class.
2) Instantiate a VetoableChangeSupport object within your Bean:
private VetoableChangeSupport vetos = new VetoableChangeSupport(this);
VetoableChangeSupport manages a list of VetoableChangeListener objects, and fires
property change events at each object in the list when a change occurs to a constrained property.
3) Implement methods to maintain the property change listener list.
public void addVetoableChangeListener( VetoableChangeListener l)
{
vetos.addVetoableChangeListener(l);
}
public void removeVetoableChangeListener( VetoableChangeListener l)
{
vetos.removeVetoableChangeListener(l);
}

4) Write a property's setter method to fire a property change event when the property is
changed.
This includes adding a throws clause to the setter method's signature.
JellyBean's setPriceInCents method looks like this:

Java Beans by BRJ

BRJ062

16

public void setPriceInCents(int newPriceInCents) throws PropertyVetoException


{
int oldPriceInCents = ourPriceInCents;
vetos.fireVetoableChange("priceInCents", new Integer(oldPriceInCents), new Integer(newPriceInCents));
// No-one vetoed, so go ahead and make the change.
ourPriceInCents = newPriceInCents; changes.firePropertyChange("priceInCents", new Integer(oldPriceInCents), new
Integer(newPriceInCents));
}

Implementing Constrained Property Listeners


So to make your class able to listen and respond to property change events, your listener class
must:
Implement the VetoableChangeListener interface.
Implement the vetoableChange method. This is the method that will be called by the source
Bean on each object in the listener list (maintained by the VetoableChangeSupport object). This is
also the method that exercises veto power. A property change is vetoed by throwing the
PropertyVetoException.

USING THE BEANINFO INTERFACE

This section describes how a developer can use the BeanInfo interface to explicitly control this
process.
This interface defines several methods, including these:
PropertyDescriptor[ ] getPropertyDescriptors( )
EventSetDescriptor[ ] getEventSetDescriptors( )
MethodDescriptor[ ] getMethodDescriptors( )
They return arrays of objects that provide information about the properties, events, and methods
of a Bean.
By implementing these methods, a developer can designate exactly what is presented to a user.
// A Bean information class.

package sunw.demo.colors;
import java.beans.*;
public class ColorsBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor rectangular = new
PropertyDescriptor("rectangular", Colors.class);
PropertyDescriptor pd[] = {rectangular};
return pd;
}
catch(Exception e) {
}
return null;
}
}

You must compile this file from the BDK\\demo directory or set CLASSPATH so that it includes
c:\\bdk\\demo. If you don't, the compiler won't find the Colors.class file properly.
After this file is successfully compiled, the colors.mft file can be updated, as shown here:
Name: sunw/demo/colors/ColorsBeanInfo.class
Name: sunw/demo/colors/Colors.class
Java-Bean: True
Use the JAR tool to create a new colors.jar file. Restart the BDK and create an instance of the
Colors Bean in the BeanBox.
Java Beans by BRJ

BRJ063

17

Persistence
Persistence is the ability to save a Bean to nonvolatile storage and retrieve it at a later time.
Let us first see how the BDK allows you to save a set of Beans that have been configured and
connected together to form an application. Recall our previous example involving both the
Colors and TickTock Beans.
The rectangular property of the Colors Bean was changed to true, and the interval property of
the TickTock Bean was changed to one second.
To save the application, go to the menu bar of the BeanBox and select File | Save.
A dialog box should appear, allowing you to specify the name of a file to which the Beans and
their configuration parameters should be saved. Supply a filename and click the OK button on
that dialog box. Exit from the BDK.
Start the BDK again. To restore the application, go to the menu bar of the BeanBox and select File
| Load. A dialog box should appear, allowing you to specify the name of the file from which an
application should be restored.
Supply the name of the file in which the application was saved, and click the OK button. Your
application should now be functioning.
Confirm that the rectangular property of the Colors Bean is true and that the interval property
for the TickTock Bean is equal to one second.
The object serialization capabilities provided by the Java class libraries are used to provide
persistence for Beans.
If a Bean inherits directly or indirectly from java.awt.Component, it is automatically
serializable, because that class implements the java.io.Serializable interface.
If a Bean does not inherit an implementation of the Serializable interface, you must provide this
yourself. Otherwise, containers cannot save the configuration of your component.
The transient keyword can be used to designate data members of a Bean that should not be
serialized. The color variable of the Colors class is an example of such an item.

Java Beans by BRJ

BRJ064

18

SWINGS
(UNIT-III)

SNO. CONTENTS

PAGE NO.

SWINGS
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.

Introduction to Java Swings

Icons

JApplet

Labels

Buttons

Checkboxes

Text Boxes

Combo Boxes

Tabbed Panes

11

Scroll Panes

12

Trees

14

Tables.

13

1 |B R J

BRJ065
000001

Introduction to swing

Swing is a set of classes that provides more powerful and flexible components than are possible with
the AWT.
Swing provides a set of "lightweight" (all-Java language) components that, to the maximum degree
possible, work the same on all platforms.
The term lightweight is used to describe such elements. The Swing component classes that are used are
shown here:

Class

AbstractButton
ButtonGroup
ImageIcon
JApplet
JButton
JCheckBox
JComboBox
JLabel
JRadioButton
JScrollPane
JTabbedPane
JTable
JTextField
JTree

Description

Abstract super class for Swing buttons.


Encapsulates a mutually exclusive set of buttons.
Encapsulates an icon.
The Swing version of Applet.
The Swing push button class.
The Swing check box class.
Encapsulates a combo box (an combination of a drop-down list and text
field).
The Swing version of a label.
The Swing version of a radio button.
Encapsulates a scrollable window.
Encapsulates a tabbed window.
Encapsulates a table-based control.
The Swing version of a text field.
Encapsulates a tree-based control.

Advantages of Swing Component


o
o

o
o
o
o
o

In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies
several exciting additions, including tabbed panes, scroll panes, trees, and tables.
Components such as buttons have more capabilities in Swing. For example, a button may have
both an image and a text string associated with it. Also, the image can be changed as the state of
the button changes.
Swing components are not implemented by platform-specific code. Instead, they are written
entirely in Java and, therefore, are platform-independent.
You can easily add or change the borders drawn around most Swing components. For example,
it's easy to put a box around the outside of a container or label.
You can easily change the behavior or appearance of a Swing component by either invoking
methods on it or creating a subclass of it.
Swing components don't have to be rectangular. Buttons, for example, can be round.
Assistive technologies such as screen readers can easily get information from Swing
components. For example, a tool can easily get the text that's displayed on a button or label.

Difference between AWT and Swing Components

The biggest difference between the AWT components and Swing components is that the Swing
components are implemented with absolutely no native code. Since Swing components aren't restricted
to the least common denominator -- the features that are present on every platform -- they can have
more functionality than AWT components.
Swing lets you specify which look and feel your program's GUI uses. By contrast, AWT components
always have the look and feel of the native platform.

2 |B R J

BRJ066
000002

Major difference between swing and AWT components:

AWT

SWING

Heavy weight
Native component
Native look and feel
Does not have complex component

Light weight
Pure java Component
Better look and feel
Has additional components like JTree, JTable,
JProgressBar, JSlider, etc
JApplet can have menu.
JList does not support scrolling but this can be done
using scrollPane
While adding components on Frame or window, they
have to be added on its conetent pane.
Has slidePane or TabbedPane
MDI can be achived using InternalFrame Object
Menu item can have images or radio buttons or
checkboxes.
All swing components have JMV
Default layout is BorderLayout.

Applet can not have menu


List has scrollbar

Components can be added directly on the Frame


or window
Does not have slidePane or TabbedPane
Does not support MDI window
Menu item cannot have images or radio buttons
or checkboxes.
They do not have JMV(Java Model Viewport)
Default layout is flowLayout

JApplet

Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must be
subclasses of JApplet.
JApplet are specialized components that provide a place for other Swing components to paint
themselves.
JApplet supports various "panes," such as the content pane, the glass pane, and the root pane.
When adding a component to an instance of JApplet, do not invoke the add() method of the applet.
Instead, call add() for the content pane of the JApplet object.
The content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form is shown
here:
void add(comp)
Here, comp is the component to be added to the content pane.
Example:-

// JApplet Example Code


import java.awt.*;
import javax.swing.*;
public class JAppletExample extends JApplet
{
public void init()
{
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));
content.add(new JButton("Button 3"));
}
}

3 |B R J

BRJ067
000003

Icons and Labels


Icons

In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image.
Two of its constructors are shown here:
1. ImageIcon(String filename):- Creates an ImageIcon from the specified file.
ImageIcon(URL url):- Creates an ImageIcon from the specified URL.

The ImageIcon class implements the Icon interface that declares the methods shown here:
Method
1. int getIconHeight( )- Returns the height of the icon in pixels.
2. int getIconWidth( )- Returns the width of the icon in pixels.
3. void paintIcon(Component comp,Graphics g,int x, int y)- Paints the icon at position x, y on the
graphics context g. Additional information about the paint operation can be provided in comp.

Labels

Swing labels are instances of the JLabel class, which extends JComponent.
Labels can display text and/or an icon.
Some of its constructors are shown here:
1. JLabel(Icon i):- Creates a JLabel instance with the specified image.
2. JLabel(String s):- Creates a JLabel instance with the specified text.
3. JLabel(String s, Icon i, int align):- Creates a JLabel instance with the specified text, image, and
horizontal alignment. The align argument is either LEFT, RIGHT, or CENTER. These constants
are defined in the SwingConstants interface, along with several others used by the Swing
classes.
The icon and text associated with the label can be read and written by the following methods:
1. Icon getIcon( ):- Returns the graphic image (glyph, icon) that the label displays.
2. String getText( ):- Returns the text string that the label displays.
3. void setIcon(Icon i):- Defines the icon this component will display.
4. void setText(String s):- Defines the single line of text this component will display.

Example:
The following example illustrates how to create and display a label containing both an icon and a string.
The applet begins by getting its content pane. Next, an ImageIcon object is created for the file
france.gif. This is used as the second argument to the JLabel constructor. The first and last arguments
for the JLabel constructor are the label text and the alignment. Finally, the label is added to the content
pane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet
{
public void init()
{
// Get content pane
Container contentPane = getContentPane();
// Create an icon
ImageIcon ii = new ImageIcon("france.gif");
// Create a label
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add label to the content pane
contentPane.add(jl);
}
}

4 |B R J

BRJ068
000004

Buttons

Swing buttons provide features that are not found in the Button class defined by the AWT.
For example, you can associate an icon with a Swing button. Swing buttons are subclasses of the
AbstractButton class, which extends JComponent. AbstractButton contains many methods that allow
you to control the behavior of buttons, check boxes, and radio buttons.
For example, you can define different icons that are displayed for the component when it is disabled,
pressed, or selected. Another icon can be used as a rollover icon, which is displayed when the mouse is
positioned over that component.
The following are the methods that control this behavior:
1. void setDisabledIcon(Icon di):-Sets the disabled icon for the button.
2. void setPressedIcon(Icon pi):- Sets the pressed icon for the button.
3. void setSelectedIcon(Icon si):- Sets the selected icon for the button.
4. void setRolloverIcon(Icon ri):- Sets the rollover icon for the button
The text associated with a button can be read and written via the following methods:
1. String getText( ):- Returns the button's text.
2. void setText(String s):- Sets the button's text.
Concrete subclasses of AbstractButton generate action events when they are pressed. Listeners
register and unregistered for these events via the methods shown here:
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
Here, al is the action listener.

The JButton Class

The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both
to be associated with the push button.
Some of its constructors are shown here:
1. JButton(Icon i):- Creates a button with an icon.
2. JButton(String s):- Creates a button with text.
3. JButton(String s, Icon i):- Creates a button with initial text and an icon.
Example:-The following example displays four push buttons. First button displays only text and other
three buttons display text along with the icon.

5 |B R J

import java.awt.*;
import javax.swing.*;
public class JButtons extends JFrame
{
public static void main(String[] args)
{
new JButtons();
}
public JButtons()
{
super("Using JButton");
//WindowUtilities.setNativeLookAndFeel();
//addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton button1 = new JButton("Java");
content.add(button1);
ImageIcon cup = new ImageIcon("iso.gif");
JButton button2 = new JButton(cup);
content.add(button2);
JButton button3 = new JButton("Java", cup);
content.add(button3);
JButton button4 = new JButton("Java", cup);
button4.setHorizontalTextPosition
(SwingConstants.LEFT);
content.add(button4);
pack();
setVisible(true);
}
}

BRJ069
000005

Another Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JButtonDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends JApplet
implements ActionListener {
JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add buttons to content pane
ImageIcon france = new ImageIcon("france.gif");
JButton jb = new JButton(france);
jb.setActionCommand("France");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon germany = new ImageIcon("germany.gif");
jb = new JButton(germany);
jb.setActionCommand("Germany");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon italy = new ImageIcon("italy.gif");
jb = new JButton(italy);
jb.setActionCommand("Italy");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon japan = new ImageIcon("japan.gif");
jb = new JButton(japan);
jb.setActionCommand("Japan");
jb.addActionListener(this);
contentPane.add(jb);
// Add text field to content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void actionPerformed(ActionEvent ae)
{
jtf.setText(ae.getActionCommand());
}
}

Check Boxes

6 |B R J

The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of
AbstractButton.
This is an implementation of a check box, which is an item that can be selected or deselected, and which
displays its state to the user.
Some of its constructors are shown here:
1. JCheckBox(Icon i):- Creates an initially unselected check box with an icon.
2. JCheckBox(Icon i, boolean state):- Creates a check box with an icon and specifies whether or
not it is initially selected.
3. JCheckBox(String s):- Creates an initially unselected check box with text.
4. JCheckBox(String s, boolean state):- Creates a check box with text and specifies whether or
not it is initially selected.
5. JCheckBox(String s, Icon i):- Creates an initially unselected check box with the specified text
and icon.
6. JCheckBox(String s, Icon i, boolean state):- Creates a check box with text and icon, and
specifies whether or not it is initially selected.
The state of the check box can be changed via the following method:

BRJ070
000006

1. void setSelected(boolean state):- Sets the state of the button. Here, state is true if the check
box should be checked.

Example:
The following example illustrates how to create an applet that displays four check boxes and a text field.
When a check box is pressed, its text is displayed in the text field. When a check box is selected or
deselected, an item event is generated. This is handled by itemStateChanged( ). Inside
itemStateChanged( ), the getItem( ) method gets the JCheckBox object that generated the event. The
getText( ) method gets the text for that check box and uses it to set the text inside the text field.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo" width=400 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Create icons
ImageIcon normal = new ImageIcon("normal.gif");
ImageIcon rollover = new ImageIcon("rollover.gif");
ImageIcon selected = new ImageIcon("selected.gif");
// Add check boxes to the content pane
JCheckBox cb = new JCheckBox("C", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("C++", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Java", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
// Add text field to the content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}

Text Fields

7 |B R J

The Swing text field is encapsulated by the JTextComponent class, which extends JComponent.
It provides functionality that is common to Swing text components.
One of its subclasses is JTextField.
JTextField is a lightweight component that allows the editing of a single line of text.

BRJ071
000007

JTextField components generate ActionEvents whenever the user presses the Return key within the
field. To get these events, implement the ActionListener interface and register your listener using the
addActionListener() method.

Some of its constructors are shown here:


1. JTextField( ):- Constructs a new TextField.
2. JTextField(int cols):- Constructs a new empty TextField with the specified number of columns.
3. JTextField(String s, int cols):- Constructs a new TextField initialized with the specified text and
columns.
4. JTextField(String s):- Constructs a new TextField initialized with the specified text.

Example:
The following example illustrates how to create a text field. The applet begins by getting its content
pane, and then a flow layout is assigned as its layout manager. Next, a JTextField object is created and
is added to the content pane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add text field to content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
}

JTextArea

A JTextArea is used to accept multi-line input from the user.


The java.awt.TextArea internally handles scrolling. JTextArea is different in that it doesn't manage
scrolling, but implements the swing Scrollable interface. This allows it to be placed inside a JScrollPane if
scrolling behavior is desired, and used directly if scrolling is not desired.
The java.awt.TextArea has the ability to do line wrapping. This was controlled by the horizontal scrolling
policy.
JTextArea has a bound property for line wrapping that controls whether or not it will wrap lines. By
default, the line wrapping property is set to false (not wrapped).
java.awt.TextArea has two properties rows and columns that are used to determine the preferred size. If
the value for rows or columns is equal to zero, the preferred size along that axis is used for the viewport
preferred size along the same axis.
The java.awt.TextArea could be monitored for changes by adding a TextListener for TextEvents.

Constructors:1. JTextArea():-Constructs a new TextArea.


2. JTextArea(Document doc) :-Constructs a new JTextArea with the given document model, and
defaults for all of the other arguments (null, 0, 0).
3. JTextArea(Document doc, String text, int rows, int columns) :-Constructs a new JTextArea
with the specified number of rows and columns, and the given model.
4. JTextArea(int rows, int columns):-Constructs a new empty TextArea with the specified
number of rows and columns.
5. JTextArea(String text):-Constructs a new TextArea with the specified text displayed.
6. JTextArea(String text, int rows, int columns):-Constructs a new TextArea with the specified
text and number of rows and columns.

8 |B R J

BRJ072
000008

Combo Boxes

Swing provides a combo box (a combination of a text field and a drop-down list)
Through the JComboBox class, which extends JComponent?
A combo box normally displays one entry.
However, it can also display a drop-down list that allows a user to select a different entry.
Two of JComboBox's constructors are shown here:
JComboBox( )
JComboBox(Vector v)
Here, v is a vector that initializes the combo box.
Items are added to the list of choices via the addItem( ) method,
whose signature is shown here:
void addItem (Object ob)
Here, obj is the object to be added to the combo box.
Example:The following example contains a combo box and a label. The label displays an
icon. The combo box contains entries for France, Germany, Italy, and Japan.
When a country is selected, the label is updated to display the flag for that country.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
</applet>
*/
public class JComboBoxDemo extends JApplet
implements ItemListener {
JLabel jl;
ImageIcon france, germany, italy, japan;
public void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Create a combo box and add it
// to the panel
JComboBox jc = new JComboBox();
jc.addItem("France");
jc.addItem("Germany");
jc.addItem("Italy");
jc.addItem("Japan");
jc.addItemListener(this);
contentPane.add(jc);
// Create label
jl = new JLabel(new ImageIcon("france.gif"));
contentPane.add(jl);
}
public void itemStateChanged(ItemEvent ie) {
String s = (String)ie.getItem();
jl.setIcon(new ImageIcon(s + ".gif"));
}
}

Radio Buttons

9 |B R J

Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton.
Some of its constructors are shown here:
1. JRadioButton(Icon i):- Creates an initially unselected radio button with the specified image but
no text.
2. JRadioButton(Icon i, Boolean state):- Creates a radio button with the specified image and
selection state, but no text.
3. JRadioButton(String s):- Creates an unselected radio button with the specified text.

BRJ073
000009

4. JRadioButton(String s, boolean state):- Creates a radio button with the specified text and
selection state.
5. JRadioButton(String s, Icon i):- Creates a radio button that has the specified text and image,
and that is initially unselected.
6. JRadioButton(String s, Icon i, boolean state):- Creates a radio button that has the specified
text, image, and selection state.
Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at
any time.
The ButtonGroup class is instantiated to create a button group. Elements are then added to the button
group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.

Example:
The following example displays three radio buttons and one text field are created. When a radio button
is pressed, its text is displayed in the text field. Radio button presses generate action events that are
handled by actionPerformed( ). The getActionCommand( ) method gets the text that is associated
with a radio button and uses it to set the text field.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener
{
JTextField tf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add radio buttons to content pane
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
contentPane.add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
contentPane.add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this);
contentPane.add(b3);
// Define a button group
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
// Create a text field and add it
// to the content pane
tf = new JTextField(5);
contentPane.add(tf);
}
public void actionPerformed(ActionEvent ae)
{
tf.setText(ae.getActionCommand());
}
}

10 |B R J

BRJ074
000010

Tabbed Panes

A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title.
Tabbed panes are commonly used for setting configuration options.
Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent.
Constructor:
o JTabbedPane() :-Creates an empty TabbedPane with a default tab placement of
JTabbedPane.TOP
o JTabbedPane(int tabPlacement) :-Creates an empty TabbedPane with the specified tab
placement of either: JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, or
JTabbedPane.RIGHT.
o JTabbedPane(int tabPlacement, int tabLayoutPolicy):-Creates an empty TabbedPane with
the specified tab placement and tab layout policy.
Tabs are defined via the following method:
o void addTab(String str, Component comp):- Adds a component represented by a title and no
icon.
Parameters:

title - the title to be displayed in this tab


component - the component to be displayed when this tab is
clicked

The general procedure to use a tabbed pane in an applet is outlined here:


1. Create a JTabbedPane object.
2. Call addTab( ) to add a tab to the pane.
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the content pane of the applet.

Example:
The following example illustrates how to create a tabbed pane. The first tab is titled "Cities" and
contains four buttons. Each button displays the name of a city. The second tab is titled "Colors" and
contains three check boxes. Each check box displays the name of a color. The third tab is titled "Flavors"
and contains one combo box. This enables the user to select one of three flavors.

11 |B R J

import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet
{
public void init()
{
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
getContentPane().add(jtp);
}
}
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel

BRJ075
000011

{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}

Scroll Panes

A scroll pane is a component that presents a rectangular area in which a component may be viewed.
Horizontal and/or vertical scroll bars may be provided if necessary.
Scrollpanes are implemented in Swing by the JScrollPane class, which extends JComponent.
Some of its constructors are shown here:
1. JScrollPane(Component comp):- Creates a JScrollPane that displays the contents of the
specified component, where both horizontal and vertical scrollbars appear whenever the
component's contents are larger than the view.
2. JScrollPane(int vsb, int hsb):- Creates an empty (no viewport view) JScrollPane with specified
scrollbar constants.
3. JScrollPane(Component comp, int vsb, int hsb):- Creates a JScrollPane that displays the view
component in a viewport whose view position can be controlled with a pair of scrollbars.
These constants are defined by the ScrollPaneConstants interface. Some
examples of these constants are described as follows:

1. HORIZONTAL_SCROLLBAR_ALWAYS:- Always provide horizontal scroll bar


2. HORIZONTAL_SCROLLBAR_AS_NEEDED:- Provide horizontal scroll bar, if needed
3. VERTICAL_SCROLLBAR_ALWAYS:- Always provide vertical scroll bar
4. VERTICAL_SCROLLBAR_AS_NEEDED:-Provide vertical scroll bar, if needed
Following steps that you should follow to use a scroll pane in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object.
3. Add the scroll pane to the content pane of the applet.

Example:The following example illustrates a scroll pane. First, the content pane of the JApplet object is obtained and
a border layout is assigned as its layout manager. Next, a JPanel object is created and four hundred buttons
are added to it, arranged into twenty columns.The panel is then added to a scroll pane, and the scroll pane
is added to the content pane. This causes vertical and horizontal scroll bars to appear.
You can use the scrollbars to scroll the buttons into view.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet
{

12 |B R J

BRJ076
000012

public void init()


{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
// Add 400 buttons to a panel
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
jp.add(new JButton("Button " + b));
++b;
}
}
// Add panel to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(jp, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp, BorderLayout.CENTER);
}
}

Tables

A table is a component that displays rows and columns of data. You can drag the cursor on column
boundaries to resize columns. You can also drag a column to a new position.
Tables are implemented by the JTable class, which extends JComponent.
Constructors
o JTable(Object data[ ][ ], Object colHeads[ ]):- Constructs a JTable to display the values in the two
dimensional array, rowData, with column names, columnNames.
o JTable(int numRows, int numColumns):-Constructs a JTable with numRows and numColumns of
empty cells using DefaultTableModel.
Here are the steps for using a table in an applet:
1. Create a JTable object.
2. Create a JScrollPane object.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the applet.

Example:
The following example illustrates how to create and use a table. The content pane of the JApplet object is
obtained and a border layout is assigned as its layout manager. This table has three columns. A twodimensional array of strings is created for the table cells. These arrays are passed to the JTable constructor.
The table is added to a scroll pane and then the scroll pane is added to the content pane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet
{
public void init()
{
// Get content pane
Container contentPane = getContentPane();
// Set layout manager
contentPane.setLayout(new BorderLayout());
// Initialize column headings
final String[] colHeads = { "Name", "Roll No", "Address", "Percentage" };
// Initialize data
final Object[][] data = {
{ "Ramesh Shetty","1","kalina","67%" },

13 |B R J

BRJ077
000013

{ "Kapil Varma","2","bandra","45%" },
{ "Ritu Singh", "3","malad","56%" },
{ "Amita Jadhav","4","miraroad","89%" },
{ "Sumit Sahani", "5","mahim","79%" },

};// Create the table


JTable table = new JTable(data, colHeads);
// Add tree to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp, BorderLayout.CENTER);
}
}

Trees

One of Swing's advanced components is JTree. Trees are good for representing hierarchical information, like
the contents of a disk drive or a company's organizational chart.
The classes that support JTree have their own package, javax.swing.tree.
A tree's data model is made up of interconnected nodes. A node has a name, typically, a parent, and some
number of children (possibly 0).
In Swing, a node is represented by the TreeNode interface. Nodes that can be modified are represented by
MutableTreeNode. A concrete implementation of this interface is DefaultMutableTreeNode. One node, called
the root node, usually resides at the top of the hierarchy.
A tree's data model is represented by the TreeModel interface. Swing provides an implementation of this
interface called DefaultTreeModel. You can create a DefaultTreeModel by passing a root TreeNode to its
constructor.
You could create a TreeMdel with just one node like this:
TreeNode root = new DefaultMutableTreeNode("Root node");
TreeModel model = new DefaultTreeModel(root);

Here's another example with a real hierarchy.


The root node contains two nodes, Node 1 and Group.
The Group node contains Node 2 and Node 3 as sub nodes.

MutableTreeNode root = new DefaultMutableTreeNode("Root node");


MutableTreeNode group = new DefaultMutableTreeNode("Group");
root.insert(group, 0);
root.insert(new DefaultMutableTreeNode("Node 1"), 1);
group.insert (new DefaultMutableTreeNode("Node 2"), 0);
group.insert (new DefaultMutableTreeNode("Node 3"), 1);

The second parameter to the insert() method is the index of the node in the parent.
Once you've got your nodes organized, you can create a TreeModel in the same way as before:
TreeModel model = new DefaultTreeModel(root);

Once you have a tree model, creating a JTree is simple:


JTree tree = new JTree(model);

Tree Events
A tree fires several events. You can find out when nodes have been expanded and collapsed, and when
selections occur. Two distinct event listener interfaces handle this information.
TreeExpansionListener
TreeSelectionListener

The following example registers an event listener that prints out the last selected node:

Constructors:o JTree():-Returns a JTree with a sample model.


o JTree(TreeModel newModel):-Returns an instance of JTree which displays the root node -- the
tree is created using the specified data model.

tree.addTreeSelectionListener(new TreeSelectionListener( )
{
public void valueChanged(TreeSelectionEvent e) {
TreePath tp = e.getNewLeadSelectionPath( );
System.out.println(tp.getLastPathComponent( ));
}
});

14 |B R J

BRJ078
000014

JTree(TreeNode root):-Returns a JTree with the specified TreeNode as its root, which displays the
root node.
o JTree(Object [] value):- Returns a JTree with each element of the specified array as the child of a
new root node which is not displayed.
Interfaces associated with the trees are:o MutableTreeNode:-Defines the requirements for a tree node object that can change -- by adding or
removing child nodes, or by changing the contents of a user object stored in the node.
Event class:o TreeExpansionEvent:-An event used to identify a single path in a tree. The source returned by
getSource will be an instance of JTree.
Other Classes associated with the trees are:o DefaultMutableTreeNode :-DefaultMutableTreeNode implements the MutableTreeNode interface A
DefaultMutableTreeNode is a general-purpose node in a tree data structure. A tree node may have at
most one parent and 0 or more children. DefaultMutableTreeNode provides operations for examining
and modifying a node's parent and children and also operations for examining the tree that the
node is a part of.
o TreeModel:- A simple tree data model that uses TreeNodes
o TreePath:- Represents a path to a node. A TreePath is an array of Objects that are taken from a
TreeModel. The elements of the array are ordered such that the root is always the first element
(index 0) of the array.
Methods associated with trees are:o public void add(MutableTreeNode newChild):-Removes newChild from its parent and makes it a
child of this node by adding it to the end of this node's child array.
o public TreeNode[] getPath():-Returns the path from the root, to get to this node. The last element in
the path is this node.
o public Object[] getPath():-Returns an ordered array of Objects containing the components of this
TreePath. The first element (index 0) is the root.
o public void insert(MutableTreeNode newChild,int childIndex):-Removes newChild from its
present parent (if it has a parent), sets the child's parent to this node, and then adds the child to this
node's child array at index childIndex. newChild must not be null and must not be an ancestor of
this node.
Here are the steps that you should follow to use a tree:o Create a JTree object.
o Create a JScrollPane Object.
o Add the tree to the scroll panes.
o Add the scroll to the content pane of the applet.
o

Example:-

import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class JTreeExample extends JFrame
{
JTreeExample()
{
MutableTreeNode it = new DefaultMutableTreeNode("IT Department");
MutableTreeNode fyit = new DefaultMutableTreeNode("FYIT");
MutableTreeNode syit = new DefaultMutableTreeNode("SYIT");
it.insert(fyit,0);
it.insert(syit,1);
fyit.insert(new DefaultMutableTreeNode("Maths-2"), 0);
fyit.insert(new DefaultMutableTreeNode("DAA"), 1);
fyit.insert(new DefaultMutableTreeNode("ETC"), 2);
fyit.insert(new DefaultMutableTreeNode("PSD"), 3);
fyit.insert(new DefaultMutableTreeNode("CG"), 4);
syit.insert(new DefaultMutableTreeNode("DBMS"), 1);
syit.insert(new DefaultMutableTreeNode("OS"), 2);
syit.insert(new DefaultMutableTreeNode("C++,JAVA"), 3);
syit.insert(new DefaultMutableTreeNode("EComm"), 4);
syit.insert(new DefaultMutableTreeNode("SE"), 5);

15 |B R J

DefaultTreeModel model = new DefaultTreeModel(it);


JTree tree = new JTree(model);
getContentPane().add(tree);

BRJ079
000015

setSize(300,300);
setVisible(true);

This section contains an example that showcases the following tree techniques:

}
public static void main(String[] args)
{
new JTreeExample();

Construction of a tree model, using DefaultMutableTreeNode.


Creation and display of a JTree
Listening for tree selection events
Modifying the tree's data model while the JTree is showing

Here's the source code for the example:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class PartsTree {


public static void main(String[] args) {
// create a hierarchy of nodes
MutableTreeNode root = new DefaultMutableTreeNode("Parts");
MutableTreeNode beams = new DefaultMutableTreeNode("Beams");
MutableTreeNode gears = new DefaultMutableTreeNode("Gears");
root.insert(beams, 0);
root.insert(gears, 1);
beams.insert(new DefaultMutableTreeNode("1x4 black"), 0);
beams.insert(new DefaultMutableTreeNode("1x6 black"), 1);
beams.insert(new DefaultMutableTreeNode("1x8 black"), 2);
beams.insert(new DefaultMutableTreeNode("1x12 black"), 3);
gears.insert(new DefaultMutableTreeNode("8t"), 0);
gears.insert(new DefaultMutableTreeNode("24t"), 1);
gears.insert(new DefaultMutableTreeNode("40t"), 2);
gears.insert(new DefaultMutableTreeNode("worm"), 3);
gears.insert(new DefaultMutableTreeNode("crown"), 4);
// create the JTree
final DefaultTreeModel model = new DefaultTreeModel(root);
final JTree tree = new JTree(model);

16 |B R J

// create a text field and button to modify the data model


final JTextField nameField = new JTextField("16t");
final JButton button = new JButton("Add a part");
button.setEnabled(false);
button.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e) {
TreePath tp = tree.getSelectionPath( );
MutableTreeNode insertNode =
(MutableTreeNode)tp.getLastPathComponent( );
int insertIndex = 0;
if (insertNode.getParent( ) != null) {
MutableTreeNode parent =
(MutableTreeNode)insertNode.getParent( );
insertIndex = parent.getIndex(insertNode) + 1;
insertNode = parent;
}
MutableTreeNode node =
new DefaultMutableTreeNode(nameField.getText( ));
model.insertNodeInto(node, insertNode, insertIndex);
}
});
JPanel addPanel = new JPanel(new GridLayout(2, 1));
addPanel.add(nameField);

BRJ080
000016

addPanel.add(button);
// listen for selections
tree.addTreeSelectionListener(new TreeSelectionListener( ) {
public void valueChanged(TreeSelectionEvent e) {
TreePath tp = e.getNewLeadSelectionPath( );
button.setEnabled(tp != null);
}
});
// create a JFrame to hold the tree
JFrame frame = new JFrame("PartsTree v1.0");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(200, 200);
frame.getContentPane( ).add(new JScrollPane(tree));
frame.getContentPane( ).add(addPanel, BorderLayout.SOUTH);
frame.setVisible(true);
}}

Another Example:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/*
*/
<applet code="JTreeEvents" width=400 height=200>
</applet>
public class JTreeEvents extends JApplet {
JTree tree;
JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
// Set layout manager
contentPane.setLayout(new BorderLayout());
// Create top node of tree
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
// Create subtree of "A"
DefaultMutableTreeNodea=new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);
// Create subtree of "B"
DefaultMutableTreeNodeb=new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);
// Create tree
tree = new JTree(top);
// Add tree to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(tree, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp, BorderLayout.CENTER);
}
// Add text field to applet
jtf = new JTextField("", 20);
contentPane.add(jtf, BorderLayout.SOUTH);
// Anonymous inner class to handle mouse clicks
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
doMouseClicked(me);
}
});
void doMouseClicked(MouseEvent me) {
TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
if(tp != null)
jtf.setText(tp.toString());
else
}
jtf.setText("");
}

17 |B R J

BRJ081
000017

JAVA SERVLETS

JAVA SERVLETS
SNO..

CONTENTS

PAGE NO.,

Introduction to Java Servlet

Simple servlet

2
3
4
5
6
7
8
9

Lifecycle of a servlet

The servlet api

The javax. Servlet package

Reading servlet parameters

Handling http request & responses


Using cookies.

Session tracking.

7
8
9

10

1|BRJ

BRJ082

Introduction to Java Servlet


1)
2)

Java Servlets are programs that run on a Web server or Application server and act as a middle layer between a requests coming
from a Web browser or other HTTP client and databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and
create web pages dynamically.

Advantage of Servlets Over "Traditional" CGI


Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI.
Efficient

With traditional CGI, a new process is started for the each HTTP request.

If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution of time.

With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not the heavyweight
operating system process.

Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the for the CGI program is
loaded into memory N time.

With servlets, however, there are N threads but only a single copy of the servlets class.

Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations,
keeping the database connections open, and the like.
Convenient

servlets have an extensive infrastructure for automatically parsing and decoding the HTML form data, reading and setting
HTTP headers, handling cookies, tracking sessions, and many other such utilities.
Powerful

Java servlets let you easily do several things that are difficult or impossible with the regular CGI.

servlets can talk directly to Web server (regular CGI programs can't).

This simplifies operations that need to look up images and other data stored in the standard places.

Servlets can also share data among each other, making the useful things like database connection pools easy to implement.

They can also maintain information from request to request, simplifying things like session tracking and caching of previous
computation.

Portable

Servlets are written in Java and follows a well-standardized API.

Server can also run virtually unchanged on Apache, Microsoft IIS, or WebStar.

Servlets are supported directly or via a plug-in on the almost every major Web server.
Inexpensive

There are also a num of free or inexpensive Web servers available that are good for "personal" use or low-volume Web sites.

However, with major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive.

Nevertheless, once you have a Web server, no matter the cost of that server, adding servlets support to it (if it doesn't come
preconfigured to support servlets) is generally free or cheap.

Lifecycle of a servlet

A servlet life cycle can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet
1) The servlet is initialized by calling the init () method.
2) The servlet calls service() method to process a client's request.
3) The servlet is terminated by calling the destroy() method.
4) Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.

The init() method :

The init method is designed to be called only once.

It is called when the servlet is first created, and not called again for each user request.

So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the
servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread
that is handed off to doGet or doPost as appropriate.

The init() method simply creates or loads some data that will be used throughout the life of the servlet.

2|BRJ

BRJ083

The init method definition looks like this:


public void init() throws ServletException
{
// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to
write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service.
The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete,
etc.., methods as appropriate.
Here is the signature of this method:

public void service(ServletRequest request,ServletResponse response) throws ServletException, IOException


{
//service method code
}

The service () method is called by the container and service method invokes doGet(), doPost(), doPut(), doDelete(), etc..
methods as appropriate.
So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of
request you receive from the client.
The doGet() and doPost() are most frequently used methods within each service request.
Here are the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled
by doGet() method.
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
// Servlet code
}

The destroy() method :


The destroy() method is called only once at the end of the life cycle of a servlet.
This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk,
and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this:
{

public void destroy()

// Finalization code...

The following figure depicts a typical servlet life-cycle scenario.


First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.

Sample Servlet

we will begin by building and testing a simple servlet. The basic steps are the following:
1) Create and compile the servlet source code.
2) Start Tomcat.
3) Start a Web browser and request the servlet.
Let us examine each of these steps in detail.

1)Create and Compile the Servlet Source Code

To begin, create a file named HelloServlet.java that contains the following program:

3|BRJ

BRJ084

import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request,ServletResponse response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}

Lets look closely at this program. First, note that it imports the javax.servlet package.
This package contains the classes and interfaces required to build servlets.
the program defines HelloServlet as a subclass of GenericServlet.
The GenericServlet class provides functionality that makes it easy to handle requests and responses.
Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden.
This method handles requests from a client.
Notice that the first argument is a ServletRequest object.
This enables the servlet to read data that is provided via the client request.
The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response.
In this program, the MIME type is text/html. This indicates that the browser should interpret the content as HTML source code.
Next, the getWriter( ) method obtains a PrintWriter.
Anything written to this stream is sent to the client as part of the HTTP response.
Then println( ) is used to write some simple HTML source code as the HTTP response.
Compile this source code and place the HelloServlet.class file in the Tomcat class files directory.

2) Start Tomcat

As explained, to start Tomcat, select Start Tomcat in the Start | Programs menu, or run startup.bat from the
C:\Program Files\Apache Tomcat 4.0\bin\ directory.

3) Start a Web Browser and Request the Servlet

Start a Web browser and enter the URL shown here:

http://localhost:8080/examples/servlet/HelloServlet

Alternatively, you may enter the URL shown here:

http://127.0.0.1:8080/examples/servlet/HelloServlet

This can be done because 127.0.0.1 is defined as the IP address of the local machine.

You will observe the output of the servlet in the browser display area. It will contain the string Hello! in bold type.

The Servlet API

Two packages contain the classes and interfaces that are required to build servlets.
These packages are javax.servlet and javax.servlet.http.
These constitute the Servlet API.

These 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.
You must download Tomcat to obtain their functionality.
The Servlet API has been in a process of ongoing development and enhancement.
The current servlet specification is version is 2.3
The Servlet API is supported by most Web servers, such as those from Sun, Microsoft, and others.
Check at http://java.sun.com for the latest information.

4|BRJ

BRJ085

The javax.servlet Package

The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.
The following table summarizes the core interfaces that are provided in this package.
The most significant of these is Servlet.
All servlets must implement this interface or extend a class that implements the interface.
The ServletRequest and ServletResponse interfaces are also very important.

The following table summarizes the core classes that are provided in the javax.servlet package.

Let us examine these interfaces and classes in more detail.


The Servlet Interface

All servlets must implement the Servlet interface.

It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet.

A method is also provided that allows a servlet to obtain any initialization parameters.

The methods defined by Servlet are shown in the below Table.

The init( ), service( ), and destroy( ) methods are the life cycle methods of the servlet.
These are invoked by the server ie.. servlet container.
The getServletConfig( ) method is called by the servlet to obtain initialization parameters.
A servlet developer overrides the getServletInfo( ) method to provide a string with useful information
(for example, author, version, date, copyright).
This method is also invoked by the server.

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 summarized here:

The ServletContext Interface

The ServletContext interface is implemented by the server.

It enables servlets to obtain information about their environment.

5|BRJ

BRJ086

Several of its methods are summarized in the Below Table.

The ServletRequest Interface

The ServletRequest interface is implemented by the server.

It enables a servlet to obtain information about a client request.

Several of its methods are summarized in the below Table.

The ServletResponse Interface

The ServletResponse interface is implemented by the server.

It enables a servlet to formulate a response for a client.

Several of its methods are summarized in the below Table.

The SingleThreadModel Interface

This interface is used to indicate that only a single thread will execute the service( ) method 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.

First, it can create several instances of the servlet.

6|BRJ

BRJ087


When a client request arrives, it is sent to an available instance of the servlet.

Second, it can synchronize access to the servlet.


The GenericServlet Class

The GenericServlet class provides implementations of the basic life cycle methods for a servlet and is typically subclassed by
servlet developers.

GenericServlet implements the Servlet and ServletConfig interfaces.

In addition, a method to append a string to the server log file is available.

The signatures of this method are shown here:


void log(String s)
void log(String s, Throwable e)

Here, s is the string to be appended to the log, and e is an exception that occurred.
The ServletInputStream Class

The ServletInputStream class extends InputStream. It is implemented by the server and provides an input stream that a
servlet developer can use to read the data from a client request.

It defines the default constructor.

In addition, a method is provided to read bytes from the stream.

Its signature is shown here:


int readLine(byte[ ] buffer, int offset, int size) throws IOException

Here, buffer is the array into which size bytes are placed starting at offset.

The method returns the actual number of bytes read or 1 if an end-of-stream condition is encountered.
The ServletOutputStream Class

The ServletOutputStream class extends OutputStream.

It is implemented by the server and provides an output stream that a servlet developer can use to write data to a client
response.

A default constructor is defined. It also defines the print( ) and println( ) methods, which output data to the stream.
The Servlet Exception Classes

javax.servlet defines two exceptions.

The first is ServletException, which indicates that a servlet problem has occurred.

The second is UnavailableException, which extends ServletException.

It indicates that a servlet is unavailable.

Reading Servlet Parameters

The ServletRequest class includes methods that allow you to read the names and values of parameters that are included in a
client request.
We will develop a servlet that illustrates their use.
The example contains two files.
A Web page is defined in PostParameters.htm and a servlet is defined in PostParametersServlet.java.
The HTML source code for PostParameters.htm is shown in the following listing.
It defines a table that contains two labels and two text fields.
One of the labels is Employeeand the other is Phone.
There is also a submit button.
Notice that the action parameter of the form tag specifies a URL.
The URL identifies the servlet to process the HTTP POST request.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlet/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>

The source code for PostParametersServlet.java is shown in the following listing.

The service( ) method is overridden to process client requests.

The getParameterNames( ) method returns an enumeration of the parameter names.

These are processed in a loop.

You can see that the parameter name and value are output to the client.

The parameter value is obtained via the getParameter( ) method.


import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet

7|BRJ

BRJ088

extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}

Compile the servlet and perform these steps to test this example:
1) Start Tomcat (if it is not already running).
2) Display the Web page in a browser.
3) Enter an employee name and phone number in the text fields.
4) Submit the Web page.
After following these steps, the browser will display a response that is dynamically generated by the servlet.

Handling HTTP Requests and Responses

The HttpServlet class provides specialized methods that handle the various types of HTTP requests.
A servlet developer typically overrides one of these methods.
These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ).
the GET and POST requests are commonly used when handling form input.

Handling HTTP GET Requests

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 in ColorGet.htm and a servlet is defined in ColorGetServlet.java.
The HTML source code for ColorGet.htm is shown in the following listing.
It defines a form that contains a select element and a submit button.
Notice that the action parameter of the form tag specifies a URL.
The URL identifies a servlet to process the HTTP GET request.

The source code for ColorGetServlet.java is shown in the following listing.


The doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet.
It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user.
A response is then formulated.

<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examples/servlet/ColorGetServlet">
<B>Color:</B>
<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>
</body>
</html>

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.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, if it is not already running.
2) Display the Web page in a browser.

8|BRJ

BRJ089

3)
4)

Select a color.
Submit the Web page.

After completing these steps, the browser will display the response that is dynamically generated by the servlet.

One other point: Parameters for an HTTP GET request are included as part of the URL that is sent to the Web server.

Assume that the user selects the red option and submits the form.

The URL sent from the browser to the server is

http://localhost:8080/examples/servlet/ColorGetServlet?color=Red

The characters to the right of the question mark are known as the query string.

Handling HTTP POST Requests

Here we will develop 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 Web page is defined in ColorPost.htm and a servlet is defined in ColorPostServlet.java.
The HTML source code for ColorPost.htm is shown in the following listing.
It is identical to ColorGet.htm except that the method parameter for the form tag explicitly specifies that the POST method
should be used, and the action parameter for the form tag specifies a different servlet.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlet/ColorPostServlet">
<B>Color:</B>
<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>
</body>
</html>

The source code for ColorPostServlet.java is shown in the following listing.


The doPost( ) method is overridden to process any HTTP POST requests that are sent to this servlet.
It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user.
A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

Compile the servlet and perform the same steps as described in the previous section to test it.
Note: Parameters for an HTTP POST request are not included as part of the URL that is sent to the Web server.
In this example, the URL sent from the browser to the server is:
http://localhost:8080/examples/servlet/ColorGetServlet

The parameter names and values are sent in the body of the HTTP request.

Using Cookies

Now, lets develop a servlet that illustrates how to use cookies.


The servlet is invoked when a form on a Web page is submitted.
The example contains three files as summarized here:
File Description AddCookie.htm Allows a user to specify a value for the cookie named MyCookie.
AddCookieServlet.java Processes the submission of AddCookie.htm.
GetCookiesServlet.java Displays cookie values.
The HTML source code for AddCookie.htm is shown in the following listing.
This 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.
<html>
<body>
<center>
<form name="Form1"
method="post"

9|BRJ

BRJ090

action="http://localhost:8080/examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>

The source code for AddCookieServlet.java is shown in the following listing.


It gets the value of the parameter named data.
It then creates a Cookie object that has the name MyCookie and contains the value of the data parameter.
The cookie is then added to the header of the HTTP response via the addCookie( ) method.
A feedback message is then written to the browser.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}

The source code for GetCookiesServlet.java is shown in the following listing.


It invokes the getCookies( ) method to read any cookies that are included in the HTTP GET request.
The names and values of these cookies are then written to the HTTP response.
Observe that the getName( ) and getValue( ) methods are called to obtain this information.
import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
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, if it is not already running.
2. Display AddCookie.htm in a browser.
3. Enter a value for MyCookie.
4. Submit the Web page.

After completing these steps you will observe that a feedback message is displayed by the browser.

Next, request the following URL via the browser:

http://localhost:8080/examples/servlet/GetCookiesServlet

Observe that the name and value of the cookie are displayed in the browser.
In this example, an expiration date is not explicitly assigned to the cookie via the SsetMaxAge( ) method of Cookie.
Therefore, the cookie expires when the browser session ends.
You can experiment by using setMaxAge( ) and observe that the cookie is then saved to the disk on the client machine.

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 created via the getSession( ) method of HttpServletRequest.
An HttpSession object is returned.
This object can store a set of bindings that associate names with objects.

10 | B R J

BRJ091

The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) 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.
The following servlet illustrates how to use session state.
The getSession( ) method gets the current session.
A new session is created if one does not already exist.
The getAttribute( ) method is called to obtain the object that is bound to the name date.
That object is a Date object that encapsulates the date and time when this page was last accessed.
(Of course, there is no such binding when the page is first accessed.)
A Date object encapsulating the current date and time is then created.
The setAttribute( ) method is called to bind the name date to this object.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date();
hs.setAttribute("date", date);S
pw.println("Current date: " + date);
}
}

When you first request this servlet, the browser displays one line with the current date and time information.
On subsequent invocations, two lines are displayed.
The first line shows the date and time when the servlet was last accessed.
The second line shows the current date and time.

11 | B R J

BRJ092

JSP
JAVA

SNO.,

SERVER

PAGES

(UNIT-V)

CONTENTS

PAGE NO.,

JSP (JAVA SERVER PAGES)


1.
2.
3.
4.
5.
6.
7

Introduction

The anatomy of a jsp page

Problem with servlets

Jsp processing

Jsp application design with mvc architecture

Database access:
Accessing a database from a Jsp
Reading and storing information in a database.

1|BRJ

BRJ094

4
5
6
8

Introduction to Java server Pages

Java Server Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert
java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.
A Java Server Pages component is a type of Java Servlet that is designed to fulfill the role of a user interface for a Java web
application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP
actions and commands. Using JSP, you can collect input from users through web page forms, present records from a database
or another source, and create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences,
accessing JavaBeans components, passing control between pages and sharing information between requests, pages etc.
WHY USE JSP?
1) Java Server Pages often serve the same purpose as programs implemented using the Common Gateway Interface
(CGI). But JSP offer several advantages in comparison with the CGI.
2) Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of
having a separate CGI files.
3) JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an
interpreter and the target script each time the page is requested.
4) Java Server Pages are built on top of the Java Servlets API, so like Servlets; JSP also has access to all the powerful
Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
5) JSP pages can be used in combination with Servlets that handle the business logic, the model supported by Java Servlet
template engines.
6) Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This means that JSP can
play a part in the simplest applications to the most complex and demanding.
ADVANTAGES OF JSP:
Following is the list of other advantages of using JSP over other technologies:
1) Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating
systems and non-Microsoft Web servers.
2) Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements
that generate the HTML.
3) Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.
4) JavaScript: JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to
perform complex tasks like database access and image processing etc.
5) Static HTML: Regular HTML, of course, cannot contain dynamic information.
6) A development environment is where you would develop your JSP programs, test them and finally run them.

The Problem with Servlets

In many Java servlet-based applications, processing the request and generating the response
are both handled by a single servlet class.
Example: shows how a servlet class often looks.

A typical servlet class

public class OrderServlet extends HttpServlet


{
public void doGet((HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter( );
if (isOrderInfoValid(request))
{

saveOrderInfo(request);
out.println("<html>");
out.println(" <head>");
out.println(" <title>Order Confirmation</title>");
out.println(" </head>");
out.println(" <body>");
out.println(" <h1>Order Confirmation</h1>");
renderOrderInfo(request);
out.println(" </body>");
out.println("</html>");
}

If you're not a programmer, don't worry about all the details in this code. The point is that the servlet contains request
processing and business logic (implemented by methods such as isOrderInfoValid( ) and saveOrderInfo( )), and also generates

2|BRJ

BRJ095

the response HTML code, embedded directly in the servlet code using println( ) calls. A more structured servlet application
isolates different pieces of the processing in various reusable utility classes and may also use a separate class library for
generating the actual HTML elements in the response. Even so, the pure servlet-based approach still has a few problems:
Thorough Java programming knowledge is needed to develop and maintain all aspects of the application, since the processing
code and the HTML elements are lumped together.
Changing the look and feel of the application, or adding support for a new type of client (such as a WML client), requires the
servlet code to be updated and recompiled.
It's hard to take advantage of web-page development tools when designing the application interface. If such tools are used to
develop the web page layout, the generated HTML must then be manually embedded into the servlet code, a process which is
time consuming, error prone, and extremely boring. Adding JSP to the puzzle lets you solve these problems by separating the
request processing and business logic code from the presentation, as illustrated in Figure 3-1. Instead of embedding HTML in
the code, you place all static HTML in a JSP page, just as in a regular web page, and add a few JSP elements to generate the
dynamic parts of the page. The request processing can remain the domain of the servlet, and the business logic can be handled
by JavaBeans and EJB components.
Figure 3-1. Separation of request processing, business logic, and presentation

As I mentioned before, separating the request processing and business logic from presentation makes it possible to divide the
development tasks among people with different skills. Java programmers implement the request processing and business logic
pieces, web page authors implement the user interface, and both groups can use best-of-breed development tools for the task
at hand. The result is a much more productive development process. It also makes it possible to change different aspects of the
application independently, such as changing the business rules without touching the user interface.
This model has clear benefits even for a web-page author without programming skills, working alone. A page author can
develop web applications with many dynamic features, using the JSP standard actions and the JSTL libraries, as well as Java
components provided by open source projects and commercial companies.

The Anatomy of a JSP Page

A JSP page is simply a regular web page with JSP elements for generating the parts that differ for each request, as shown in
Figure Template text and JSP elements

3|BRJ

BRJ096

Template text and JSP elements

Everything in the page that isn't a JSP element is called template text. Template text can be any text: HTML, WML, XML, or even
plain text. Since HTML is by far the most common web-page language in use today, most of the descriptions and examples in
this book use HTML, but keep in mind that JSP has no dependency on HTML; it can be used with any markup language.
Template text is always passed straight through to the browser. When a JSP page request is processed, the template text and
dynamic content generated by the JSP elements are merged, and the result is sent as the response to the browser.

JSP Processing

Just as a web server needs a servlet container to provide an interface to servlets, the server needs a JSP container to process
JSP pages. The JSP container is responsible for intercepting requests for JSP pages. To process all JSP elements in the page, the
container first turns the JSP page into a servlet (known as the [JSP page implementation class).
The conversion is pretty straightforward; all template text is converted to println( ) statements similar to the ones in the
handcoded servlet shown in Example 3-1, and all JSP elements are converted to Java code that implements the corresponding
dynamic behavior. The container then compiles the servlet class Converting the JSP page to a servlet and compiling the servlet
form the translation phase.
The JSP container initiates the translation phase for a page automatically when it receives the first request for the page. Since
the translation phase takes a bit of time, the first user to request a JSP page notices a slight delay. The translation phase can
also be initiated explicitly; this is referred to as precompilation of a JSP page.
Precompiling a JSP page is a way to avoid hitting the first user with this delay. The JSP container is also responsible for
invoking the JSP page implementation class (the generated servlet) to process each request and generate the response. This is
called the request processing phase.
The two phases are illustrated in Figure 3-3.

4|BRJ

BRJ097

As long as the JSP page remains unchanged, any subsequent request goes straight to the request processing phase (i.e., the
container simply executes the class file). When the JSPpage is modified, it goes through the translation phase again before
entering the request processing phase.
The JSP container is often implemented as a servlet configured to handle all requests for JSPpages. In fact, these two containers
-- a servlet container and a JSP container -- are often combined in one package under the name web container.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the
translation phase, a JSP page is handled exactly like a regular servlet: it's loaded once and called repeatedly, until the server is
shut down. By virtue of being an automatically generated servlet, a JSP page inherits all the advantages of a servlet platform
and vendor independence, integration, efficiency, scalability,robustness, and security.

JSP Elements

There are three types of JSP elements you can use: directive, action, and scripting.
3.3.1.1 Directive elements
The directive elements, shown in Table 3-1, specify information about the page itself that remains the same between requests
-- for example, if session tracking is required or not, buffering requirements, and the name of a page that should be used to
report errors, if any.

Standard action elements


Action elements typically perform some action based on information that is required at the exact time JSP page is requested
by a browser. An action can, for instance, access parameters sent with the request to do a database lookup. It can also
dynamically generate HTML, such as a table filled with information retrieved from an external system.
The JSP specification defines a few standard action elements, listed in Table 3-2.

3.3.1.3 Custom action elements and the JSP Standard Tag Library
In addition to the standard actions, the JSP specification includes a Java API a programmer can use to develop custom actions to
extend the JSP language. The JSP Standard Tag Library (JSTL) is such an extension, with the special status of being defined by a
formal specification from Sun and typically bundled with the JSP container. JSTL contains action elements for processes
needed in most JSP applications, such as conditional processing, database access, internationalization, and more.
3.3.1.4 Scripting elements
Scripting elements, shown in Table 3-3, allow you to add small pieces of code (typically Java code) in a JSP page, such as an if
statement to generate different HTML depending on a certain condition. Like actions, they are also executed when the page is
requested. You should use scripting elements with extreme care: if you embed too much code in your JSP pages, you will end
up with the same kind of maintenance problems as with servlets embedding HTML.

5|BRJ

BRJ098

3.3.1.5 JavaBeans components


JSP elements, such as action and scripting elements, are often used to work with JavaBeans. Put succinctly, a JavaBeans
component is a Java class that complies with certain coding conventions. JavaBeans components are typically used as
containers for information that describes application entities, such as a customer or an order.

JSP Application Design with MVC

JSP technology can play a part in everything from the simplest web application, such as an online phone list or an employee
vacation planner, to full-fledged enterprise applications, such as a human-resource application or a sophisticated online
shopping site. How large a part JSP plays differs in each case, of course. In this section, I introduce a design model called
Model-View-Controller (MVC), suitable for both simple and complex applications. MVC was first described by Xerox in a
number of papers published in the late 1980s. The key point of using MVC is to separate logic into three distinct units: the
Model, the View, and the Controller. In a server application, we commonly classify the parts of the application as business
logic, presentation, and request processing. Business logic is the term used for the manipulation of an application's data, such
as customer, product, and order information.
Presentation refers to how the application data is displayed to the user, for example, position, font, and size. And finally,
request processing is what ties the business logic and presentation parts together. In MVC terms, the Model corresponds to
business logic and data, the View to the presentation, and the Controller to the request processing. Why use this design with
JSP? The answer lies primarily in the first two elements. Remember that an application data structure and logic (the Model) is
typically the most stable part of an application, while the presentation of that data (the View) changes fairly often. Just look at
all the face-lifts many web sites go through to keep up with the latest fashion in web design. Yet, the data they present remains
the same. Another common example of why presentation should be separated from the business logic is that you may want to
present the data in different languages or present different subsets of the data to internal and external users. Access to the
data through new types of devices, such as cell phones and personal digital assistants (PDAs), is the latest trend. Each client
type requires its own presentation format. It should come as no surprise, then, that separating business logic from the
presentation makes it easier to evolve an application as the requirements change; new presentation interfaces can be
developed without touching the business logic.
This MVC model is used for most of the examples in this book. In Part II, JSP pages are used as both the Controller and the
View, and JavaBeans components are used as the Model. The examples in Chapter 5 through Chapter 9 use a single JSP page
that handles everything,
Many types of real-world applications can be developed this way, but what's more important is that this approach allows you
to examine all the JSP features without getting distracted by other technologies.

Accessing a Database

Almost all the web applications that you see on the Internet access a database. Databases store customer information,
order information, product information, even discussion forum messages.
in short, all information that needs to survive a server restart and is too complex to handle in plain-text files.
There are many types of databases used in the industry today.
However, relational databases are by far the most common.
A relational database uses tables to represent the information it handles.
A table consists of rows of columns, with each column holding a single value of a predefined data type.
Examples of these data types are text data, numeric data, dates, and binary data such as images and sound.
A specialized language called Structured Query Language (SQL) is used to access the data.
SQL is an ANSI standard and is supported by all major database vendors.
Relational database engines come in all shapes and sizes, from simple one-person databases with limited features, to
sophisticated databases capable of handling large numbers of concurrent users with support for transactions
distributed over multiple servers and extremely optimized search algorithms.
Even though they all use SQL as the data access language, the API used to execute SQL statements is different for each
database engine. To help programmers write code that's portable between database engines, the standard Java
libraries include an API called the Java Database Connectivity (JDBC) API. JDBC defines a set of classes that can execute
SQL statements the same way in any relational database.
The complexity of databases varies extensively. A database for an online discussion forum, for instance, requires only
one or two tables, while a database for a human resources system may contain hundreds of related tables. In this
chapter, we look at a set of JSTL database actions you can use to build any type of database-driven web application.
But if the database is complex, you may want to use another approach: hiding the database behind application specific
beans and custom actions, or moving all database processing to a servlet and using JSP only to show the result.

6|BRJ

BRJ099

Accessing a Database from a JSP Page

JSTL includes a number of actions for database access to make it easy to develop simple database-driven JSP applications.
The actions provide the following features:

Using a connection pool for better performance and scalability

Supporting queries, updates, and inserts

Handling the most common data-type conversions

Supporting a combination of database operations in one transaction

Application Architecture Example

we build an employee register application. This application contains functions for adding and changing employee information,
as well as for looking up employees matching a search criterion. The employee information is stored in a relational database
and accessed through the JSTL database access actions.
The employee registration part of the application contains the pages shown in Figure 11-1.
Figure 11-1. Employee registration pages

The enter.jsp page presents a form in which the


user enters information about an employee. When
the form is submitted, it invokes the validate.jsp
page, where all input is validated. If the input is
invalid, the request is forwarded back to the
enter.jsp page to display error messages and the
form with all the values the user previously
entered. The user can then correct the invalid
values and submit the form again. When all input is
valid, the validate.jsp page forwards the request to
the store.jsp page where the information is stored
in the database.
Finally, the store.jsp page redirects to the
confirmation.jsp page, which displays the
information actually stored in the database as a
confirmation to the user.
Figure 11-2 shows the pages used to implement the employee search function.
Figure 11-2 Employee search pages
The search.html page is a regular HTML page with
a form for entering the search criteria. The user
can enter a partial first name, last name and
department name. Submitting the form invokes the
find.jsp page. Here the database is searched for
employees matching the criteria specified by the
user, and the result is kept in the request scope.

The find.jsp page forwards to the list.jsp page,


where the result is displayed. For each employee
listed, the list.jsp page adds a Delete button.
Clicking on the Delete button invokes the
delete.jsp page, removing the employee
information from the database. The delete.jsp then
redirects to the find.jsp page, to get an updated
collection of employees matching the search
criteria, and the find.jsp forwards to list.jsp as
before, to show the result after deleting the
employee.

7|BRJ

BRJ100

Reading and Storing Information in a Database

The first page the user loads to register an employee in the example application is enter.jsp. This page, which contains a form
for entering all information about an employee, is shown in
Employee information entry form

The input is validated by the validate.jsp page when


the form is submitted. The enter.jsp and validate.jsp
pages are similar to the pages for input validation and
don't access the database. Instead of going through
these pages now, let's jump directly to the store.jsp
page where the database access takes place.

We'll return to the enter.jsp and validate.jsp pages at


the end of this chapter, to look at some interesting
things not related to database access. Example 11-1
shows the complete store.jsp page. This page first
searches the database for information about an
employee with the specified username. If one is
found, the database is updated with all the other employee information the user entered. Otherwise, a new employee entry is
stored in the database. All database information about the employee is then collected, and the request is forwarded to the
confirmation.jsp page. Let's look at the complete page first and then discuss the different pieces in detail.

Database access page (store.jsp)

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>


<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>

<%-- See if the employee is already defined. If not, insert the info, else update it. --%>
<sql:query var="empDbInfo">
SELECT * FROM Employee
WHERE UserName = ?
<sql:param value="${param.userName}" />
</sql:query>
<%-- Deal with the date values: parse the employment date and create a Date object from it,
and create a new variable to hold the current date. --%>
<fmt:parseDate value="${param.empDate}" var="parsedEmpDate"
pattern="yyyy-MM-dd" />
<jsp:useBean id="now" class="java.util.Date" />
<c:choose>
<c:when test="${empDbInfo.rowCount == 0}">
<sql:update>
INSERT INTO Employee (UserName, Password, FirstName, LastName, Dept, EmpDate, EmailAddr, ModDate)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
<sql:param value="${param.userName}" />
<sql:param value="${param.password}" />
<sql:param value="${param.firstName}" />
<sql:param value="${param.lastName}" />
<sql:param value="${param.dept}" />
<sql:dateParam value="${parsedEmpDate}" type="date"/>
<sql:param value="${param.emailAddr}" />
<sql:dateParam value="${now}" />
</sql:update>
</c:when>
<c:otherwise>
<sql:update>
UPDATE Employee SET Password = ?, FirstName = ?, LastName = ?, Dept = ?, EmpDate = ?, EmailAddr = ?, ModDate = ?
WHERE UserName = ?
<sql:param value="${param.password}" />
<sql:param value="${param.firstName}" />

8|BRJ

BRJ101

<sql:param value="${param.lastName}" />


<sql:param value="${param.dept}" />
<sql:dateParam value="${parsedEmpDate}" type="date"/>
<sql:param value="${param.emailAddr}" />
<sql:dateParam value="${now}" />
<sql:param value="${param.userName}" />
</sql:update>
</c:otherwise>
</c:choose>
<%-- Get the new or updated data from the database --%>
<sql:query var="newEmpDbInfo" scope="session">
SELECT * FROM Employee
WHERE UserName = ?
<sql:param value="${param.userName}" />
</sql:query>
<%-- Redirect to the confirmation page --%>
<c:redirect url="confirmation.jsp" />

All JSTL database actions are packaged in their own tag library. At the top of the page in Example 11-1 you'll find the taglib
directive for this library that associates it with the sql prefix, similar to the tag libraries used in the previous examples. Most of
the JSTL database actions are used in this page. Let's look at them one at a time.

Reading database information

The first JSTL action that accesses the database in Example 11-1 is the <sql:query> action, described in Table 11-3.

The <sql:query> action reads information from a database using the SQL SELECT statement, specified in the element's body or
as the sql attribute value. A SELECT statement retrieves data from the database by specifying various clauses that identify the
table to search in, the columns to return, the search criteria, and other options. If you're not familiar with the SELECT
statement, you can read up on it in the documentation for your database.
The SELECT statement in Example 11-1 gets all columns in the Employee table for every row in which the UserName column
has the value specified in the userName field in the entry form. Since the username is unique in our application, either 0 or one
row is returned.
The <sql:query> action in this example gets a connection from the default DataSource specified by the context parameter. It
then executes the SQL SELECT statement and saves the result in the scope specified by the scope attribute, with the name
specified by the var attribute. If no scope is specified, as in this example, the result is saved in the page scope.
Besides the SQL statement, the action element body also contains an <sql:param> action,described in Table 11-4.

9|BRJ

BRJ102

The <sql:param> action replaces a placeholder, marked with a question mark (?), in the SQL statement with a value. In
Example 11-1, the EL expression used for the value attribute gets the userName request parameter value, corresponding to
the form field with the same name in the enter.jsp page:
<sql:query var="empDbInfo">
SELECT * FROM Employee WHERE UserName = ?
<sql:param value="${param.userName}" />
</sql:query>

You could use a <c:out> action in the body instead to insert the userName parameter value directly into the SQL statement,
like this:
<ora:sqlQuery id="empDbInfo">
SELECT * FROM Employee
WHERE UserName = '<c:out value="${params.userName}" />'
</ora:sqlQuery>

but then you run into the problem of string quoting in SQL. Most database engines require a string literal to be enclosed in
single quotes in an SQL statement. That's easy to handle by just putting single quotes around the <c:out> action, like I've done
here. What's not so easy is how to handle quotes within the string value.
Different database engines employ different rules for how to encode embedded quotes. Most require a single quote in a string
literal to be duplicated, while others use a backslash as an escape character or let you enclose the string literal with double
quotes if the value includes single quotes.
When you use the <sql:param> action, you don't have to worry about this type of formatting at all; the value is set directly in
the SQL statement, bypassing all quoting rules.
Another reason for using <sql:param> is that using a <c:out> action to add a dynamic value to an SQL statement is also a
security risk. If a user enters a value such as "foo' OR 1 = 1 -- " in the username field, the SQL statement looks like this after the
<c:out> action is processed:
SELECT * FROM Employee WHERE UserName = 'foo' OR 1 = 1 --'
The "OR 1 = 1" part means that this condition is always true, making the SQL statements returning all rows instead of only one
row matching a specific username. Most databases interpret the " -- " part as the start of a comment, so whatever comes after
these characters is ignored.
Tricks like this can be used to gain access to protected sites or return information that is supposed to be secret. Using
<sql:param> prevents this type of attacks. Instead of merging the dynamic value and the static text to create an SQL statement
that the database then interprets, the <sql:param> action explicitly tells the database to use the provided value in place of the ?
when it has interpreted the statement. Hence, there's no way to fool it.
Only one dynamic value is needed in the query in Example 11-1, but an SQL statement can contain as many placeholders as
you like, matched by the same number of <sql:param> actions in the <sql:query> element body.
The first <sql:param> action replaces the first question mark in the SQL statement with its value, the second replaces the
second question mark, and so on. The result generated by the <sql:query> action is an instance of the
javax.servlet.jsp.jstl.sql.Result class. It's a bean with a number of properties for accessing all rows and their column values, as
well as properties for the column names and number of rows in the result.
We look at most of the Result properties later in this chapter, but the only one used in Example 11-1 is the rowCount property.
It's used to see if the query returned any rows.
The SELECT statement searches the database for information about the employee entered in the form. If the employee is
already registered, the query returns one row; otherwise no rows.
This information is used to decide whether to insert or update the employee information:
<c:choose>
<c:when test="${empDbInfo.rowCount == 0}">
<%-- Insert the employee data --%>
...
</c:when>
<c:otherwise>
<%-- Update the employee data --%>
...
</c:otherwise>
</c:choose>

Inserting database information

An SQL INSERT statement is used to insert new rows in a database table. To execute an INSERT statement, use the
<sql:update> action, described in Table 11-5.

10 | B R J

BRJ103

The <sql:update> action executes any SQL statement that doesn't return rows: INSERT, UPDATE, and DELETE, and even socalled Data Definition Language (DDL) statements such as CREATE TABLE. These statements do exactly what it sounds like
they do: insert, update and delete information, and create a new table, respectively. (Refer to your database documentation for
details about the syntax.) For INSERT, UPDATE, and DELETE, the <sql:update> action can optionally save an Integer object,
telling how many rows were affected by the statement. The Integer is saved in the scope specified by the scope attribute using
the name specified by the var attribute. This feature isn't used in Example 11-1, but in some applications it can be used as
feedback to the user or to decide what to do next. The SQL statement can be specified through the sql attribute or the action's
body, and <sql:param> actions can be used to give values to the placeholders in the statement. Multiple <sql:param> actions
are used in Example 11-1:
<sql:update>
INSERT INTO Employee (UserName, Password, FirstName, LastName, Dept, EmpDate, EmailAddr, ModDate)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
<sql:param value="${param.userName}" />
<sql:param value="${param.password}" />
<sql:param value="${param.firstName}" />
<sql:param value="${param.lastName}" />
<sql:param value="${param.dept}" />
<sql:dateParam value="${parsedEmpDate}" type="date"/>
<sql:param value="${param.emailAddr}" />
<sql:dateParam value="${now}" />
</sql:update>
Most of the placeholders are replaced with request parameter values, just as for the query. The exceptions are the
placeholders for the EmpDate and ModDate columns, which require special attention.
Databases are picky about the format for date and time data types. In Example 11-1 we get the date from the form as a string
in the format yyyy-MM-dd (e.g., 2002-03-06), but the EmpDate column is declared as a DATE column, as shown in Table 11-1.
Some databases accept a string in the format used for this application as a value for a DATE column, but others don't. To be on
the safe side, it's best to convert the string into its native date format, a java.util.Date object, before sending it to the database.
It can be done using a JSTL action from the formatting library, assigned the fmt prefix by the taglib directive at the beginning of
the page:
<fmt:parseDate value="${params.empDate}" var="parsedEmpDate" pattern="yyyy-MM-dd" />
The <fmt:parseDate> action takes the date or time string specified by the value attribute and interprets it according to the
pattern defined by the pattern attribute. The pattern describes the order and format of the year, month, and day parts in the
string representation of the date. We'll return to the <fmt:parseDate> action in Chapter 13 to look at all the details, but for now
it suffices to say that the pattern description is very flexible. For instance, if you want the user to enter dates in a format such
"Tuesday February 19, 2002," you specify the pattern EEEE MMMM dd, yyyy instead of the yyyy-MM-dd pattern used in this
example to tell the action how to interpret the date string. If the string value can be interpreted as a date according to the
pattern, the action saves a java.util.Date object representing the date as a variable with the name specified by the var attribute.
This variable can then replace the placeholder in the SQL statement.
Besides dates, you should also convert numeric values you receive as strings when they are declared as INT, REAL, etc., in the
database, using the JSTL <fmt:parseNumber> action. In this example, there are no columns of this type. The JSTL formatting
actions are very powerful, but let's save the details for Chapter 13.
The Employee table also has a column named ModDate, to hold the date and time the information was last modified. It is
declared as a TIMESTAMP column. To set its value, we need a java.util.Date object that represents the current date and time.
It's easy to create one with the <jsp:useBean> action: <jsp:useBean id="now" class="java.util.Date" />

11 | B R J

BRJ104

The <jsp:useBean> action can create an instance of any class that has a no-arguments constructor, like the java.util.Date class
does. The instance is saved in the variable named by the id attribute.
Finally, we need to use the <sql:dateParam> action, described in Table 11-6, instead of the <sql:param> action to set the date
and timestamp values.

You have to use <sql:dateParam> because of an unfortunate quirk in the JDBC API.
JDBC defines its own classes for date and time values: java.sql.Date, java.sql.Time, and java.sql.Timestamp. These are the only
types accepted for date and time value placeholders. The <sql:dateParam> takes a java.util.Date object and turns it into one of
the JDBC types based on the type attribute value or to a java.sql.Timestamp if no type is specified.

Updating database information

Once you know how to insert information in a database, updating it's a piece of cake. You just use the <sql:update> action with
an SQL UPDATE statement instead of an INSERT statement:
<sql:update>
UPDATE Employee
SET Password = ?,
FirstName = ?,
LastName = ?,
Dept = ?,
EmpDate = ?,
EmailAddr = ?,
ModDate = ?
WHERE UserName = ?
<sql:param value="${param.password}" />
<sql:param value="${param.firstName}" />
<sql:param value="${param.lastName}" />
<sql:param value="${param.dept}" />
<sql:dateParam value="${parsedEmpDate}" type="date" />
<sql:param value="${param.emailAddr}" />
<sql:dateParam value="${now}" />
<sql:param value="${param.userName}" />
</sql:update>
No surprises here. The only difference from how you insert information is the SQL statement. The UPDATE statement sets all
the specified values for rows matching the WHERE clause, in this case the single row for the specified employee.

12 | B R J

BRJ105

You might also like