You are on page 1of 144

11.

LECTURE NOTES

UNIT-1 INTRODUCTION TO HTML


What is HTML?

HTML is a language for describing web pages.

 HTML stands for Hyper Text Markup Language


 HTML is not a programming language, it is a markup language
 A markup language is a set of markup tags
 HTML uses markup tags to describe web pages

HTML Tags

HTML markup tags are usually called HTML tags

 HTML tags are keywords surrounded by angle brackets like <html>


 HTML tags normally come in pairs like <b> and </b>
 The first tag in a pair is the start tag, the second tag is the end tag

Start and end tags are also called opening tags and closing tags.

HTML Documents = Web Pages

 HTML documents describe web pages


 HTML documents contain HTML tags and plain text
 HTML documents are also called web pages

The purpose of a web browser (like Internet Explorer or Firefox) is to read HTML documents and display
them as web pages. The browser does not display the HTML tags, but uses the tags to interpret the
content of the page:

Example:

<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>

Example explanation

 The text between <html> and </html> describes the web page
 The text between <body> and </body> is the visible page content
 The text between <h1> and </h1> is displayed as a heading
 The text between <p> and </p> is displayed as a paragraph
Example

<html>

<body>

<h1>This is my Main Page</h1>

<p>This is some text.</p>

<p><a href="page1.htm">This is a link to Page 1</a></p>

<p><a href="page2.htm">This is a link to Page 2</a></p>

</body>

</html>

Output :

This is my Main Page


This is some text.

This is a link to Page 1

This is a link to Page 2

Page1.html

<html>

<body>

<h1>This is Page1</h1>

<p>This is some text.</p>

</body>

</html>

Page2.html
<html>

<body>

<h1>This is Page2</h1>

<p>This is some text.</p>

</body>

</html>

HTML Headings

HTML headings are defined with the <h1> to <h6> tags.

<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>

<h4>This is a heading</h4>
<h5>This is a heading</h5>
<h6>This is a heading</h6>

HTML Paragraphs

HTML paragraphs are defined with the <p> tag.

<p>This is a paragraph</p>

HTML Links

HTML links are defined with the <a> tag.

<a href="http://www.w3schools.com">This is a link</a>

HTML Images

HTML images are defined with the <img> tag.

<img src="w3schools.jpg" width="104" height="142" />

HTML Elements

An HTML element is everything from the start tag to the end tag:
Start tag * Element content End tag *

<p> This is a paragraph </p>

<a href="default.htm"
This is a link </a>
>

<br />    

* The start tag is often called the opening tag. The end tag is often called the closing tag.

HTML Element Syntax

 An HTML element starts with a start tag / opening tag


 An HTML element ends with an end tag / closing tag
 The element content is everything between the start and the end tag
 Some HTML elements have empty content
 Empty elements are closed in the start tag
 Most HTML elements can have attributes

EX:

<html>
<body>
<p>This is my first paragraph</p>
</body>
</html>

Example Explained
The <p> element:
<p>This is my first paragraph</p>

The <p> element defines a paragraph in the HTML document


The element has a start tag <p> and an end tag </p>
The element content is: This is my first paragraph

The <body> element:

<body>
<p>This is my first paragraph</p>
</body>

The <body> element defines the body of the HTML document


The element has a start tag <body> and an end tag </body>
The element content is another HTML element (a paragraph)
The <html> element:

<html>
<body>
<p>This is my first paragraph</p>
</body>
</html>

The <html> element defines the whole HTML document.


The element has a start tag <html> and an end tag </html>
The element content is another HTML element (the body)

Empty HTML Elements

HTML elements without content are called empty elements. Empty elements can be closed in the start
tag.

<br> is an empty element without a closing tag (it defines a line break).

HTML Attributes

 HTML elements can have attributes


 Attributes provide additional information about the element
 Attributes are always specified in the start tag
 Attributes come in name/value pairs like: name="value"

Attribute Example

HTML links are defined with the <a> tag. The link address is provided as an attribute:

EX:

<html>
<body>
<a href="http://www.w3schools.com">
This is a link</a>
</body>
</html>
OUTPUT:

This is a link click on this one it will reflect on the site

Always Quote Attribute Values

Attribute values should always be enclosed in quotes.


Double style quotes are the most common, but single style quotes are also allowed.

In some rare situations, like when the attribute value itself contains quotes, it is necessary to use single
quotes:

name='John "ShotGun" Nelson'

HTML Headings

Headings are defined with the <h1> to <h6> tags.

<h1> defines the largest heading. <h6> defines the smallest heading

EXAMPLE

<html>

<body>

<h1>This is heading 1</h1>

<h2>This is heading 2</h2>

<h3>This is heading 3</h3>

<h4>This is heading 4</h4>

<h5>This is heading 5</h5>

<h6>This is heading 6</h6>

</body>

</html>

OUTPUT

This is heading 1
This is heading 2
This is heading 3

This is heading 4

This is heading 5

This is heading 6

HTML Rules (Lines)

The <hr /> tag is used to create an horizontal rule (line).

Example:

<html>

<body>

<p>The hr tag defines a horizontal rule:</p>

<hr />

<p>This is a paragraph</p>

<hr />

<p>This is a paragraph</p>

<hr />

<p>This is a paragraph</p>

</body>

</html>

OUTPUT

The hr tag defines a horizontal rule:


This is a paragraph

This is a paragraph

This is a paragraph

HTML Comments

Comments can be inserted in the HTML code to make it more readable and understandable. Comments
are ignored by the browser and are not displayed.

Comments are written like this:

EX:

<html>
<body>
<!--This comment will not be displayed-->
<p>This is a regular paragraph</p>
</body>
</html

OUTPUT:

This is a regular paragraph

HTML Tag Reference

Tag Description

<html> Defines an HTML document

<body> Defines the document's body

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

<hr /> Defines a horizontal rule

<!--> Defines a comment

HTML LINE BREAKS


Use the <br /> tag if you want a line break (a new line) without starting a new paragraph

<html>
<body>
<p>This is<br />a para<br />graph with line breaks</p>
</body>
</html>

OUTPUT:

This is a paragraph with line breaks

HTML Text Formatting

HTML uses tags like <b> and <i> for formatting output, like bold or italic text.

Example:

<html>

<body>

<p><b>This text is bold</b></p>

<p><big>This text is big</big></p>

<p><i>This text is italic</i></p>

<p><code>This is computer output</code></p>

<p>This is<sub> subscript</sub> and <sup>superscript</sup></p>

</body>

</html>

Output:

This text is bold

This text is big

This text is italic

This is computer output


This is subscript and superscript

DEL and INS a text in HTML DOC:

EX:

<html>

<body>

<p>

a dozen is

<del>twenty</del>

<ins>twelve</ins>

pieces

</p>

<p>

Most browsers will overstrike deleted text and underline inserted text.

</p>

<p>

Some older browsers will display deleted or inserted text as plain text.

</p>

</body>

</html>

OUTPUT:

dozen is twelve pieces

Most browsers will overstrike deleted text and underline inserted text.

Some older browsers will display deleted or inserted text as plain text
FOR DECLARING ADDRESS in HTML DOCUMENT

<html>

<body>

<address>

Donald Duck<br>

BOX 555<br>

Disneyland<br>

USA

</address>

</body>

</html>

OUTPUT:

Donald Duck
BOX 555
Disneyland
USA

The HTML Style Attribute

The purpose of the style attribute is:

To provide a common way to style all HTML elements.

Styles were introduced with HTML 4, as the new and preferred way to style HTML elements. With
HTML styles, styles can be added to HTML elements directly by using the style attribute, or indirectly by
in separate style sheets (CSS files).

You can learn everything about styles and CSS in our CSS tutorial.

Deprecated Tags and Attributes


In HTML 4, some tags and attributes are defined as deprecated. Deprecated means that they will
not be supported in future versions of HTML and XHTML.
The message is clear: Avoid the use of deprecated tags and attributes.
These tags and attributes should be avoided:

Tags Description

<center> Defines centered content

<font> and <basefont> Defines HTML fonts

<s> and <strikeout> Defines strikeout text

<u> Defines underlined text

   

Attributes Description

align Defines the alignment of text

bgcolor Defines the background color

color Defines the text color

For all the above: Use styles instead.

Style Examples:
EX1. Set the back ground color yellow
<html>
<body style="background-color:yellow">
<h2>Look: Colored Background!</h2>
</body>
</html>

output:

Look: Colored Background!(back ground color is in yellow)


EX2:
<html>
<body>
<h1 style="font-family:verdana">A heading</h1>
<p style="font-family:courier new; color:red; font-size:20px;">A paragraph</p>
</body>
</html>

output:

A heading

A paragraph

Ex3:

<html>

<body>

<h1 style="text-align:center">This is heading 1</h1>

<p>The heading above is aligned to the center of this page. The heading above is aligned to the center of
this page. The heading above is aligned to the center of this page.</p>

</body>

</html>

output:

This is heading 1

The heading above is aligned to the center of this page. The heading above is aligned to the center of this
page. The heading above is aligned to the center of this page.

An HTML Link:
Link syntax:
<a href="url">Link text</a>

The start tag contains attributes about the link.

The element content (Link text) defines the part to be displayed.


Note: The element content doesn't have to be text. You can link from an image or any other
HTML element.

The target Attribute

The target attribute defines where the linked document will be opened.

The code below will open the document in a new browser window:

Ex:

<a href="http://www.w3schools.com/"
target="_blank">Visit W3Schools!</a>

HTML Images

he Image Tag and the Src Attribute

In HTML, images are defined with the <img> tag. 

The <img> tag is empty, which means that it contains attributes only and it has no closing tag.

To display an image on a page, you need to use the src attribute. Src stands for "source". The value of the
src attribute is the URL of the image you want to display on your page.

The syntax of defining an image

<img src="url" />

The URL points to the location where the image is stored.

The Alt Attribute


The alt attribute is used to define an "alternate text" for an image. The value of the alt attribute is
an author-defined text
<img src="boat.gif" alt="Big Boat" />

INSERT IMAGE EXAMPLE:


<html>
<body>
<p>
An image:
<img src="constr4.gif"
width="144" height="50">
</p>
<p>
A moving image:
<img src="hackanm.gif"
width="48" height="48">
</p>
<p>
Note that the syntax of inserting a moving image is no different from that of a non-moving image.
</p>
</body>
</html>
OUTPUT:

An image:

A moving image:

Note that the syntax of inserting a moving image is no different from that of a non-moving image.

Example2: Images from another location

<html>

<body>

<p>An image from another folder:</p>

<img src="/images/chrome.gif"

width="33" height="32">

<p>An image from W3Schools:</p>

<img src="http://www.w3schools.com/images/w3schools_green.jpg"

width="104" height="142">
</body>

</html>

output:

An image from another folder:

An image from W3Schools:

HTML TABLES
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each
row is divided into data cells (with the <td> tag). The letters td stands for "table data," which is
the content of a data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal
rules, tables, etc.

Simple EX:
<tableborder="1">
<tr>
<td>row1,cell1</td>
<td>row1,cell2</td>
</tr>
<tr>
<td>row2,cell1</td>
<td>row2,cell2</td>
</tr>
</table>
output:
row 1, cell 1 row 1, cell 2

row 2, cell 1 row 2, cell 2

Note: If you do not specify a border attribute the table will be displayed without any borders. Sometimes
this can be useful, but most of the time, you want the borders to show.

Headings in a Table
Headings in a table are defined with the <th> tag.
Ex:
<table border="1">
<tr>
<th>Heading</th>
<th>Another Heading</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

output:

Heading Another Heading

row 1, cell 1 row 1, cell 2

row 2, cell 1 row 2, cell 2

Empty Cells in a Table:


Table cells with no content are not displayed very well in most browsers.
EX:
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td></td>
</tr>
</table>
OUTPUT:

row 1, cell 1 row 1, cell 2

row 2, cell 1 row2, cell2

EXAMPLES:

1.Table with no borders:

<html>

<body>

<h4>This table has no borders:</h4>

<table>

<tr>

<td>100</td>

<td>200</td>

<td>300</td>

</tr>

<tr>

<td>400</td>

<td>500</td>

<td>600</td>

</tr>

</table>

</body>
</html>

OUTPUT: This table has no borders:

100 200 300

400 500 600

EX: table caption

<html>

<body>

<h4>

This table has a caption,

and a thick border:

</h4>

<table border="6">

<caption>My Caption</caption>

<tr>

<td>100</td>

<td>200</td>

<td>300</td>

</tr>

<tr>

<td>400</td>

<td>500</td>

<td>600</td>

</tr>

</table>

</body>

</html>
OUTPUT:

This table has a caption, and a thick border:


My Caption

100 200 300

400 500 600

EX:

<html>

<body>

<table border="1">

<tr>

<td>

<p>This is a paragraph</p>

<p>This is another paragraph</p>

</td>

<td>This cell contains a table:

<table border="1">

<tr>

<td>A</td>

<td>B</td>

</tr>

<tr>

<td>C</td>
<td>D</td>

</tr>

</table>

</td>

</tr>

<tr>

<td>This cell contains a list

<ul>

<li>apples</li>

<li>bananas</li>

<li>pineapples</li>

</ul>

</td>

<td>HELLO</td>

</tr>

</table>

</body>

</html>

OUTPUT:

This is the link for output

http://w3schools.com/html/tryit.asp?filename=tryhtml_table_elements;

EX: cell padding

<html>

<body>

<h4>Without cellpadding:</h4>
<table border="1">

<tr>

<td>First</td>

<td>Row</td>

</tr>

<tr>

<td>Second</td>

<td>Row</td>

</tr>

</table>

<h4>With cellpadding:</h4>

<table border="1"

cellpadding="10">

<tr>

<td>First</td>

<td>Row</td>

</tr>

<tr>

<td>Second</td>

<td>Row</td>

</tr>

</table>

</body>
</html>

output:

`Without cellpadding:
First Row

Second Row

With cellpadding:

First Row

Second Row

Ex:Cell spacing

<html>

<body>

<h4>Without cellspacing:</h4>

<table border="1">

<tr>

<td>First</td>

<td>Row</td>

</tr> <tr>

<td>Second</td>

<td>Row</td>

</tr>

</table>

<h4>With cellspacing:</h4>
<table border="1"

cellspacing="10">

<tr>

<td>First</td>

<td>Row</td>

</tr>

<tr>

<td>Second</td>

<td>Row</td>

</tr>

</table>

</body>

</html>

Table Tags
Tag Description

<table> Defines a table

<th> Defines a table header

<tr> Defines a table row

<td> Defines a table cell

<caption> Defines a table caption

<colgroup> Defines groups of table columns

<col> Defines the attribute values for one or more columns in a table

<thead> Defines a table head

<tbody> Defines a table body


<tfoot> Defines a table footer

HTML Lists:
HTML supports ordered, unordered and definition lists.

Unordered Lists:

An unordered list is a list of items. The list items are marked with bullets (typically small black circles).

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

EX:

<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>

Here is how it looks in a browser:

 Coffee
 Milk

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

Ordered Lists:

An ordered list is also a list of items. The list items are marked with numbers.

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

EX:

<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>

Here is how it looks in a browser:

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

Definition Lists

A definition list is not a list of single items. It is a list of items (terms), with a description of each item
(term).

A definition list starts with a <dl> tag (definition list).

Each term starts with a <dt> tag (definition term).

Each description starts with a <dd> tag (definition description).

EX

<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>

Here is how it looks in a browser:

Coffee

Black hot drink

Milk

White cold drink

Inside the <dd> tag you can put paragraphs, line breaks, images, links, other lists, etc.

EXAMPLES for LIST

1.different types of ordered list

<html>

<body>

<h4>Numbered list:</h4>

<ol>

<li>Apples</li>
<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ol>

<h4>Letters list:</h4>

<ol type="A">

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ol>

<h4>Lowercase letters list:</h4>

<ol type="a">

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ol>

<h4>Roman numbers list:</h4>

<ol type="I">

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>
</ol>

<h4>Lowercase Roman numbers list:</h4>

<ol type="i">

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ol>

</body>

</html>

OUTPUT:

Numbered list:

1. Apples
2. Bananas
3. Lemons
4. Oranges

Letters list:

A. Apples
B. Bananas
C. Lemons
D. Oranges

Lowercase letters list:

a. Apples
b. Bananas
c. Lemons
d. Oranges

Roman numbers list:

I. Apples
II. Bananas
III. Lemons
IV. Oranges
Lowercase Roman numbers list:

i. Apples
ii. Bananas
iii. Lemons
iv. Oranges

EX 2: Different types of unordered list

<html>

<body>

<h4>Disc bullets list:</h4>

<ul type="disc">

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ul>

<h4>Circle bullets list:</h4>

<ul type="circle">

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ul>
<h4>Square bullets list:</h4>

<ul type="square">

<li>Apples</li>

<li>Bananas</li>

<li>Lemons</li>

<li>Oranges</li>

</ul>

</body>

</html>

output:

Disc bullets list:

 Apples
 Bananas
 Lemons
 Oranges

Circle bullets list:

o Apples
o Bananas
o Lemons
o Oranges

Square bullets list:

 Apples
 Bananas
 Lemons
 Oranges

EX: Definition list

<html>

<body>
<h4>A Definition List:</h4>

<dl>

<dt>Coffee</dt>

<dd>Black hot drink</dd>

<dt>Milk</dt>

<dd>White cold drink</dd>

</dl>

</body>

</html>

OUTPUT:

A Definition List:
Coffee

Black hot drink

Milk

White cold drink

EX:nested list

<html>

<body>

<h4>A nested List:</h4>

<ul>

<li>Coffee</li>

<li>Tea

<ul>

<li>Black tea</li>
<li>Green tea

<ul>

<li>China</li>

<li>Africa</li>

</ul>

</li>

</ul>

</li>

<li>Milk</li>

</ul>

</body>

</html>

output:

A nested List:

 Coffee
 Tea
o Black tea
o Green tea
 China
 Africa
 Milk

LIST TAGS:

Tag Description

<ol> Defines an ordered list

<ul> Defines an unordered list

<li> Defines a list item <dl> Defines a definition list

<dt> Defines a term (an item) in a definition list


<dd> Defines a description of a term in a definition list

<dir> Deprecated. Use <ul> instead <menu> Deprecated. Use <ul> instead

HTML Forms
Forms

A form is an area that can contain form elements.

Form elements are elements that allow the user to enter information (like text fields, textarea fields, drop-
down menus, radio buttons, checkboxes, etc.) in a form.

A form is defined with the <form> tag.

Syntax:

<form>
.
input elements
.
</form>

Input

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

Text Fields

Text fields are used when you want the user to type letters, numbers, etc. in a form.

Simple ex:

<form>
First name:
<input type="text" name="firstname" />
<br />
Last name:
<input type="text" name="lastname" />
</form>

How it looks in a browser:

First name:

Last name:
Note that the form itself is not visible. Also note that in most browsers, the width of the text field is 20
characters by default. 

Radio Buttons:

Radio Buttons are used when you want the user to select one of a limited number of choices.

EX:

<form>
<input type="radio" name="sex" value="male" /> Male
<br />
<input type="radio" name="sex" value="female" /> Female
</form>

How it looks in a browser:

Male

Female

Note that only one option can be chosen.

Checkboxes :

Checkboxes are used when you want the user to select one or more options of a limited number of
choices.

Simple ex:

<form>
I have a bike:
<input type="checkbox" name="vehicle" value="Bike" />
<br />
I have a car:
<input type="checkbox" name="vehicle" value="Car" />
<br />
I have an airplane:
<input type="checkbox" name="vehicle" value="Airplane" />
</form>

How it looks in a browser:

I have a bike:

I have a car:

I have an airplane:
The Form's Action Attribute and the Submit Button

When the user clicks on the "Submit" button, the content of the form is sent to the server. The form's
action attribute defines the name of the file to send the content to. The file defined in the action attribute
usually does something with the received input.

Ex:

<form name="input" action="html_form_submit.asp" method="get">


Username:
<input type="text" name="user" />
<input type="submit" value="Submit" />
</form>

How it looks in a browser:

Submit
Username:

If you type some characters in the text field above, and click the "Submit" button, the browser
will send your input to a page called "html_form_submit.asp". The page will show you the
received input.

HTML Frames
Frames

With frames, you can display more than one HTML document in the same browser window. Each HTML
document is called a frame, and each frame is independent of the others.

The disadvantages of using frames are:

 The web developer must keep track of more HTML documents


 It is difficult to print the entire page

The Frameset Tag

 The <frameset> tag defines how to divide the window into frames
 Each frameset defines a set of rows or columns
 The values of the rows/columns indicate the amount of screen area each row/column will occupy

The Frame Tag

 The <frame> tag defines what HTML document to put into each frame

In the example below we have a frameset with two columns. The first column is set to 25% of the width
of the browser window. The second column is set to 75% of the width of the browser window. The
HTML document "frame_a.htm" is put into the first column, and the HTML document "frame_b.htm" is
put into the second column:

Ex:

<frameset cols="25%,75%">
   <frame src="frame_a.htm">
   <frame src="frame_b.htm">
</frameset>

vertical frame set example:

<html>

<frameset cols="25%,50%,25%">

<frame src="frame_a.htm">

<frame src="frame_b.htm">

<frame src="frame_c.htm">

</frameset>

</html>

EX: Horizontal frame set

<html>

<frameset rows="25%,50%,25%">

<frame src="frame_a.htm">

<frame src="frame_b.htm">

<frame src="frame_c.htm">

</frameset></html>

HTML CSS

How to Use Styles

When a browser reads a style sheet, it will format the document according to it. There are three ways of
inserting a style sheet:
External Style Sheet

An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you
can change the look of an entire Web site by changing one file. Each page must link to the style sheet
using the <link> tag. The <link> tag goes inside the head section.

Syntax:

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>

Internal Style Sheet

An internal style sheet should be used when a single document has a unique style. You define internal
styles in the head section with the <style> tag.

Ex:

<head>
<style type="text/css">
body {background-color: red}
p {margin-left: 20px}
</style>
</head>

Inline Styles

An inline style should be used when a unique style is to be applied to a single occurrence of an element.

To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS
property. The example shows how to change the color and the left margin of a paragraph:

<p style="color: red; margin-left: 20px">


This is a paragraph
</p>

UNIT-II INTRODUCTION TO JAVASCRIPT


Introduction to JavaScript

JavaScript is a programming language that can be included on web pages to make them more interactive.
You can use it to check or modify the contents of forms, change images, open new windows and write
dynamic page content. You can even use it with CSS to make DHTML (Dynamic Hyper Text Markup
Language). This allows you to make parts of your web pages appear or disappear or move around on the
page. JavaScript’s only execute on the page(s) that are on your browser window at any set time. When the
user stops viewing that page, any scripts that were running on it are immediately stopped. The only
exception is a cookie, which can be used by many pages to pass information between them, even after the
pages have been closed.

JavaScript, originally nicknamed Livewire and then Live Script when it was created by Netscape, should
in fact be called ECMAscript as it was renamed when Netscape passed it to the ECMA for
standardization.

JavaScript is a client side, interpreted, object oriented, high level scripting language, while Java is a client
side, compiled, object oriented high level language. Now after that mouthful, here's what it means.

Client side

Programs are passed to the computer that the browser is on, and that computer runs them. The alternative
is server side, where the program is run on the server and only the results are passed to the computer that
the browser is on. Examples of this would be PHP, Perl, ASP, JSP etc.

Interpreted

The program is passed as source code with all the programming language visible. It is then converted into
machine code as it is being used. Compiled languages are converted into machine code first then passed
around, so you never get to see the original programming language. Java is actually dual half compiled,
meaning it is half compiled (to 'byte code') before it is passed, then executed in a virtual machine which
converts it to fully compiled code just before use, in order to execute it on the computer's processor.
Interpreted languages are generally less fussy about syntax and if you have made mistakes in a part they
never use, the mistake usually will not cause you any problems.

Scripting

This is a little harder to define. Scripting languages are often used for performing repetitive tasks.
Although they may be complete programming languages, they do not usually go into the depths of
complex programs, such as thread and memory management. They may use another program to do the
work and simply tell it what to do. They often do not create their own user interfaces, and instead will
rely on the other programs to create an interface for them. This is quite accurate for JavaScript. We do not
have to tell the browser exactly what to put on the screen for every pixel, we just tell it that we want it to
change the document, and it does it. The browser will also take care of the memory management and
thread management, leaving JavaScript free to get on with the things it wants to do.

High level

Written in words that are as close to english as possible. The contrast would be with assembly code,
where each command can be directly translated into machine code.

How is JavaScript constructed:

The basic part of a script is a variable, literal or object. A variable is a word that represents a piece of text,
a number, a Boolean true or false value or an object. A literal is the actual number or piece of text or
Boolean value that the variable represents. An object is a collection of variables held together by a parent
variable, or a document component.

The next most important part of a script is an operator. Operators assign literal values to variables or say
what type of tests to perform.

The next most important part of a script is a control structure. Control structures say what scripts should
be run if a test is satisfied.

Functions collect control structures, actions and assignments together and can be told to run those pieces
of script as and when necessary.

The most obvious parts of a script are the actions it performs. Some of these are done with operators but
most are done using methods. Methods are a special kind of function and may do things like submitting
forms, writing pages or displaying messages.

Events can be used to detect actions, usually created by the user, such as moving or clicking the mouse,
pressing a key or resetting a form. When triggered, events can be used to run functions.

As an example, think of the following situation. A person clicks a submit button on a form. When they
click the button, we want to check if they have filled out their name in a text box and if they have, we
want to submit the form. So, we tell the form to detect the submit event. When the event is triggered, we
tell it to run the function that holds together the tests and actions. The function contains a control structure
that uses a comparison operator to test the text box to see that it is not empty. Of course we have to work
out how to reference the text box first. The text box is an object. One of the variables it holds is the text
that is written in the text box. The text written in it is a literal. If the text box is not empty, a method is
used that submits the form.

An Introduction to Dynamic HTML with Javascript

Every web page in the world uses HTML (the Hyper Text Markup Language) - it's a formatting language
that tells a web browser whether the contents of a web page should be in bold, large or small, tabulated or
in paragraphs. However, HTML is a static language - once it's been loaded into a web page then it won't
change; unless, of course, it's Dynamic HTML.

Dynamic HTML works because of the fact that when web page is viewed in a web browser (such as
Microsoft Internet Explorer or Mozilla Firefox) it is not just formatted text - it is actually a set of objects,
a set of objects that can be manipulated using a programming language such as Javascript; and the most
important of the objects to is the document.

Using Javascript to Work with a Web Page Document

The document is the web page itself, and with Javascript it is possible to modify the title of the web page:

document.title = "A Dynamic Web Page";

The contents of that web page can also be created by using Javascript code; for instance the web page can
be written to by using the document's write method:
//Create a heading

document.write ("<h1 id=h1>Hello World</h1>");

//Create a paragraph with text in it

document.write ("<p id=p1>This is a dynamic web page.</p>");

//Create an empty paragraph

document.write ("<p id=p2></p>");

This code actually creates some additional objects (h1, p1 and p2) and they can now be accessed using
Javascript code.

Regexp and White Space:


Easy Pattern Helper makes removing or dealing with white space easy

Accessing Objects within a Web Page Document

Each object that's created must be given a unique ID, and once that has been done then each object can
be accessed using the document's getElementById method; for example, the code above creates an
empty paragraph (p2) - the contents of that paragraph can be changed by using the getElementById
method to access the paragraph and then updating it's innerHTML property:

var p2 = document.getElementById ('p2');

p2.innerHTML = "Isn't this exciting?";

Dealing with Events in a Dynamic Web Page

Each object in a web page has a number of events associated with it - these events are things such as:

onmouseover - this event occurs when the mouse pointer is placed over an object

onmouseout - the mouse pointer is moved away from an object

onclick - the user has clicked on an object

These events can then be used to run Javascript functions - in this example the text in a paragraph
changes color and is displayed in a second paragraph:

<p id=p3

onmouseover="overme('p3')"

onmouseout="away('p3')"
>An example of a web page event</p>

<p id=p4></p>

<script>

var p4 = document.getElementById('p4');

function oversee(me) {

var object = document.getElementById(me);

object.style.color = "blue";

p4.innerHTML = "Your mouse is over '" + object.innerHTML + "'";

function away(me) {

var object = document.getElementById(me);

object.style.color = "black";

p4.innerHTML = "";

</script>

Conclusion

Dynamic HTML using Javascript is not difficult to implement, but those simple techniques can produce
an impressive web page - something much more interesting than just boring old static HTML.

DHTML: Dynamic HTML. An extension of HTML that enables, among other things, the inclusion of
small animations and dynamic menus in Web pages. DHTML code makes use of style sheets and
JavaScript.

When you see an object, or word(s), on a webpage that becomes highlighted, larger, a different color, or a
streak runs through it by moving your mouse cursor over it is the result of adding a DHTML effect. This
is done in the language coding and when the file of the webpage was saved it was saved as the .dhtml
format instead of .htm or .html.

DHTML sites are dynamic in nature. DHTML uses client side scripting to change variables in the
presentation which affects the look and function of an otherwise static page. DHTML characteristics are
the functions while a page is iewed, rather than generating a unique page with each page load (a dynamic
website).
On the other hand, HTML is static. HTML sites relies solely upon client-side technologies. This means
the pages of the site do not require any special processing from the server side before they go to the
browser. In other words, the pages are always the same for all visitors - static. HTML pages have no
dynamic content, as in the examples above.

Objects IN Java Script:

JavaScript is an object oriented language. However, in practice objects defined by the programmer
himself are rarely used, except in complex DOM API's. Of course such standard objects as window and
document and their numerous offspring are very important, but they are defined by the browser, not by
the programmer.

I myself have written JavaScript for more than three years without ever defining an object. The technique
explained on this page is the first practical use of programmer-defined objects I've found.

Since the only other programming languages I know are Commodore 64 Basic (which is not object
oriented, to put it mildly) and Perl (which doesn't need to be object oriented) and since I don't have any
formal training in programming I cannot write a general introduction to objects and object oriented
programming. Therefore a quick overview will have to suffice.

Methods and properties

In JavaScript you can define your own objects. In addition, you can assign methods and properties to each
object, pre-written or self-defined.

Methods are 'things that do something', they can be recognized by their brackets (). When you call them,
like object.method(), something happens.

The Date object

The Date object is used to work with dates and times. You create an instance of the Date object with the
"new" keyword. To store the current date in a variable called "my_date":

var my_date=new Date()

After creating an instance of the Date object, you can access all the methods of the object from the
"my_date" variable. If, for example, you want to return the date (from 1-31) of a Date object, you should
write the following:

my_date.getDate()

You can also write a date inside the parentheses of the Date() object, like this:

new Date("Month dd, yyyy hh:mm:ss")

new Date("Month dd, yyyy")


new Date(yy,mm,dd,hh,mm,ss)

new Date(yy,mm,dd)

new Date(milliseconds)

Here is how you can create a Date object for each of the ways above:

var my_date=new Date("October 12, 1988 13:14:00")

var my_date=new Date("October 12, 1988")

var my_date=new Date(88,09,12,13,14,00)

var my_date=new Date(88,09,12)

var my_date=new Date(500)

The Most Common Methods

NN: Netscape, IE: Internet Explorer, ECMA: Web Standard

Methods Explanation NN IE ECMA

Date() Returns a Date object 2.0 3.0 1.0

getDate() Returns the date of a Date object (from 1-31) 2.0 3.0 1.0

getDay() Returns the day of a Date object (from 0-6. 0=Sunday, 2.0 3.0 1.0
1=Monday, etc.)

getMonth() Returns the month of a Date object (from 0-11. 0=January, 2.0 3.0 1.0
1=February, etc.)

getFullYear() Returns the year of the Date object (four digits) 4.0 4.0 1.0

getHours() Returns the hour of the Date object (from 0-23) 2.0 3.0 1.0

getMinutes() Returns the minute of the Date object (from 0-59) 2.0 3.0 1.0

getSeconds() Returns the second of the Date object (from 0-59) 2.0 3.0 1.0
UNIT-III XML
What is XML?

XML is a markup language for documents containing structured information.

Structured information contains both content (words, pictures, etc.) and some indication of what role that
content plays (for example, content in a section heading has a different meaning from content in a
footnote, which means something different than content in a figure caption or content in a database table,
etc.). Almost all documents have some structure.

A markup language is a mechanism to identify structures in a document. The XML specification defines a
standard way to add markup to documents.

What's a Document?

The number of applications currently being developed that are based on, or make use of, XML documents
is truly amazing (particularly when you consider that XML is not yet a year old)! For our purposes, the
word "document" refers not only to traditional documents, like this one, but also to the myriad of other
XML "data formats". These include vector graphics, e-commerce transactions, mathematical equations,
object meta-data, server APIs, and a thousand other kinds of structured information.
So XML is Just Like HTML?

No. In HTML, both the tag semantics and the tag set are fixed. An <h1> is always a first level heading
and the tag <ati.product.code> is meaningless. The W3C, in conjunction with browser vendors and the
WWW community, is constantly working to extend the definition of HTML to allow new tags to keep
pace with changing technology and to bring variations in presentation (stylesheets) to the Web. However,
these changes are always rigidly confined by what the browser vendors have implemented and by the fact
that backward compatibility is paramount. And for people who want to disseminate information widely,
features supported by only the latest releases of Netscape and Internet Explorer are not useful.

XML specifies neither semantics nor a tag set. In fact XML is really a meta-language for describing
markup languages. In other words, XML provides a facility to define tags and the structural relationships
between them. Since there's no predefined tag set, there can't be any preconceived semantics. All of the
semantics of an XML document will either be defined by the applications that process them or by style
sheets.

So XML Is Just Like SGML?

No. Well, yes, sort of. XML is defined as an application profile of SGML. SGML is the Standard
Generalized Markup Language defined by ISO 8879. SGML has been the standard, vendor-independent
way to maintain repositories of structured documentation for more than a decade, but it is not well suited
to serving documents over the web (for a number of technical reasons beyond the scope of this article).
Defining XML as an application profile of SGML means that any fully conformant SGML system will be
able to read XML documents. However, using and understanding XML documents does not require a
system that is capable of understanding the full generality of SGML. XML is, roughly speaking, a
restricted form of SGML.

For technical purists, it's important to note that there may also be subtle differences between documents as
understood by XML systems and those same documents as understood by SGML systems. In particular,
treatment of white space immediately adjacent to tags may be different.

Why XML?

In order to appreciate XML, it is important to understand why it was created. XML was created so that
richly structured documents could be used over the web. The only viable alternatives, HTML and SGML,
are not practical for this purpose.

HTML, as we've already discussed, comes bound with a set of semantics and does not provide arbitrary
structure.

SGML provides arbitrary structure, but is too difficult to implement just for a web browser. Full SGML
systems solve large, complex problems that justify their expense. Viewing structured documents sent over
the web rarely carries such justification.

This is not to say that XML can be expected to completely replace SGML. While XML is being designed
to deliver structured content over the web, some of the very features it lacks to make this practical, make
SGML a more satisfactory solution for the creation and long-time storage of complex documents. In
many organizations, filtering SGML to XML will be the standard procedure for web delivery.
XML Development Goals

The XML specification sets out the following goals for XML,these are references to the W3C
Recommendation Extensible Markup Language (XML) 1.0. If you are interested in more technical detail
about a particular topic, please consult the specification)

1. It shall be straightforward to use XML over the Internet. Users must be able to view XML
documents as quickly and easily as HTML documents. In practice, this will only be possible
when XML browsers are as robust and widely available as HTML browsers, but the principle
remains.
2. XML shall support a wide variety of applications. XML should be beneficial to a wide variety of
diverse applications: authoring, browsing, content analysis, etc. Although the initial focus is on
serving structured documents over the web, it is not meant to narrowly define XML.
3. XML shall be compatible with SGML. Most of the people involved in the XML effort come from
organizations that have a large, in some cases staggering, amount of material in SGML. XML
was designed pragmatically, to be compatible with existing standards while solving the relatively
new problem of sending richly structured documents over the web.
4. It shall be easy to write programs that process XML documents. The colloquial way of expressing
this goal while the spec was being developed was that it ought to take about two weeks for a
competent computer science graduate student to build a program that can process XML
documents.
5. The number of optional features in XML is to be kept to an absolute minimum, ideally zero.
Optional features inevitably raise compatibility problems when users want to share documents
and sometimes lead to confusion and frustration.
6. XML documents should be human-legible and reasonably clear. If you don't have an XML
browser and you've received a hunk of XML from somewhere, you ought to be able to look at it
in your favorite text editor and actually figure out what the content means.
7. The XML design should be prepared quickly. Standards efforts are notoriously slow. XML was
needed immediately and was developed as quickly as possible.
8. The design of XML shall be formal and concise. In many ways a corollary to rule 4, it essentially
means that XML must be expressed in EBNF and must be amenable to modern compiler tools
andtechniques.
There are a number of technical reasons why the SGML grammar cannot be expressed in EBNF.
Writing a proper SGML parser requires handling a variety of rarely used and difficult to parse
language features. XML does not.
9. XML documents shall be easy to create. Although there will eventually be sophisticated editors to
create and edit XML content, they won't appear immediately. In the interim, it must be possible to
create XML documents in other ways: directly in a text editor, with simple shell and Perl scripts,
etc.
10. Terseness in XML markup is of minimal importance. Several SGML language features were
designed to minimize the amount of typing required to manually key in SGML documents. These
features are not supported in XML. From an abstract point of view, these documents are
indistinguishable from their more fully specified forms, but supporting these features adds a
considerable burden to the SGML parser (or the person writing it, anyway). In addition, most
modern editors offer better facilities to define shortcuts when entering text.

How Is XML Defined?

XML is defined by a number of related specifications:


Extensible Markup Language (XML) 1.0

Defines the syntax of XML. The XML specification is the primary focus of this article.

XML Pointer Language (XPointer) and XML Linking Language (XLink)

Defines a standard way to represent links between resources. In addition to simple links, like
HTML's <A> tag, XML has mechanisms for links between multiple resources and links between
read-only resources. XPointer describes how to address a resource; XLink describes how to
associate two or more resources.

Extensible Style Language (XSL)

Defines the standard style sheet language for XML.

As time goes on, additional requirements will be addressed by other specifications. Currently (Sep, 1998),
namespaces (dealing with tags from multiple tag sets), a query language (finding out what's in a document
or a collection of documents), and a schema language (describing the relationships between tags, DTDs in
XML) are all being actively pursued.

XML Attribute

XML Attributes are very similar to HTML attributes that you may already have a grasp of. An attribute
appears within the opening tag of an element.

XML Attribute Syntax

Unlike in HTML, XML requires that all XML attributes have a value. This means all attributes have to be
equal to something! Below is the correct way to create an attribute in XML.

XML Code:
<student active="true">
<name>Robert</name>
<grade>A+</grade>
</student>

The attribute active is valid because we set it to a value true. Here is an example of shorthand that is
sometimes used in HTML, but is not valid XML.

XML Code:
<student active>
<name>Robert</name>
<grade>A+</grade>
</student>

This XML attribute is wrong because it was not set to a value.


XML Attribute Quotation Usage

The types of quotes that you use around your attribute values is entirely up to you. Both the single quote
(') and the double quote (") are perfectly fine to use in your XML documents.

The only instance you might want to use one quotation over the other is if your attribute value contains a
quotation or apostrophe of its own. Below are a couple of real world examples.

XML Code:
<student nickname='Rob "The Dog"'>
<name>Robert</name>
<grade>A+</grade>
</student>

XML Code:
<student group="Pete's Pandas">
<name>Robert</name>
<grade>A+</grade>
</student>

Document Object Model (DOM)


The Document Object Model (DOM) is an application programming interface (API) for HTML and
XML documents. It defines the logical structure of documents and the way a document is accessed and
manipulated. In the DOM specification, the term "document" is used in the broad sense - increasingly,
XML is being used as a way of representing many different kinds of information that may be stored in
diverse systems, and much of this would traditionally be seen as data rather than as documents.
Nevertheless, XML presents this data as documents, and the DOM may be used to manage this data.

With the Document Object Model, programmers can build documents, navigate their structure, and add,
modify, or delete elements and content. Anything found in an HTML or XML document can be accessed,
changed, deleted, or added using the Document Object Model, with a few exceptions - in particular, the
DOM interfaces for the XML internal and external subsets have not yet been specified.

As a W3C specification, one important objective for the Document Object Model is to provide a standard
programming interface that can be used in a wide variety of environments and applications.

What the Document Object Model is

The DOM is a programming API for documents. It closely resembles the structure of the documents it
models. For instance, consider this table, taken from an HTML document:

<TABLE>
<TBODY>
<TR>
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</TBODY>
</TABLE>

The DOM represents this table like this:

DOM representation of the example table

In the DOM, documents have a logical structure which is very much like a tree; to be more precise, it is
like a "forest" or "grove", which can contain more than one tree. However, the DOM does not specify that
documents must be implemented as a tree or a grove, nor does it specify how the relationships among
objects be implemented. The DOM is a logical model that may be implemented in any convenient
manner. In this specification, we use the term structure model to describe the tree-like representation of a
document; we specifically avoid terms like "tree" or "grove" in order to avoid implying a particular
implementation. One important property of DOM structure models is structural isomorphism: if any two
Document Object Model implementations are used to create a representation of the same document, they
will create the same structure model, with precisely the same objects and relationships.

The Document Object Model currently consists of two parts, DOM Core and DOM HTML. The DOM
Core represents the functionality used for XML documents, and also serves as the basis for DOM HTML.
A compliant implementation of the DOM must implement all of the fundamental interfaces in the Core
chapter with the semantics as defined. Further, it must implement at least one of the HTML DOM and the
extended (XML) interfaces with the semantics as defined.

What is a DTD?

DTD stands for Document Type Definition.

XML lets applications share data easily. However, XML lets you make up your own set of tags. A DTD
defines the legal elements and their structure in an XML document.

Independent developers can agree to use a common DTD for exchanging XML data. Your application can
use this agreed upon DTD to verify the data it receives. The DTD can also be used to verify your own
data.

DTD standards are defined by the World Wide Web Consortium (W3C). The W3C site provides a
comprehensive reference of DTDs.

However, this tutorial focuses on Microsoft's implementation of the XML and DTDs. All examples
contained herein require Internet Explorer 5.0 or later.

Using a DTD in an XML Document

DTDs can be declared inline in your XML code or they can reference an external file.

This is an example of an internal DTD. You can open it in Explorer then select View | Source to view the
complete XML document with the DTD included.

<?xml version="1.0"?>
<!DOCTYPE message [
   <!ELEMENT message (to,from,subject,text)>
   <!ELEMENT to (#PCDATA)>
   <!ELEMENT from (#PCDATA)>
   <!ELEMENT subject (#PCDATA)>
   <!ELEMENT text (#PCDATA)>
]>
<message>
  <to>Dave</to>
  <from>Susan</from>
  <subject>Reminder</subject>
  <text>Don't forget to buy milk on the way home.</text>
</message>

Line 2 defines the <message> element as having the four child elements: <to>, <from>, <subject> and
<text>.

 <!ELEMENT message (to,from,subject,text)>

This line defines the <to> element to be of type PCDATA.

<!ELEMENT to (#PCDATA)>

Here is the same document with an external DTD reference:

 <?xml version="1.0"?>
<!DOCTYPE message SYSTEM "message.dtd">
<message>
  <to>Dave</to>
  <from>Susan</from>
  <subject>Reminder</subject>
  <text>Don't forget to buy milk on the way home.</text>
</message>

And here is the referenced DTD file. You can open it in Explorer and select View | Source as above.

 
<?xml version="1.0"?>
<!ELEMENT message (to,from,subject,text)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT subject (#PCDATA)>
<!ELEMENT text (#PCDATA)>

XML Components

Before talking further about DTDs, we should review some of the basic XML components.

 XML elements
An XML element is made up of a start and end tag with data in between. The tags describe the
data. The data is called the value of the element. Elements can have a value, child elements or
they can be empty (have no value).
For example, this XML element is a <director> element with the value "Bill Smith".

<director>Bill Smith</director>

 Attributes
An element can optionally contain one or more attributes in its start tag. An attribute is a name-
value pair separated by an equal sign (=). Attribute values must always be quoted.

<CITY ZIP="01085">Westfield</CITY>

ZIP="01085" is an attribute of the <CITY> element.

 Parsed character data - PCDATA


Like we said, elements have values. If a value has tags representing child elements, these tags
need to be expanded or parsed and handled as separate elements.

 Character data - CDATA


The value of an element is treated as a single item and is not expanded.

 Entities
Certain characters, like "<", have special meaning in XML. If you want to use these special
characters in your data you need a way to tell the XML parser not to interpret them as having
their normally meaning.

Entities are sets of characters that can be used to represent these special characters or other text.

Entity Special Character


&lt; <
&gt; >
&amp; &
&quot; "
&apos; '

To use "<" in your data, you would use the entity "&lt;" instead.

DTD Elements

In DTD, elements are declared using an element declaration with the following syntax:

 <!ELEMENT element-name (element-content)>

 Empty elements
Empty elements use the empty keyword. Move the mouse over the text for additional
information.
<!ELEMENT img (EMPTY)>

 Elements with data


If an element has data, you must specify the type of its data.

<!ELEMENT element-name (#CDATA)>


<!ELEMENT element-name (#PCDATA)>
<!ELEMENT element-name (ANY)>

Example:
<!ELEMENT message (#PCDATA)>

ANY can contain any type of data.


#CDATA is character type data.
#PCDATA is character data that must be parsed and expanded. If a #PCDATA section contains elements,
those elements must also be declared.

 Elements with children - Sequences


If an element has child elements, the child elements must be enumerated in the same order that
they appear in the document.

Using the message example:

<!ELEMENT element-name (child-element,child-element,...)>

Example:
<!ELEMENT message (to,from,subject,text)>

The child elements must also be declared. Here are their declarations:

<!ELEMENT message (to,from,subject,text)>


<!ELEMENT to (#CDATA)>
<!ELEMENT from (#CDATA)>
<!ELEMENT subject (#CDATA)>
<!ELEMENT text (#CDATA)>

 DOCTYPE definition
With an internal DTD, you need a DOCTYPE definition to indicate the DTD code.

<!DOCTYPE root-element [element declarations]>

Example:
<?xml version="1.0"?>
<!DOCTYPE message [
  <!ELEMENT message (to,from,subject,text)>
  <!ELEMENT to         (#CDATA)>
  <!ELEMENT from      (#CDATA)>
  <!ELEMENT subject (#CDATA)>
  <!ELEMENT text     (#CDATA)>
]>
<message>
  <to>Dave</to>
  <from>Susan</from>
  <subject>Reminder</subject>
  <text>Don't forget to buy milk on the way home.</text>
</message>

 Element instances
You can specify how many times an element can occur in a document.

Symbol Instances
none must occur exactly 1 time
* 0 or more times
+ 1 or more times
? Exactly 0 or 1 time

For example:

<!Element message (to+,from,subject?,text,#PCDATA)>

DTD Attribute Declaration

In DTD, attributes are declared using an ATTLIST declaration. An attribute declaration specifies the
associated element, the attribute, its type, and possibly its default value. Here are the syntax variations:

 <!ATTLIST element-name attribute-name attribute-type #DEFAULT  default-value>

<!ATTLIST element-name  attribute-name attribute-type #FIXED   fixed_value>

<!ATTLIST element-name attribute-name attribute-type (Val1|Val2|..) default_val>

<!ATTLIST element-name attribute-name attribute-type  #IMPLIED>  

<!ATTLIST element-name attribute-name attribute-type  #REQUIRED>


 Attribute type
Attributes can have these types:

Type Description
CDATA Character data
ENTITY An entity
ENTITIES List of entities data
ID Unique ID data
IDREF ID of another element
IDREFS List of IDs of other elements
NMTOKEN XML name data
NMTOKENS List of XML names
NOTATION Name of a notation
(val1|val2|...) List of values
xml: Predefined value

 Default values
Attribute default values can be:

Default Value Description


If no value exists in the XML data, the value specified in the DTD
#DEFAULT value
will be used
#FIXED value If another value exists in the XML data, an error will occur
#IMPLIED The value doesn't have to be supplied in the XML data.
#REQUIRED If the XML data doesn't have a value, an error will occur.

 DTD Examples
Here are some sample DTD statements. Move the mouse over the text for more information.

<!ATTLIST person gender CDATA #DEFAULT "male">


<!ATTLIST person gender CDATA #FIXED "male">
<!ATTLIST person gender CDATA #REQUIRED>
<!ATTLIST person gender CDATA #IMPLIED>
<!ATTLIST person gender (male|female) "male">

Here is an XML statement that will satisfy all of the above DTD statements.
<person gender="male">

This XML statement does not satisfy DTD rule 2 which requires a value of "male".

<person gender="female">

This XML statement fails DTD rule 5 because "unknown" is not an acceptable value.

<person gender="unknown">

DTD Entity Declaration

Recall, entities are variables that represent other values. The value of the entity is substituted for the
entity when the XML document is parsed.

Entities can be defined internally or externally to your DTD.

Internal declaration:
<!ENTITY entity-name entity-value>

Example:
<!ENTITY website "http://www.TheScarms.com">

External declaration:
<!ENTITY entity-name SYSTEM "entity-URL">

Example:
<!ENTITY website SYSTEM "http://www.TheScarms.com/entity.xml">

The above entity make this line of XML valid.

 XML line:
<url>&website</url>

Evaluates to:
<url>http://www.TheScarms.com</url>
 XML Namespaces

2.1 Basic Concepts

Definition: An XML namespace is identified by a URI reference; element and attribute names may be
placed in an XML namespace using the mechanisms described in this specification.
Definition: An expanded name is a pair consisting of a namespace name and a local name. Definition:
For a name N in a namespace identified by a URI I, the namespace name is I. For a name N that is not in
a namespace, the namespace name has no value. ] [Definition: In either case the local name is N. ] It is
this combination of the universally managed IRI namespace with the vocabulary's local names that is
effective in avoiding name clashes.

URI references can contain characters not allowed in names, and are often inconveniently long, so
expanded names are not used directly to name elements and attributes in XML documents. Instead
qualified names are used. [Definition: A qualified name is a name subject to namespace interpretation. ]
In documents conforming to this specification, element and attribute names appear as qualified names.
Syntactically, they are either prefixed names or unprefixed names. An attribute-based declaration syntax
is provided to bind prefixes to namespace names and to bind a default namespace that applies to
unprefixed element names; these declarations are scoped by the elements on which they appear so that
different bindings may apply in different parts of a document. Processors conforming to this specification
MUST recognize and act on these declarations and prefixes.

Declaring Namespaces

Definition: A namespace (or more precisely, a namespace binding) is declared using a family of reserved
attributes. Such an attribute's name must either be xmlns or begin xmlns:. These attributes, like any other
XML attributes, may be provided directly or by default.

Attribute Names for Namespace Declaration

[1]    NSAttName    ::=    PrefixedAttName

| DefaultAttName

[2]    PrefixedAttName    ::=    'xmlns:' NCName [NSC: Reserved Prefixes and Namespace
Names]

[3]    DefaultAttName    ::=    'xmlns'

[4]    NCName    ::=    NCNameStartChar /* An XML Name, minus the ":" */


NCNameChar*

[5]    NCNameChar    ::=    NameChar - ':'

[6]    NCNameStartChar    ::=    Letter | '_'

The attribute's normalized value MUST be either a URI reference — the namespace name identifying the
namespace — or an empty string. The namespace name, to serve its intended purpose, SHOULD have the
characteristics of uniqueness and persistence. It is not a goal that it be directly usable for retrieval of a
schema (if any exists).

Definition: If the attribute name matches PrefixedAttName, then the NCName gives the namespace
prefix, used to associate element and attribute names with the namespace name in the attribute value in
the scope of the element to which the declaration is attached. In such declarations, the namespace name
may not be empty. ]
Definition: If the attribute name matches DefaultAttName, then the namespace name in the attribute value
is that of the default namespace in the scope of the element to which the declaration is attached.] Default
namespaces and overriding of declarations are discussed in Applying Namespaces to Elements and
Attributes.

An example namespace declaration, which associates the namespace prefix edi with the namespace name
http://ecommerce.example.org/schema:

<x xmlns:edi='http://ecommerce.example.org/schema'>
<!-- the "edi" prefix is bound to http://ecommerce.example.org/schema
for the "x" element and contents -->
</x>

Namespace constraint: Reserved Prefixes and Namespace Names

The prefix xml is by definition bound to the namespace name http://www.w3.org/XML/1998/namespace.


It MAY, but need not, be declared, and MUST NOT be bound to any other namespace name. Other
prefixes MUST NOT be bound to this namespace name, and it MUST NOT be declared as the default
namespace.

The prefix xmlns is used only to declare namespace bindings and is by definition bound to the namespace
name http://www.w3.org/2000/xmlns/. It MUST NOT be declared . Other prefixes MUST NOT be bound
to this namespace name, and it MUST NOT be declared as the default namespace. Element names MUST
NOT have the prefix xmlns.

All other prefixes beginning with the three-letter sequence x, m, l, in any case combination, are reserved.
This means that:

users SHOULD NOT use them except as defined by later specifications

processors MUST NOT treat them as fatal errors.

Though they are not themselves reserved, it is inadvisable to use prefixed names whose LocalPart begins
with the letters x, m, l, in any case combination, as these names would be reserved if used without a
prefix.

Qualified Names

In XML documents conforming to this specification, some names (constructs corresponding to the
nonterminal Name) MUST be given as qualified names, defined as follows:

Qualified Name
[7]    QName    ::=    PrefixedName

| UnprefixedName

[8]    PrefixedName    ::=    Prefix ':' LocalPart

[9]    UnprefixedName    ::=    LocalPart


[10]    Prefix    ::=    NCName

[11]    LocalPart    ::=    NCName

The Prefix provides the namespace prefix part of the qualified name, and MUST be associated with a
namespace URI reference in a namespace declaration. [Definition: The LocalPart provides the local part
of the qualified name.]

Note that the prefix functions only as a placeholder for a namespace name. Applications SHOULD use the
namespace name, not the prefix, in constructing names whose scope extends beyond the containing
document.

Using Qualified Names

In XML documents conforming to this specification, element names are given as qualified names, as
follows:

Element Names
[12]    STag    ::=    '<' QName (S Attribute)* S? '>' [NSC: Prefix Declared]

[13]    ETag    ::=    '</' QName S? '>' [NSC: Prefix Declared]

[14]    EmptyElemTag    ::=    '<' QName (S Attribute)* S? '/>' [NSC: Prefix Declared]

An example of a qualified name serving as an element name:

<!-- the 'price' element's namespace is http://ecommerce.example.org/schema -->


<edi:price xmlns:edi='http://ecommerce.example.org/schema' units='Euro'>32.18</edi:price>

Attributes are either namespace declarations or their names are given as qualified names:

Attribute
[15]    Attribute    ::=    NSAttName Eq AttValue

| QName Eq AttValue [NSC: Prefix Declared]

An example of a qualified name serving as an attribute name:

<x xmlns:edi='http://ecommerce.example.org/schema'>
<!-- the 'taxClass' attribute's namespace is http://ecommerce.example.org/schema -->
<lineItem edi:taxClass="exempt">Baby food</lineItem>
</x>
Namespace constraint: Prefix Declared

The namespace prefix, unless it is xml or xmlns, MUST have been declared in a namespace declaration
attribute in either the start-tag of the element where the prefix is used or in an ancestor element (i.e. an
element in whose content the prefixed markup occurs).

This constraint may lead to operational difficulties in the case where the namespace declaration attribute
is provided, not directly in the XML document entity, but via a default attribute declared in an external
entity. Such declarations may not be read by software which is based on a non-validating XML processor.
Many XML applications, presumably including namespace-sensitive ones, fail to require validating
processors. If correct operation with such applications is required, namespace declarations MUST be
provided either directly or via default attributes declared in the internal subset of the DTD.

Element names and attribute names are also given as qualified names when they appear in declarations in
the DTD:

Qualified Names in Declarations


[16]    doctypedecl    ::=    '<!DOCTYPE' S QName (S ExternalID)? S? ('[' (markupdecl | PEReference |
S)* ']' S?)? '>'

[17]    elementdecl    ::=    '<!ELEMENT' S QName S contentspec S? '>'

[18]    cp    ::=    (QName | choice | seq) ('?' | '*' | '+')?

[19]    Mixed    ::=    '(' S? '#PCDATA' (S? '|' S? QName)* S? ')*'

| '(' S? '#PCDATA' S? ')'

[20]    AttlistDecl    ::=    '<!ATTLIST' S QName AttDef* S? '>'

[21]    AttDef    ::=    S (QName | NSAttName) S AttType S DefaultDecl

Note that DTD-based validation is not namespace-aware in the following sense: a DTD constrains the
elements and attributes that may appear in a document by their uninterpreted names, not by (namespace
name, local name) pairs. To validate a document that uses namespaces against a DTD, the same prefixes
must be used in the DTD as in the instance. A DTD may however indirectly constrain the namespaces
used in a valid document by providing #FIXED values for attributes that declare namespaces.

Applying Namespaces to Elements and Attributes

Namespace Scoping

The scope of a namespace declaration declaring a prefix extends from the beginning of the start-tag in
which it appears to the end of the corresponding end-tag, excluding the scope of any inner declarations
with the same NSAttName part. In the case of an empty tag, the scope is the tag itself.

Such a namespace declaration applies to all element and attribute names within its scope whose prefix
matches that specified in the declaration.
The expanded name corresponding to a prefixed element or attribute name has the URI to which the
prefix is bound as its namespace name, and the local part as its local name.

<?xml version="1.0"?>

<html:html xmlns:html='http://www.w3.org/1999/xhtml'>

<html:head><html:title>Frobnostication</html:title></html:head>
<html:body><html:p>Moved to
<html:a href='http://frob.example.com'>here.</html:a></html:p></html:body>
</html:html>

Multiple namespace prefixes can be declared as attributes of a single element, as shown in this example:

<?xml version="1.0"?>
<!-- both namespace prefixes are available throughout -->
<bk:book xmlns:bk='urn:loc.gov:books'
xmlns:isbn='urn:ISBN:0-395-36341-6'>
<bk:title>Cheaper by the Dozen</bk:title>
<isbn:number>1568491379</isbn:number>
</bk:book>
What is an XML Schema?

The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a
DTD.

An XML Schema:

 defines elements that can appear in a document


 defines attributes that can appear in a document
 defines which elements are child elements
 defines the order of child elements
 defines the number of child elements
 defines whether an element is empty or can include text
 defines data types for elements and attributes
 defines default and fixed values for elements and attributes

XML Schema Example


<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<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>

XML Schema is an XML-based alternative to DTD.

An XML schema describes the structure of an XML document.

The XML Schema language is also referred to as XML Schema Definition (XSD).

XML Schemas are the Successors of DTDs

We think that very soon XML Schemas will be used in most Web applications as a replacement for
DTDs. Here are some reasons:

 XML Schemas are extensible to future additions


 XML Schemas are richer and more powerful than DTDs
 XML Schemas are written in XML
 XML Schemas support data types
 XML Schemas support namespaces

XML Schemas are much more powerful than DTDs.

XML Schemas Support Data Types

One of the greatest strength of XML Schemas is the support for data types.

With support for 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 data facets (restrictions on data)
 It is easier to define data patterns (data formats)
 It is easier to convert data between different data types

XML Schemas use XML Syntax

Another great strength about XML Schemas is that they are written in XML.

Some benefits of that XML Schemas are written in XML:


 You don't have to learn a new language
 You can use your XML editor to edit your Schema files
 You can use your XML parser to parse your Schema files
 You can manipulate your Schema with the XML DOM
 You can transform your Schema with XSLT

XML Schemas Secure Data Communication

When sending data from a sender to a receiver, it is essential that both parts have the same "expectations"
about the content.

With XML Schemas, the sender can describe the data in a way that the receiver will understand.

A date like: "03-11-2004" will, in some countries, be interpreted as 3.November and in other countries as
11.March.

However, an XML element with a data type like this:

<date type="date">2004-03-11</date>

ensures a mutual understanding of the content, because the XML data type "date" requires the format
"YYYY-MM-DD".

XML Schemas are Extensible

XML Schemas are extensible, because they are written in XML.

With an extensible Schema definition you can:

 Reuse your Schema in other Schemas


 Create your own data types derived from the standard types
 Reference multiple schemas in the same document

Well-Formed is not Enough

A well-formed XML document is a document that conforms to the XML syntax rules, like:

it must begin with the XML declaration

 it must have one unique root element


 start-tags must have matching end-tags
 elements are case sensitive
 all elements must be closed
 all elements must be properly nested
 all attribute values must be quoted
 entities must be used for special characters

Even if documents are well-formed they can still contain errors, and those errors can have serious
consequences.
Think of the following situation: you order 5 gross of laser printers, instead of 5 laser printers. With XML
Schemas, most of these errors can be caught by your validating software.

XML documents can have a reference to a DTD or to an XML Schema.

A Simple XML Document

Look at this simple XML document called "note.xml":

<?xml version="1.0"?>
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

A DTD File

The following example is a DTD file called "note.dtd" that defines the elements of the XML document
above ("note.xml"):

<!ELEMENT note (to, from, heading, body)>


<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

The first line defines the note element to have four child elements: "to, from, heading, body".

Line 2-5 defines the to, from, heading, body elements to be of type "#PCDATA".

An XML Schema

The following example is an XML Schema file called "note.xsd" that defines the elements of the XML
document above ("note.xml"):

<?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>

The note element is a complex type because it contains other elements. The other elements (to, from,
heading, body) are simple types because they do not contain other elements. You will learn more about
simple and complex types in the following chapters.

A Reference to a DTD

This XML document has a reference to a 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>

A Reference to an XML Schema

This XML document has a reference to an 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>

In computing, the term Extensible Stylesheet Language (XSL) is used to refer to a family of languages
used for transforming and rendering XML documents.

Historically, the XSL Working Group in W3C produced a draft specification under the name XSL, which
eventually split into three parts:

1. XSL Transformations (XSLT): an XML language for transforming XML documents


2. XSL Formatting Objects (XSL-FO): an XML language for specifying the visual formatting of an
XML document
3. the XML Path Language (XPath): a non-XML language used by XSLT, and also available for use
in non-XSLT contexts, for addressing the parts of an XML document.

As a result, the term XSL is now used with a number of different meanings:

 Sometimes it refers to XSLT: this usage is best avoided. However, "xsl" is used both as the
conventional namespace prefix for the XSLT namespace, and as the conventional filename suffix
for files containing XSLT stylesheet modules
 Sometimes it refers to XSL-FO: this usage can be justified by the fact that the XSL-FO
specification carries the title Extensible Stylesheet Language (XSL); however, the term XSL-FO is
less likely to be misunderstood
 Sometimes it refers to both languages considered together, or to the working group which
develops both languages
 Sometimes, especially in the Microsoft world, it refers to a now-obsolete variant of XSLT
developed and shipped by Microsoft as part of MSXML before the W3C specification was
finalized

XML processing with SAX:


SAX (Simple API for XML) is a serial access parser API for XML. SAX provides a mechanism for
reading data from an XML document. It is a popular alternative to the Document Object Model (DOM).

A parser which implements SAX (ie, a SAX Parser) functions as a stream parser, with an event-driven
API. The user defines a number of callback methods that will be called when events occur during parsing.
The SAX events include:

 XML Text nodes


 XML Element nodes
 XML Processing Instructions
 XML Comments

Events are fired when each of these XML features are encountered, and again when the end of them is
encountered. XML attributes are provided as part of the data passed to element events.

SAX parsing is unidirectional; previously parsed data cannot be re-read without starting the parsing
operation again.

Example

Given the following XML document:

<?xml version="1.0" encoding="UTF-8"?>


<RootElement param="value">
<FirstElement>
Some Text
</FirstElement>
<SecondElement param2="something">
Pre-Text <Inline>Inlined text</Inline> Post-text.
</SecondElement>
</RootElement>

This XML document, when passed through a SAX parser, will generate a sequence of events like the
following:

 XML Processing Instruction, named xml, with attributes version equal to "1.0" and encoding
equal to "UTF-8"
 XML Element start, named RootElement, with an attribute param equal to "value"
 XML Element start, named FirstElement
 XML Text node, with data equal to "Some Text" (note: text processing, with regard to spaces,
can be changed)
 XML Element end, named FirstElement
 XML Element start, named SecondElement, with an attribute param2 equal to "something"
 XML Text node, with data equal to "Pre-Text"
 XML Element start, named Inline
 XML Text node, with data equal to "Inlined text"
 XML Element end, named Inline
 XML Text node, with data equal to "Post-text."
 XML Element end, named SecondElement
 XML Element end, named RootElement

In fact, this may vary: the SAX specification deliberately states that a given section of text may be
reported as multiple sequential text events. Thus in the example above, a SAX parser may generate a
different series of events, part of which might include:

 XML Element start, named FirstElement


 XML Text node, with data equal to "Some "
 XML Text node, with data equal to "Text"
 XML Element end, named FirstElement

Definition

Unlike DOM, there is no formal specification for SAX. The Java implementation of SAX is considered to
be normative and implementations in other languages attempt to follow the rules laid down in that
implementation, adjusting for the differences in language where necessary.

Benefits

SAX parsers have certain benefits over DOM-style parsers. The quantity of memory that a SAX parser
must use in order to function is typically much smaller than that of a DOM parser. DOM parsers must
have the entire tree in memory before any processing can begin, so the amount of memory used by a
DOM parser depends entirely on the size of the input data. The memory footprint of a SAX parser, by
contrast, is based only on the maximum depth of the XML file (the maximum depth of the XML tree) and
the maximum data stored in XML attributes on a single XML element. Both of these are always smaller
than the size of the parsed tree itself.
Because of the event-driven nature of SAX, processing documents can often be faster than DOM-style
parsers. Memory allocation takes time, so the larger memory footprint of the DOM is also a performance
issue.

Due to the nature of DOM, streamed reading from disk is impossible. Processing XML documents larger
than main memory is also impossible with DOM parsers but can be done with SAX parsers. However,
DOM parsers may make use of disk space as memory to side step this limitation.

Drawbacks

The event-driven model of SAX is useful for XML parsing, but it does have certain drawbacks.

Certain kinds of XML validation require access to the document in full. For example, a DTD IDREF
attribute requires that there be an element in the document that uses the given string as a DTD ID
attribute. To validate this in a SAX parser, one would need to keep track of every previously encountered
ID attribute and every previously encountered IDREF attribute, to see if any matches are made.
Furthermore, if an IDREF does not match an ID, the user only discovers this after the document has been
parsed; if this linkage was important to building functioning output, then time has been wasted in
processing the entire document only to throw it away.

UNIT-IV JAVA BEANS


JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool.
Practically, they are classes written in the Java programming language conforming to a particular
convention.

JavaBeans Concepts

The JavaBeans™ architecture is based on a component model which enables developers to create
software units called components. Components are self-contained, reusable software units that can be
visually assembled into composite components, applets, applications, and servlets using visual application
builder tools. JavaBean components are known as beans.

A set of APIs describes a component model for a particular language. The JavaBeans API specification
describes the core detailed elaboration for the JavaBeans component architecture.

Beans are dynamic in that they can be changed or customized. Through the design mode of a builder tool
you can use the Properties window of the bean to customize the bean and then save (persist) your beans
using visual manipulation. You can select a bean from the toolbox, drop it into a form, modify its
appearance and behavior, define its interaction with other beans, and combine it and other beans into an
applet, application, or a new bean.

The following list briefly describes key bean concepts.

 Builder tools discover a bean's features (that is, its properties, methods, and events) by a process
known as introspection. Beans support introspection in two ways:
o By adhering to specific rules, known as design patterns, when naming bean features. The
Introspector class examines beans for these design patterns to discover bean features. The
Introspector class relies on the core reflection API. The trail The Reflection API is an
excellent place to learn about reflection.
o By explicitly providing property, method, and event information with a related bean
information class. A bean information class implements the BeanInfo interface. A
BeanInfo class explicitly lists those bean features that are to be exposed to application
builder tools.
 Properties are the appearance and behavior characteristics of a bean that can be changed at design
time. Builder tools introspect on a bean to discover its properties and expose those properties for
manipulation.
 Beans expose properties so they can be customized at design time. Customization is supported in
two ways: by using property editors, or by using more sophisticated bean customizers.
 Beans use events to communicate with other beans. A bean that is to receive events (a listener
bean) registers with the bean that fires the event (a source bean). Builder tools can examine a
bean and determine which events that bean can fire (send) and which it can handle (receive).
 Persistence enables beans to save and restore their state. After changing a bean's properties, you
can save the state of the bean and restore that bean at a later time with the property changes intact.
The JavaBeans architecture uses Java Object Serialization to support persistence.
 A bean's methods are no different from Java methods, and can be called from other beans or a
scripting environment. By default all public methods are exported.

Beans vary in functionality and purpose. You have probably met some of the following beans in your
programming practice:

 GUI (graphical user interface)


 Non-visual beans, such as a spelling checker
 Animation applet
 Spreadsheet application

Using the NetBeans GUI Builder


his lesson explains how to use the NetBeans IDE GUI Builder to work with beans. In preparation for
working with the GUI Builder, you should be first familiar with the key NetBeans concepts which are
explained in the NetBeans IDE Java Quick Start Tutorial.

This lesson guides you through the process of creating a bean pattern in the NetBeans projects, introduces
the user interface of the GUI Builder, and explains how to add your bean object to the palette.

Creating a New Project

In the NetBeans IDE, you always work in a project where you store sources and files. To create a new
project, perform the following steps:

1. Select New Project from the File menu. You can also click the New Project button in the IDE
toolbar.
2. In the Categories pane, select the General node. In the Projects pane, choose the Java Application
type. Click the Next button.
3. Enter MyBean in the Project Name field and specify the project location. Do not create a Main
class here, because later you will create a new Java class in this project.
4. Click the Finish button.

This figure represents the expanded MyBean node in the Projects list.

Creating a New Form

After creating a new project, the next step is to create a form within which the JavaBeans components and
other required GUI components, will be placed.

To create a new form, perform the following sequence of actions:

1. In the Projects list, expand the MyBean node, right-click on the <default package> node and
choose New|JFrame Form from the pop-up menu.
2. Enter MyForm as the Class Name.
3. Click the Finish button.

The IDE creates the MyForm form and the MyForm class within the MyBean application and opens the
MyForm form in the GUI Builder.

This figure represents the Projects list, where the MyForm class is located.
The GUI Builder Interface

When the JFrame form is added to your application, the IDE opens the newly-created form in an Editor
tab with a toolbar containing the following buttons:

 – Selection Mode enables you to select one or more objects in the Design Area.
 – Connection Mode enables you to set a connection between objects by specifying an event.
 – Preview Design enables you to preview the form layout.
 – Align commands enable you to align selected objects.
 Change Resizability enables you to set up vertical and horizontal resizing.

When the MyForm form opens in the GUI Builder's Design view, three additional windows appear,
enabling you to navigate, organize, and edit GUI forms. These windows include the following:

 Design Area. The primary window for creating and editing Java GUI forms. Source and Design
toggle buttons enable you to switch between view a class's source code and a graphical view of
the GUI components. Click on an object to select it in the Design Area. For a multiple selection,
hold down the Ctrl key while clicking on objects.
 Inspector. Representation of a tree hierarchy of all the components in your application. The
Inspector highlights the component in the tree that is currently being edited.
 Palette. A customizable list of available components containing groups for Swing, AWT,
Borders, and Beans components. This window enables you to create, remove, and rearrange the
categories displayed in the palette using the customizer.
 Properties Window. A display of the properties of the component currently selected in the GUI
Builder, Inspector window, Projects window, or Files window.

If you click the Source button, the IDE displays the application's Java source code in the editor. Sections
of code that are automatically generated by the GUI Builder are indicated by blue areas. These blue areas
are protected from editing in the Source view. You can only edit code appearing in the white areas of the
editor when in Source view. When you make your changes in the Design View, the IDE updates the file's
sources.

Creating a Bean

To create your own bean object and add it to the palette for the bean group, execute the following
procedure:

1. Select the <default package> node in the MyBean project.


2. Choose New|Java Class from the pop-up menu.
3. Specify the name for the new class, for example, MyBean, then press the Finish button.
4. Open the MyBean.java file.
5. In the editor window, select inside the class. Right-click and choose Insert Code. Then select Add
Property.
6. In the Name field of the Add Property dialog box, type YourName and press OK.

7. Now you can analyze the automatically generated code. Notice that set and get methods were
included:
8. public class MyBean {
9.
10. /** Creates a new instance of MyBean */
11. public MyBean() {
12. }
13.
14. /**
15. * Holds value of property yourName.
16. */
17. private String yourName;
18.
19. /**
20. * Getter for property yourName.
21. * @return Value of property yourName.
22. */
23. public String getYourName() {
24. return this.yourName;
25. }
26.
27. /**
28. * Setter for property yourName.
29. * @param yourName New value of property yourName.
30. */
31. public void setYourName(String yourName) {
32. this.yourName = yourName;
33. }
34.
35. }
36. Right-click the MyBean node in the MyBean project tree and choose Tools |Add to Palette from
the pop-up menu.
37. Select the Beans group in the Palette tree to add your bean.

Now you can switch to the Palette window by choosing Palette from the Windows menu and make sure
that the MyBean component was added to the Beans group.

So far you have created a bean, set the YourName property, and added this bean as a component to the
palette.

Adding Components to the Form


Now you can use the Free Design of the GUI Builder and add the MyBean component and other standard
Swing components to MyForm.

1. Select the MyForm node in the project tree.


2. Drag the JLabel Swing component from the Palette window to the Design Area. Double-click the
component and change the text property to "Enter your name:".
3. Drag the JTextField component from the Palette window to the Design Area. Double-click the
component and empty the text field.
4. Drag the JButton component from the Palette window to the Design Area. Double-click the
component and enter "OK" as the text property.
5. Add another button and enter "Cancel" as its text property.
6. Align components by using the appropriate align commands.
7. Before you drag the MyBean component from the Pallete you must compile your project because
the MyBean component is non-visual and cannot be operated as a visual component. When you
Drag and Drop the MyBean component it will not appear in the Design Area. However, you can
view it in the Inspector window by expanding the Other Components node, as shown in the
following figure.

8.

To summarize, in the previous steps you created a project, developed a JFrame form, added a bean object
and included it in your project as a non-visual component. Later in this trail you will learn how to change
properties for the bean component and handle events by using the NetBeans GUI Builder.

Writing a Simple Bean

In this section you will learn more about beans by performing the following actions:

 Creating a simple bean


 Compiling the bean
 Generating a Java Archive (JAR) file
 Loading the bean into the GUI Builder of the NetBeans IDE
 Inspecting the bean's properties and events

Your bean will be named SimpleBean. Here are the steps to create it:

1. Write the SimpleBean code. Put it in a file named SimpleBean.java, in the directory of your choice.
Here's the code:
2. import java.awt.Color;
3. import java.beans.XMLDecoder;
4. import javax.swing.JLabel;
5. import java.io.Serializable;
6.
7. public class SimpleBean extends JLabel
8. implements Serializable {
9. public SimpleBean() {
10. setText( "Hello world!" );
11. setOpaque( true );
12. setBackground( Color.RED );
13. setForeground( Color.YELLOW );
14. setVerticalAlignment( CENTER );
15. setHorizontalAlignment( CENTER );
16. }
17. }

SimpleBean extends the javax.swing.JLabel graphic component and inherits its properties, which makes
the SimpleBean a visual component. SimpleBean also implements the java.io.Serializable interface. Your
bean may implement either the Serializable or the Externalizable interface.

18. Create a manifest, the JAR file, and the class file SimpleBean.class. Use the Apache Ant tool to
create these files. Apache Ant is a Java-based build tool that enables you to generate XML-based
configurations files as follows:
19. <?xml version="1.0" encoding="ISO-8859-1"?>
20.
21. <project default="build">
22.
23. <dirname property="basedir" file="${ant.file}"/>
24.
25. <property name="beanname" value="SimpleBean"/>
26. <property name="jarfile" value="${basedir}/${beanname}.jar"/>
27.
28. <target name="build" depends="compile">
29. <jar destfile="${jarfile}" basedir="${basedir}" includes="*.class">
30. <manifest>
31. <section name="${beanname}.class">
32. <attribute name="Java-Bean" value="true"/>
33. </section>
34. </manifest>
35. </jar>
36. </target>
37.
38. <target name="compile">
39. <javac destdir="${basedir}">
40. <src location="${basedir}"/>
41. </javac>
42. </target>
43.
44. <target name="clean">
45. <delete file="${jarfile}">
46. <fileset dir="${basedir}" includes="*.class"/>
47. </delete>
48. </target>
49.
50. </project>

It is recommended to save an XML script in the build.xml file, because Ant recognizes this file name
automatically.

Load the JAR file. Use the NetBeans IDE GUI Builder to load the jar file as follows:
1. Start NetBeans.
2. From the File menu select "New Project" to create a new application for your bean. You
can use "Open Project" to add your bean to an existing application.
3. Create a new application using the New Project Wizard.
4. Select a newly created project in the List of Projects, expand the Source Packages node,
and select the Default Package element.
5. Click the right mouse button and select New|JFrameForm from the pop-up menu.
6. Select the newly created Form node in the Project Tree. A blank form opens in the GUI
Builder view of an Editor tab.
7. Open the Palette Manager for Swing/AWT components by selecting Palette Manager in
the Tools menu.
8. In the Palette Manager window select the beans components in the Palette tree and press
the "Add from JAR" button.
9. Specify a location for your SimpleBean JAR file and follow the Add from JAR Wizard
instructions.
10. Select the Palette and Properties options from the Windows menu.
11. Expand the beans group in the Palette window. The SimpleBean object appears. Drag the
SimpleBean object to the GUI Builder panel.

The following figure represents the SimpleBean object loaded in the GUI Builder panel:

Inspect Properties and Events. The SimpleBean properties will appear in the Properties window. For
example, you can change a background property by selecting another color. To preview your form, use
the Preview Design button of the GUI Builder toolbar. To inspect events associated with the
SimpleBean object, switch to the Events tab of the Properties window. You will learn more about bean
properties and events in the lessons that follow.
Properties

In the following sections you will learn how to implement bean properties. A bean property is a named
attribute of a bean that can affect its behavior or appearance. Examples of bean properties include color,
label, font, font size, and display size.

The JavaBeans™ specification defines the following types of bean properties:

 Simple – A bean property with a single value whose changes are independent of changes in any
other property.
 Indexed – A bean property that supports a range of values instead of a single value.
 Bound – A bean property for which a change to the property results in a notification being sent to
some other bean.
 Constrained – A bean property for which a change to the property results in validation by another
bean. The other bean may reject the change if it is not appropriate.

Bean properties can also be classified as follows:

 Writable – A bean property that can be changed


o Standard
o Expert
o Preferred
 Read Only – A bean property that cannot be changed.
 Hidden – A bean property that can be changed. However, these properties are not disclosed with
the BeanInfo class

BeanBuilder uses this schema to group and represent properties in the Properties window

Manipulating Events

Event passing is the means by which components communicate with each other. Components broadcast
events, and the underlying framework delivers the events to the components that are to be notified. The
notified components usually perform some action based on the event that took place.

The event model was designed to accommodate the JavaBeans™ architecture. To understand how events
and event handling work in the JavaBeans component model, you must understand the concepts of events,
listeners, and sources. To refresh your knowledge in these areas, read the Writing Event Listeners lesson
of the Swing tutorial.

The event model that is used by the JavaBeans architecture is a delegation model. This model is
composed of three main parts: sources, events, and listeners.

The source of an event is the object that originates or fires the event. The source must define the events it
will fire, as well as the methods for registering listeners of those events. A listener is an object that
indicates that it is to be notified of events of a particular type. Listeners register for events using the
methods defined by the sources of those events.

From the Properties lesson you discovered two event listeners. The PropertyChangeListener(in the API
reference documentation) interface provides a notification whenever a bound property value is changed
and the VetoableChangeListener(in the API reference documentation) creates a notification whenever a
bean changes a constrained property value.

Simple Event Example


This example represents an application that performs an action when a button is clicked. Button
components are defined as sources of an event type called ActionEvent(in the API reference
documentation). Listeners of events of this type must register for these events using the
addActionListener method.

Therefore, the addActionListener method is used to register the ButtonHandler object as a listener of the
ActionEvent event that is fired by the button.

In addition, according to the requirements of the ActionListener class, you must define an
actionPerformed method, which is the method that is called when the button is clicked.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class ButtonHandler implements ActionListener {


/**
* Component that will contain messages about
* events generated.
*/
private JTextArea output;
/**
* Creates an ActionListener that will put messages in
* JTextArea everytime event received.
*/
public ButtonHandler( JTextArea output )
{
this.output = output;
}

/**
* When receives action event notification, appends
* message to the JTextArea passed into the constructor.
*/
public void actionPerformed( ActionEvent event )
{
this.output.append( "Action occurred: " + event + '\n' );
}
}

class ActionTester {
public static void main(String args[]) {
JFrame frame = new JFrame( "Button Handler" );
JTextArea area = new JTextArea( 6, 80 );
JButton button = new JButton( "Fire Event" );
button.addActionListener( new ButtonHandler( area ) );
frame.add( button, BorderLayout.NORTH );
frame.add( area, BorderLayout.CENTER );
frame.pack();
frame.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}

Using Introspection to Discover the Events A Bean Fires

The JavaBeans API provides event-oriented design patterns to give introspecting tools the ability to
discover what events a bean can fire. For a bean to be the source of an event, it must implement methods
that add and remove listener objects for that type of event. The design patterns for these methods are the
following:

public void add<EventListenerType>(<EventListenerType> a)


public void remove<EventListenerType>(<EventListenerType> a)
These methods let a source bean know where to fire events. The source bean then fires events at those
listener beans using the methods for those particular interfaces. For example, if a source bean registers
ActionListener objects, it will fire events at those objects by calling the actionPerformed method on those
listeners.

package java.awt.event;
import java.util.EventListener;

public interface ActionListener extends EventListener {

public void actionPerformed(ActionEvent e);


}

Using the NetBeans GUI Builder to Set Events

In the lesson "Using the NetBeans GUI Builder," you learned how to create a MyBean component, add
the yourName property, and design a simple form. Now you will set an event by which a value entered in
the JTextField component is stored in the yourName property. Use the GUI Builder as follows to set such
an event:

1. Left click the MyForm node.


2. Switch to the Connection Mode by clicking the appropriate button on the GUI Builder toolbar.
3. In the Design Area or Inspector window select the OK button (jButton1). Notice that the button is
highlighted in red when it is selected.
4. In the Inspector window select the myBean1 component.
5. In the Connection wizard's Select Source Event page, select the action|
actionPerformed[jButton1ActionPerformed1] event by expanding the event type directory nodes,
as represented in the following figure.

6. Click the Next button.


7. In the Specify Target Operation page, specify the yourName property in the MyBean component,
and click the Next button.
8. In the Enter Parameters page, specify the target property by selecting the Property radio button.
9. Press the ellipsis (...) button to display the Select Property dialog box.
10. In the Select Property dialog box select the jTextField component from the Component
combobox and choose the text property from the list that is presented, as shown on the following
figure.

11. Click the Finish button.

The Source Editor window is now displayed. Since the GUI Builder automatically generates the code to
connect the form's components, the following code will be added to the MyForm class:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
myBean1.setYourName(jTextField1.getText());
}
Bean Persistence

A bean has the property of persistence when its properties, fields, and state information are saved to and
retrieved from storage. Component models provide a mechanism for persistence that enables the state of
components to be stored in a non-volatile place for later retrieval.

The mechanism that makes persistence possible is called serialization. Object serialization means
converting an object into a data stream and writing it to storage. Any applet, application, or tool that uses
that bean can then "reconstitute" it by deserialization. The object is then restored to its original state.

For example, a Java application can serialize a Frame window on a Microsoft Windows machine, the
serialized file can be sent with e-mail to a Solaris machine, and then a Java application can restore the
Frame window to the exact state which existed on the Microsoft Windows machine.

Any applet, application, or tool that uses that bean can then "reconstitute" it by deserialization.

All beans must persist. To persist, your beans must support serialization by implementing either the
java.io.Serializable(in the API reference documentation) interface, or the java.io.Externalizable(in the
API reference documentation) interface. These interfaces offer you the choices of automatic serialization
and customized serialization. If any class in a class's inheritance hierarchy implements Serializable or
Externalizable, then that class is serializable.

Introspection

Introspection is the automatic process of analyzing a bean's design patterns to reveal the bean's properties,
events, and methods. This process controls the publishing and discovery of bean operations and
properties. This lesson explains the purpose of introspection, introduces the Introspection API, and gives
an example of introspection code.

Purpose of Introspection

A growing number of Java object repository sites exist on the Internet in answer to the demand for
centralized deployment of applets, classes, and source code in general. Any developer who has spent time
hunting through these sites for licensable Java code to incorporate into a program has undoubtedly
struggled with issues of how to quickly and cleanly integrate code from one particular source into an
application.

The way in which introspection is implemented provides great advantages, including:

1. Portability - Everything is done in the Java platform, so you can write components once, reuse
them everywhere. There are no extra specification files that need to be maintained independently
from your component code. There are no platform-specific issues to contend with. Your
component is not tied to one component model or one proprietary platform. You get all the
advantages of the evolving Java APIs, while maintaining the portability of your components.
2. Reuse - By following the JavaBeans design conventions, implementing the appropriate interfaces,
and extending the appropriate classes, you provide your component with reuse potential that
possibly exceeds your expectations.

Introspection API
The JavaBeans API architecture supplies a set of classes and interfaces to provide introspection.

The BeanInfo (in the API reference documentation) interface of the java.beans package defines a set of
methods that allow bean implementors to provide explicit information about their beans. By specifying
BeanInfo for a bean component, a developer can hide methods, specify an icon for the toolbox, provide
descriptive names for properties, define which properties are bound properties, and much more.

The getBeanInfo(beanName) (in the API reference documentation) of the Introspector (in the API
reference documentation) class can be used by builder tools and other automated environments to provide
detailed information about a bean. The getBeanInfo method relies on the naming conventions for the
bean's properties, events, and methods. A call to getBeanInfo results in the introspection process
analyzing the bean’s classes and superclasses.

The Introspector class provides descriptor classes with information about properties, events, and methods
of a bean. Methods of this class locate any descriptor information that has been explicitly supplied by the
developer through BeanInfo classes. Then the Introspector class applies the naming conventions to
determine what properties the bean has, the events to which it can listen, and those which it can send.

The following figure represents a hierarchy of the FeatureDescriptor classes:

Each class represented in this group describes a particular attribute of the bean. For example, the isBound
method of the PropertyDescriptor class indicates whether a PropertyChangeEvent event is fired when the
value of this property changes.

Editing Bean Info with the NetBeans BeanInfo Editor

To open the BeanInfo dialog box, expand the appropriate class hierarchy to the bean Patterns node. Right-
click the bean Patterns node and choose BeanInfo Editor from the pop-up menu. All elements of the
selected class that match bean-naming conventions will be displayed at the left in the BeanInfo Editor
dialog box as shown in the following figure:

Select one of the following nodes to view and edit its properties at the right of the dialog box:

 BeanInfo
 Bean
 Properties
 Methods
 Event Sources

Special symbols (green and red) appear next to the subnode to indicate whether an element will be
included or excluded from the BeanInfo class.

If the Get From Introspection option is not selected, the node's subnodes are available for inclusion in the
BeanInfo class. To include all subnodes, right-click a node and choose Include All. You can also include
each element individually by selecting its subnode and setting the Include in BeanInfo property. If the Get
From Introspection option is selected, the setting the properties of subnodes has no effect in the generated
BeanInfo code.

The following attributes are available for the nodes for each bean, property, event sources, and method:

 Name - A name of the selected element as it appears in code.


 Preferred - An attribute to specify where this property appears in the Inspector window under the
Properties node.
 Expert - An attribute to specify where this property appears in the Inspector window under the
Other Properties node.
 Hidden - An attribute to mark an element for tool use only.
 Display Name Code - A display name of the property.
 Short Description Code - A short description of the property.
 Include in BeanInfo - An attribute to include the selected element in the BeanInfo class.
 Bound - An attribute to make the bean property bound.
 Constrained - An attribute to make the bean property constrained.
 Mode - An attribute to set the property's mode and generate getter and setter methods.
 Property Editor Class - An attribute to specify a custom class to act as a property editor for the
property.

For Event Source nodes, the following Expert properties are available:

 Unicast (read-only)
 In Default Event Set

Introspection Sample
The following example represents code to perform introspection:

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;

public class SimpleBean


{
private final String name = "SimpleBean";
private int size;

public String getName()


{
return this.name;
}

public int getSize()


{
return this.size;
}

public void setSize( int size )


{
this.size = size;
}
public static void main( String[] args )
throws IntrospectionException
{
BeanInfo info = Introspector.getBeanInfo( SimpleBean.class );
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
System.out.println( pd.getName() );
}
}

This example creates a non-visual bean and displays the following properties derived from the BeanInfo
object:
 class
 name
 size

Note that a class property was not defined in the SimpleBean class. This property was inherited from the
Object class. To get properties defined only in the SimpleBean class, use the following form of the
getBeanInfo method:

Introspector.getBeanInfo( SimpleBean.class, Object.class );


Bean Customization

Customization provides a means for modifying the appearance and behavior of a bean within an
application builder so it meets your specific needs. There are several levels of customization available for
a bean developer to allow other developers to get maximum benefit from a bean’s potential functionality.

The following links are useful for learning about property editors and customizers:

 PropertyEditor(in the API reference documentation) interface


 PropertyEditorSupport(in the API reference documentation) class
 PropertyEditorManager(in the API reference documentation) class
 Customizer(in the API reference documentation) interface
 BeanInfo(in the API reference documentation) interface

A bean's appearance and behavior can be customized at design time within beans-compliant builder tools.
There are two ways to customize a bean:

 By using a property editor. Each bean property has its own property editor. The NetBeans GUI
Builder usually displays a bean's property editors in the Properties window. The property editor
that is associated with a particular property type edits that property type.
 By using customizers. Customizers give you complete GUI control over bean customization.
Customizers are used where property editors are not practical or applicable. Unlike a property
editor, which is associated with a property, a customizer is associated with a bean.

Property Editors

A property editor is a tool for customizing a particular property type. Property editors are activated in the
Properties window. This window determines a property's type, searches for a relevant property editor, and
displays the property's current value in a relevant way.

Property editors must implement the PropertyEditor interface, which provides methods to specify how a
property should be displayed in a property sheet. The following figure represents the Properties window
containing myBean1 properties:
You begin the process of editing these properties by clicking the property entry. Clicking most of these
entries will bring up separate panels. For example, to set up the foreground or background use selection
boxes with choices of colors, or press the "..." button to work with a standard ColorEditor window.
Clicking on the toolTipText property opens a StringEditor window.

The support class PropertyEditorSupport provides a default implementation of the PropertyEditor


interface. By subclassing your property editor from PropertyEditorSupport, you can simply override the
methods you need.

To display the current property value "sample" within the Properties window, you need to override
isPaintable to return true. You then must override paintValue to paint the current property value in a
rectangle in the property sheet. Here's how ColorEditor implements paintValue:

public void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box) {


Color oldColor = gfx.getColor();
gfx.setColor(Color.black);
gfx.drawRect(box.x, box.y, box.width-3, box.height-3);
gfx.setColor(color);
gfx.fillRect(box.x+1, box.y+1, box.width-4, box.height-4);
gfx.setColor(oldColor);
}

To support the custom property editor, override two more methods. Override supportsCustomEditor to
return true, and then override getCustomEditor to return a custom editor instance.
ColorEditor.getCustomEditor returns this.

In addition, the PropertyEditorSupport class maintains a PropertyChangeListener list, and fires property
change event notifications to those listeners when a bound property is changed.

How Property Editors are Associated with Properties

Property editors are discovered and associated with a given property in the following ways:
 Explicit association by way of a BeanInfo object. The editor of the title's property is set with the
following line of code:
 pd.setPropertyEditorClass(TitleEditor.class);
 Explicit registration by way of the java.beans.PropertyEditorManager.registerEditor method. This
method takes two arguments: the bean class type, and the editor class to be associated with that
type.
 Name search. If a class has no explicitly associated property editor, then the
PropertyEditorManager searchs for that class's property editor in the following ways:
o Appending "Editor" to the fully qualified class name. For example, for the
my.package.ComplexNumber class, the property editor manager would search for the
my.package.ComplexNumberEditor class.
o Appending "Editor" to the class name and searching a class path.

Customizers

You have learned that builder tools provide support for you to create your own property editors. What
other needs should visual builders meet for complex, industrial-strength beans? Often it is undesirable to
have all the properties of a bean revealed on a single (sometimes huge) property sheet. What if one single
root choice about the type of the bean rendered half the properties irrelevant? The JavaBeans specification
provides for user-defined customizers, through which you can define a higher level of customization for
bean properties than is available with property editors.

When you use a bean Customizer, you have complete control over how to configure or edit a bean. A
Customizer is an application that specifically targets a bean's customization. Sometimes properties are
insufficient for representing a bean's configurable attributes. Customizers are used where sophisticated
instructions would be needed to change a bean, and where property editors are too primitive to achieve
bean customization.

All customizers must:

 Extend java.awt.Component or one of its subclasses.


 Implement the java.beans.Customizer interface This means implementing methods to register
PropertyChangeListener objects, and firing property change events at those listeners when a
change to the target bean has occurred.
 Implement a default constructor.
 Associate the customizer with its target class via BeanInfo.getBeanDescriptor.

UNIT-V SERVLETS
A web server is computers program that delivers (serves) content, such as this web page, using
the Hypertext Transfer Protocol. The term web server can also refer to the computer or virtual machine
running the program

Web application:

In software engineering, a web application or webapp is an application that is accessed via a


web browser over a network such as the Internet or an intranet.
Web browser is a software application for retrieving, presenting, and traversing information
resources on the World Wide Web. An information resource is identified by a Uniform Resource
Identifier (URI) and may be a web page, image, video, or other piece of content. Hyperlinks present in
resources enable users to easily navigate their browsers to related resources.

Servlets are Java programming language objects that dynamically process requests and construct
responses. The Java Servlet API allows a software developer to add dynamic content to a Web server
using the Java platform

The servlet API, contained in the Java package hierarchy javax.servlet, defines the expected
interactions of a Web container and a servlet. A Web container is essentially the component of a Web
server that interacts with the servlets. The Web container is responsible for managing the lifecycle of
servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access
rights

Execution procedure of servlet:

1)Create a directory(This is called as Document_Root)


Ex:F:\OurWebApp
2)Under Document_Root create a directory with the name WEB-INF
3)Under WEB-INF create
a)lib--->used to place jar files
b)classes--->used to place class file
4)we can place the static resources under Document_Root all the sub directories of
Document_Root(but not under WEB-INF directory)
5)create a file with the name web.xml and place it under WEB-INF directory.This file is
called as Deployment Descriptor(DD).
6)We can deploy the web application on Tomcat by copying the exploded directory structure
into webapps directory.

Lifecycle of a servlet

The servlet lifecycle consists of the following steps:

1. The servlet class is loaded by the container during start-up.


2. The container calls the init() method. This method initializes the servlet and must be called before
the servlet can service any requests. In the entire life of a servlet, the init() method is called only
once.
3. After initialization, the servlet can service client requests. Each request is serviced in its own
separate thread. The container calls the service() method of the servlet for every request. The
service() method determines the kind of request being made and dispatches it to an appropriate
method to handle the request. The developer of the servlet must provide an implementation for
these methods. If a request for a method that is not implemented by the servlet is made, the
method of the parent class is called, typically resulting in an error being returned to the requester.
4. Finally, the container calls the destroy() method that takes the servlet out of service. The destroy()
method like init() is called only once in the lifecycle of a servlet.
Here is a simple servlet that just generates HTML. Note that HttpServlet is a subclass of GenericServlet,
an implementation of the Servlet interface. The service() method dispatches requests to methods doGet(),
doPost(), doPut(), doDelete(), etc., according to the HTTP request.

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" +
"<html>\n" +
"<head><title>Hello WWW</title></head>\n" +
"<body>\n" +
"<h1>Hello WWW</h1>\n" +
"</body></html>");
}
}

ServletConfig and ServletContext

There is only one ServletContext in every application. This object can be used by all the servlets to
obtain application level information or container details. Every servlet, on the other hand, gets its own
ServletConfig object. This object provides initialization parameters for a servlet. A developer can obtain
the reference to ServletContext using the ServletConfig object.

The "servletcontext" object was created by the container at the time of servlet initialization and destroyed
just before the servlet deinstantion i.e., the scope of the sevletcontext object is the scope of the web
application..

There will be only one serveletcontext object for the entire web application. Servlet context object was
created by the container if it is the first request form the client other wise it will create the reference of the
existed object.

Servlet containers

A servlet container is a specialized web server that supports servlet execution. It combines the basic
functionality of a web server with certain Java/servlet specific optimizations and extensions – such as an
integrated Java runtime environment, and the ability to automatically translate specific URLs into servlet
requests. Individual servlets are registered with a servlet container, providing the container with
information about what functionality they provide, and what URL or other resource locator they will use
to identify themselves. The servlet container is then able to initialize the servlet as necessary and deliver
requests to the servlet as they arrive. Many containers have the ability to dynamically add and remove
servlets from the system, allowing new servlets to quickly be deployed or removed without affecting
other servlets running from the same container. Servlet containers are also referred to as web containers
or web engines.

Like the other Java APIs, different vendors provide their own implementations of the servlet container
standard. For a list of some of the free and commercial web containers, see the list of Servlet containers.
(Note that 'free' means that non-commercial use is free. Some of the commercial containers, e.g. Resin
and Orion, are free to use in a server environment for non profit organizations).

Servlet API Documentation:

Packages

The javax.servlet package contains a number of classes and interfaces that


describe and define the contracts between a servlet class and the runtime
javax.servlet
environment provided for an instance of such a class by a conforming servlet
container.

The javax.servlet.http package contains a number of classes and interfaces that


describe and define the contracts between a servlet class running under the HTTP
javax.servlet.http
protocol and the runtime environment provided for an instance of such a class by
a conforming servlet container.

Package javax.servlet
The javax.servlet package contains a number of classes and interfaces that describe and define the
contracts between a servlet class and the runtime environment provided for an instance of such a class by
a conforming servlet container.

Interface Summary

A filter is an object that performs filtering tasks on either the


Filter request to a resource (a servlet or static content), or on the
response from a resource, or both.

A FilterChain is an object provided by the servlet container to


FilterChain the developer giving a view into the invocation chain of a
filtered request for a resource.

A filter configuration object used by a servlet container to pass


FilterConfig
information to a filter during initialization.
Defines an object that receives requests from the client and
RequestDispatcher sends them to any resource (such as a servlet, HTML file, or
JSP file) on the server.

Servlet Defines methods that all servlets must implement.

A servlet configuration object used by a servlet container to


ServletConfig
pass information to a servlet during initialization.

Defines a set of methods that a servlet uses to communicate


ServletContext with its servlet container, for example, to get the MIME type
of a file, dispatch requests, or write to a log file.

Implementations of this interface receive notifications of


ServletContextAttributeListener changes to the attribute list on the servlet context of a web
application.

Implementations of this interface receive notifications about


ServletContextListener changes to the servlet context of the web application they are
part of.

Defines an object to provide client request information to a


ServletRequest
servlet.

A ServletRequestAttributeListener can be implemented by the


ServletRequestAttributeListener developer interested in being notified of request attribute
changes.

A ServletRequestListener can be implemented by the


ServletRequestListener developer interested in being notified of requests coming in
and out of scope in a web component.

Defines an object to assist a servlet in sending a response to


ServletResponse
the client.

Deprecated. As of Java Servlet API 2.4, with no direct


SingleThreadModel
replacement.

Class Summary

GenericServlet Defines a generic, protocol-independent servlet.


This is the event class for notifications about changes to the attributes
ServletContextAttributeEvent
of the servlet context of a web application.

This is the event class for notifications about changes to the servlet
ServletContextEvent
context of a web application.

Provides an input stream for reading binary data from a client request,
ServletInputStream including an efficient readLine method for reading data one line at a
time.

ServletOutputStream Provides an output stream for sending binary data to the client.

ServletRequestAttributeEven This is the event class for notifications of changes to the attributes of
t the servlet request in an application.

ServletRequestEvent Events of this kind indicate lifecycle events for a ServletRequest.

Provides a convenient implementation of the ServletRequest interface


ServletRequestWrapper that can be subclassed by developers wishing to adapt the request to a
Servlet.

Provides a convenient implementation of the ServletResponse interface


ServletResponseWrapper that can be subclassed by developers wishing to adapt the response
from a Servlet.

Exception Summary

Defines a general exception a servlet can throw when it encounters


ServletException
difficulty.

Defines an exception that a servlet or filter throws to indicate that it is


UnavailableException
permanently or temporarily unavailable.

Package javax.servlet.http
The javax.servlet.http package contains a number of classes and interfaces that describe and define the
contracts between a servlet class running under the HTTP protocol and the runtime environment provided
for an instance of such a class by a conforming servlet container.
Interface Summary

Extends the ServletRequest interface to provide request


HttpServletRequest
information for HTTP servlets.

Extends the ServletResponse interface to provide HTTP-specific


HttpServletResponse
functionality in sending a response.

Provides a way to identify a user across more than one page


HttpSession request or visit to a Web site and to store information about that
user.

Objects that are bound to a session may listen to container events


HttpSessionActivationListener notifying them that sessions will be passivated and that session
will be activated.

This listener interface can be implemented in order to get


HttpSessionAttributeListener notifications of changes to the attribute lists of sessions within
this web application.

Causes an object to be notified when it is bound to or unbound


HttpSessionBindingListener
from a session.

Deprecated. As of Java(tm) Servlet API 2.1 for security reasons,


HttpSessionContext
with no replacement.

Implementations of this interface are notified of changes to the


HttpSessionListener
list of active sessions in a web application.

Class Summary

Creates a cookie, a small amount of information sent by a servlet to a


Cookie
Web browser, saved by the browser, and later sent back to the server.

Provides an abstract class to be subclassed to create an HTTP servlet


HttpServlet
suitable for a Web site.

Provides a convenient implementation of the HttpServletRequest


HttpServletRequestWrapper interface that can be subclassed by developers wishing to adapt the
request to a Servlet.
Provides a convenient implementation of the HttpServletResponse
HttpServletResponseWrappe
interface that can be subclassed by developers wishing to adapt the
r
response from a Servlet.

Events of this type are either sent to an object that implements


HttpSessionBindingListener when it is bound or unbound from a
HttpSessionBindingEvent session, or to a HttpSessionAttributeListener that has been configured
in the deployment descriptor when any attribute is bound, unbound or
replaced in a session.

This is the class representing event notifications for changes to sessions


HttpSessionEvent
within a web application.

HttpUtils Deprecated. As of Java(tm) Servlet API 2.3.

UNIT-VI INTRODUCTION TO JSP


Introduction to JavaServer Pages

JavaServer Pages is a technology specified by Sun Microsystems as a convenient way of generating


dynamic content in pages that are output by a Web application (an application running on a Web server).

This technology, which is closely coupled with Java servlet technology, enables you to include Java code
snippets and calls to external Java components within the HTML code (or other markup code, such as
XML) of your Web pages. JavaServer Pages (JSP) technology works nicely as a front-end for business
logic and dynamic functionality in JavaBeans and Enterprise JavaBeans (EJBs).

JSP code is distinct from other Web scripting code, such as JavaScript, in a Web page. Anything that you
can include in a normal HTML page can be included in a JSP page as well.

In a typical scenario for a database application, a JSP page will call a component such as a JavaBean or
Enterprise JavaBean, and the bean will directly or indirectly access the database, generally through JDBC.

A JSP page is translated into a Java servlet before being executed, and processes HTTP requests and
generates responses similarly to any other servlet. JSP technology offers a more convenient way to code
the servlet. The translation typically occurs on demand, but sometimes in advance.
Furthermore, JSP pages are fully interoperable with servlets—JSP pages can include output from a servlet
or forward to a servlet, and servlets can include output from a JSP page or forward to a JSP page.

What a JSP Page Looks Like

Here is an example of a simple JSP page. For an explanation of JSP syntax elements used here, see
"Overview of JSP Syntax Elements".

<HTML>
<HEAD><TITLE>The Welcome User JSP</TITLE></HEAD>
<BODY>
<% String user=request.getParameter("user"); %>
<H3>Welcome <%= (user==null) ? "" : user %>!</H3>
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! :-)</B></P>
<B>Enter name:</B>
<FORM METHOD=get>
<INPUT TYPE="text" NAME="user" SIZE=15>
<INPUT TYPE="submit" VALUE="Submit name">
</FORM>
</BODY>
</HTML>

In a traditional JSP page, Java elements are set off by tags such as <% and %>, as in the preceding
example. (JSP XML syntax is different, as described in "Details of JSP XML Documents".) In this
example, Java snippets get the user name from an HTTP request object, print the user name, and get the
current date.

This JSP page will produce output as shown in Figure 1-1 if the user inputs the name "Amy".

Figure 1-1 Sample Welcome Page


JSP Pages Work

A JSP page is basically a web page with traditional HTML and bits of Java code. The file extension of a
JSP page is ".jsp" rather than ".html" or ".htm", and that tells the server that this page requires special
handling that will be accomplished by a server extension or a plug-in. Here is a simple example:

Sample 1: date.jsp

<HTML>

<HEAD>

<TITLE>JSP Example</TITLE>

</HEAD>

<BODY BGCOLOR="ffffcc">

<CENTER>

<H2>Date and Time</H2>

<%

java.util.Date today = new java.util.Date();


out.println("Today's date is: "+today);

%>

</CENTER>

</BODY>

</HTML>

This example contains traditional HTML and some Java code. The tag <% identifies the beginning of a
scriptlet, and the %> tag identifies the end of a scriptlet. When date.jsp is requested from a web browser,
you see something similar to Figure 1.

Figure 1: Requesting date.jsp

Behind the Scenes

When this page (date.jsp) is called, it will be compiled (by the JSP engine) into a java servlet. At this
point the servlet is handled by the servlet engine just like any other servlet. The servlet engine then loads
the servlet class (using a class loader) and executes it to create dynamic HTML to be sent to the browser,
as shown in Figure 2. For this example, the servlet creates a Date object and writes it as a string to the out
object, which is an output stream to the browser.

Figure 2: Request/Response Flow when Calling a JSP

The next time the page is requested, the JSP engine executes the already-loaded servlet unless the JSP
page has changed, in which case it is automatically recompiled into a servlet and executed.
Scripting Elements

In the date.jsp example the full Date class name is used including the package name, which may become
tedious. If you want to create an instance of Date simply by using: Date today = new Date(); without
having to specify the full class path use the page directive as follows:

Sample 2 :date2.jsp

<%@page import="java.util.*" %>

<HTML>

<HEAD>

<TITLE>JSP Example</TITLE>

</HEAD>

<BODY BGCOLOR="ffffcc">

<CENTER>

<H2>Date and Time</H2>

<%

java.util.Date today = new java.util.Date();

out.println("Today's date is: "+today);

%>

</CENTER>

</BODY>

</HTML>

Yet, another way of doing the same thing using the <%= tag is by writing:

Sample 3:date3.jsp

<%@page import="java.util.*" %>


<HTML>

<HEAD>

<TITLE>JSP Example</TITLE>

</HEAD>

<BODY BGCOLOR="#ffffcc">

<CENTER>

<H2>Date and Time</H2>

Today's date is: <%= new Date() %>

</CENTER>

</BODY>

</HTML>

As you can see, the same thing can be accomplished using different tags and techniques. There are several
JSP scripting elements. Here are some conventional rules that will help you use JSP scripting elements
effectively:

Use <% ... %> to handle declarations, expressions, or any other type of valid snippet of code.
Sample 1 above is an example.
Use the page directive as in <%@page ... %> to define the scripting language.
Also, it can be used to specify import statements. Here is an example:
<%@page language="java" import="java.util.*" %>.
Use <%! .... %> to declare variables or methods. For example:
<%! int x = 10; double y = 2.0; %>.
Use <%= ... %> to define an expression and cast the result as a String. For example:
<%= a+b %> or <%= new java.util.Date() %>.
Use the include directive as in <%@ include ... %> to insert the contents of another file in the
main JSP file. For example:
<%@include file="copyright.html" %>.

Convenience of JSP Coding Versus Servlet Coding

Combining Java code and Java calls into an HTML page is more convenient than using straight Java code
in a servlet. JSP syntax gives you a shortcut for coding dynamic Web pages, typically requiring much less
code than Java servlet syntax. Following is an example contrasting servlet code and JSP code.
Servlet Code
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class Hello extends HttpServlet


{
public void doGet(HttpServletRequest rq, HttpServletResponse rsp)
{
rsp.setContentType("text/html");
try {
PrintWriter out = rsp.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Welcome</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H3>Welcome!</H3>");
out.println("<P>Today is "+new java.util.Date()+".</P>");
out.println("</BODY>");
out.println("</HTML>");
} catch (IOException ioe)
{
// (error processing)
}
}
}

See "The Servlet Interface" for some background information about the standard HttpServlet abstract
class, HttpServletRequest interface, and HttpServletResponse interface.

JSP Code
<HTML>
<HEAD><TITLE>Welcome</TITLE></HEAD>
<BODY>
<H3>Welcome!</H3>
<P>Today is <%= new java.util.Date() %>.</P>
</BODY>
</HTML>

Note how much simpler JSP syntax is. Among other things, it saves Java overhead such as package
imports and try...catch blocks.

Additionally, the JSP translator automatically handles a significant amount of servlet coding overhead for
you in the .java file that it outputs, such as directly or indirectly implementing the standard
javax.servlet.jsp.HttpJspPage interface (covered in "Standard JSP Interfaces and Methods") and adding
code to acquire an HTTP session.

Also note that because the HTML of a JSP page is not embedded within Java print statements, as it is in
servlet code, you can use HTML authoring tools to create JSP pages.
Separation of Business Logic from Page Presentation: Calling JavaBeans

JSP technology allows separating the development efforts between the HTML code that determines static
page presentation, and the Java code that processes business logic and presents dynamic content. It
therefore becomes much easier to split maintenance responsibilities between presentation and layout
specialists who might be proficient in HTML but not Java, and code specialists who may be proficient in
Java but not HTML.

In a typical JSP page, most Java code and business logic will not be within snippets embedded in the JSP
page. Instead, it will be in JavaBeans or Enterprise JavaBeans that are invoked from the JSP page.

JSP technology offers the following syntax for defining and creating an instance of a JavaBeans class:

<jsp:useBean id="pageBean" class="mybeans.NameBean" scope="page" />

This example creates an instance, pageBean, of the mybeans.NameBean class. The scope parameter will
be explained later in this chapter.

Later in the page, you can use this bean instance, as in the following example:

Hello <%= pageBean.getNewName() %> !

This prints "Hello Julie !", for example, if the name "Julie" is in the newName attribute of pageBean,
which might occur through user input.

The separation of business logic from page presentation allows convenient division of responsibilities
between the Java expert who is responsible for the business logic and dynamic content (the person who
owns and maintains the code for the NameBean class) and the HTML expert who is responsible for the
static presentation and layout of the Web page that the application users see (the person who owns and
maintains the code in the .jsp file for this JSP page).

Tags used with JavaBeans—useBean to declare the JavaBean instance and getProperty and setProperty to
access bean properties—are further discussed in "Standard Actions: JSP Tags".

JSP Pages and Alternative Markup Languages

JavaServer Pages technology is typically used for dynamic HTML output, but the JSP specification also
supports additional types of structured, text-based document output. A JSP translator does not process
text outside of JSP elements, so any text that is appropriate for Web pages in general is typically
appropriate for a JSP page as well.

A JSP page takes information from an HTTP request and accesses information from a database server
(such as through a SQL database query). It combines and processes this information and incorporates it,
as appropriate, into an HTTP response with dynamic content. The content can be formatted as HTML,
DHTML, XHTML, or XML, for example.

For information about JSP support for XML, refer to Chapter 5, "JSP XML Support" and to the Oracle
Application Server Containers for J2EE JSP Tag Libraries and Utilities Reference.
Overview of JSP Syntax Elements

You have seen a simple example of JSP syntax in "What a JSP Page Looks Like". Now here is a top-level
list of syntax categories and topics:

Directives: These convey information regarding the JSP page as a whole.

Scripting elements: These are Java coding elements such as declarations, expressions, scriptlets, and
comments.

Objects and scopes: JSP objects can be created either explicitly or implicitly and are accessible within a
given scope, such as from anywhere in the JSP page or the session.

Actions: These create objects or affect the output stream in the JSP response (or both).

This section introduces each category, including basic syntax and a few examples. There is also
discussion of bean property conversions, and an introduction to custom tag libraries (used for custom
actions). For more information, see the Sun Microsystems JavaServer Pages Specification.

Directives

Directives provide instruction to the JSP container regarding the entire JSP page. This information is used
in translating or executing the page. The basic syntax is as follows:

<%@ directive attribute1="value1" attribute2="value2"... %>

The JSP specification supports the following directives:

page

include

taglib

page directive

Use this directive to specify any of a number of page-dependent attributes, such as scripting language,
content type, character encoding, class to extend, packages to import, an error page to use, the JSP page
output buffer size, and whether to automatically flush the buffer when it is full. For example:

<%@ page language="java" import="packages.mypackage" errorPage="boof.jsp" %>

Alternatively, to enable auto-flush and set the JSP page output buffer size to 20 KB:

<%@ page autoFlush="true" buffer="20kb" %>

This example unbuffers the page:


<%@ page buffer="none" %>

include directive

Use this directive to specify a resource that contains text or code to be inserted into the JSP page when it
is translated. For example:

<%@ include file="/jsp/userinfopage.jsp" %>

Specify either a page-relative or context-relative path to the resource. See "Requesting a JSP Page" for
discussion of page-relative and context-relative paths.

taglib directive

Use this directive to specify a library of custom JSP tags that will be used in the JSP page. Vendors can
extend JSP functionality with their own sets of tags. This directive includes a pointer to a tag library
descriptor file and a prefix to distinguish use of tags from that library. For example:

<%@ taglib uri="/oracustomtags" prefix="oracust" %>

Later in the page, use the oracust prefix whenever you want to use one of the tags in the library. Presume
this library includes a tag dbaseAccess:

<oracust:dbaseAccess ... >


...
</oracust:dbaseAccess>

JSP tag libraries and tag library descriptor files are introduced later in this chapter, in "Custom Tag
Libraries", and discussed in detail in Chapter 8, "JSP Tag Libraries".

Scripting Elements

JSP scripting elements include the following categories of Java code snippets that can appear in a JSP
page:

 Declarations

 Expressions

 Scriptlets

 Comments

Declarations

These are statements declaring methods or member variables that will be used in the JSP page.
A JSP declaration uses standard Java syntax within the <%!...%> declaration tags to declare a member
variable or method. This will result in a corresponding declaration in the generated servlet code. For
example:

<%! double f1=0.0; %>

This example declares a member variable, f1. In the servlet class code generated by the JSP translator, f1
will be declared at the class top level.

Expressions

These are Java expressions that are evaluated, converted into string values as appropriate, and displayed
where they are encountered on the page.

A JSP expression does not end in a semicolon, and is contained within <%=...%> tags. For example:

<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>

Scriptlets

These are portions of Java code intermixed within the markup language of the page.

A scriptlet, or code fragment, can consist of anything from a partial line to multiple lines of Java code.
You can use them within the HTML code of a JSP page to set up conditional branches or a loop, for
example.

A JSP scriptlet is contained within <%...%> scriptlet tags, using normal Java syntax.

Example 1:

<% if (pageBean.getNewName().equals("")) { %>


I don't know you.
<% } else { %>
Hello <%= pageBean.getNewName() %>.
<% } %>

Three one-line JSP scriptlets are intermixed with two lines of HTML code, one of which includes a JSP
expression (which does not require a semicolon). Note that JSP syntax allows HTML code to be the code
that is conditionally executed within the if and else branches (inside the Java brackets set out in the
scriptlets).

The preceding example assumes the use of a JavaBean instance, pageBean.

Example 2:

<% if (pageBean.getNewName().equals("")) { %>


I don't know you.
<% empmgr.unknownemployee();
} else { %>
Hello <%= pageBean.getNewName() %>.
<% empmgr.knownemployee();
} %>

This example adds more Java code to the scriptlets. It assumes the use of a JavaBean instance, pageBean,
and assumes that some object, empmgr, was previously instantiated and has methods to execute
appropriate functionality for a known employee or an unknown employee.

Comments

These are developer comments embedded within the JSP code, similar to comments embedded within any
Java code.

Comments are contained within <%--...--%> syntax. For example:

<%-- Execute the following branch if no user name is entered. --%>

Unlike HTML comments, JSP comments are not visible when users view the page source from their
browsers.

Software Environment

To run JSP pages, you need a web server with a web container that conforms to JSP and servlet
specifications. The web container executes on the web server and manages the execution of all JSP pages
and servlets running on that web server. Tomcat 3.2.1 is a complete reference implementation for the Java
Servlet 2.2 and JSP 1.1 specifications. Download and install binary versions of Tomcat.

To configure Tomcat:

Set the environment variable JAVA_HOME to point to the root directory of your Java 2
Standard Edition (J2SE) installation.
Set the TOMCAT_HOME environment variable to point to the root directory of your
Tomcat installation.
To start Tomcat, use TOMCAT_HOME/bin/startup.bat for windows or startup.sh for
UNIX.
By default, it will start listening on port 8080.
Save your .jsp files in TOMCAT_HOME/webapps/examples/jsp and your JavaBeans
classes in TOMCAT_HOME/webapps/examples/web-inf/classes.
UNIT-VII JAVA SERVER PAGES
JSP Objects and Scopes

In this document, the term JSP object refers to a Java class instance declared within or accessible to a JSP
page. JSP objects can be either:

Explicit: Explicit objects are declared and created within the code of your JSP page, accessible to that
page and other pages according to the scope setting you choose.

Implicit: Implicit objects are created by the underlying JSP mechanism and accessible to Java scriptlets or
expressions in JSP pages according to the inherent scope setting of the particular object type.

These topics are discussed in the following sections:

Explicit Objects

Implicit Objects

Using an Implicit Object


Object Scopes

Explicit Objects

Explicit objects are typically JavaBean instances that are declared and created in jsp:useBean action
statements. The jsp:useBean statement and other action statements are described in "Standard Actions:
JSP Tags", but here is an example:

<jsp:useBean id="pageBean" class="mybeans.NameBean" scope="page" />

This statement defines an instance, pageBean, of the NameBean class that is in the mybeans package. The
scope parameter is discussed in "Object Scopes".

You can also create objects within Java scriptlets or declarations, just as you would create Java class
instances in any Java program.

Implicit Objects

JSP technology makes available to any JSP page a set of implicit objects. These are Java objects that are
created automatically by the JSP container and that allow interaction with the underlying servlet
environment.

The implicit objects listed immediately below are available. For information about methods available
with these objects, refer to the Sun Microsystems Javadoc for the noted classes and interfaces at the
following location:

page

This is an instance of the JSP page implementation class and is created when the page is translated. The
page implementation class implements the interface javax.servlet.jsp.HttpJspPage. Note that page is
synonymous with this within a JSP page.

request

This represents an HTTP request and is an instance of a class that implements the
javax.servlet.http.HttpServletRequest interface, which extends the javax.servlet.ServletRequest interface.

response

This represents an HTTP response and is an instance of a class that implements the
javax.servlet.http.HttpServletResponse interface, which extends the javax.servlet.ServletResponse
interface.

The response and request objects for a particular request are associated with each other.

pageContext
This represents the page context of a JSP page, which is provided for storage and access of all page scope
objects of a JSP page instance. A pageContext object is an instance of the javax.servlet.jsp.PageContext
class.

The pageContext object has page scope, making it accessible only to the JSP page instance with which it
is associated.

session

This represents an HTTP session and is an instance of a class that implements the
javax.servlet.http.HttpSession interface.

application

This represents the servlet context for the Web application and is an instance of a class that implements
the javax.servlet.ServletContext interface.

The application object is accessible from any JSP page instance running as part of any instance of the
application within a single JVM. (The programmer should be aware of the server architecture regarding
use of JVMs.)

out

This is an object that is used to write content to the output stream of a JSP page instance. It is an instance
of the javax.servlet.jsp.JspWriter class, which extends the java.io.Writer class.

The out object is associated with the response object for a particular request.

config

This represents the servlet configuration for a JSP page and is an instance of a class that implements the
javax.servlet.ServletConfig interface. Generally speaking, servlet containers use ServletConfig instances
to provide information to servlets during initialization. Part of this information is the appropriate
ServletContext instance.

exception (JSP error pages only)

This implicit object applies only to JSP error pages, which are pages to which processing is forwarded
when an exception is thrown from another JSP page. They must have the page directive isErrorPage
attribute set to true.

The implicit exception object is a java.lang.Exception instance that represents the uncaught exception that
was thrown from another JSP page and that resulted in the current error page being invoked.

The exception object is accessible only from the JSP error page instance to which processing was
forwarded when the exception was encountered. For an example of JSP error processing and use of the
exception object, see "Runtime Error Processing".
Using an Implicit Object

Any of the implicit objects discussed in the preceding section might be useful. The following example
uses the request object to retrieve and display the value of the username parameter from the HTTP
request:

<H3> Welcome <%= request.getParameter("username") %> ! <H3>

The request object, like the other implicit objects, is available automatically; it is not explicitly
instantiated.

Object Scopes

Objects in a JSP page, whether explicit or implicit, are accessible within a particular scope. In the case of
explicit objects, such as a JavaBean instance created in a jsp:useBean action, you can explicitly set the
scope with the following syntax, as in the example in "Explicit Objects":

scope="scopevalue"

There are four possible scopes:

scope="page" (default scope): The object is accessible only from within the JSP page where it was
created. A page-scope object is stored in the implicit pageContext object. The page scope ends when the
page stops executing.

Note that when the user refreshes the page while executing a JSP page, new instances will be created of
all page-scope objects.

scope="request": The object is accessible from any JSP page servicing the same HTTP request that is
serviced by the JSP page that created the object. A request-scope object is stored in the implicit request
object. The request scope ends at the conclusion of the HTTP request.

scope="session": The object is accessible from any JSP page that is sharing the same HTTP session as the
JSP page that created the object. A session-scope object is stored in the implicit session object. The
session scope ends when the HTTP session times out or is invalidated.

scope="application": The object is accessible from any JSP page that is used in the same Web application
as the JSP page that created the object, within any single Java virtual machine. The concept is similar to
that of a Java static variable. An application-scope object is stored in the implicit application servlet
context object. The application scope ends when the application itself terminates, or when the JSP
container or servlet container shuts down.

You can think of these four scopes as being in the following progression, from narrowest scope to
broadest scope:

page < request < session < application

If you want to share an object between different pages in an application, such as when forwarding
execution from one page to another, or including content from one page in another, you cannot use page
scope for the shared object; in this case, there would be a separate object instance associated with each
page. The narrowest scope you can use to share an object between pages is request. (For information
about including and forwarding pages, see "Standard Actions: JSP Tags" below.)

Standard Actions: JSP Tags

JSP action elements result in some sort of action occurring while the JSP page is being executed, such as
instantiating a Java object and making it available to the page. Such actions can include the following:

Creating a JavaBean instance and accessing its properties

Forwarding execution to another HTML page, JSP page, or servlet

Including an external resource in the JSP page

For standard actions, there is a set of tags defined in the JSP specification. Although directives and
scripting elements described earlier in this chapter are sufficient to code a JSP page, the standard tags
described here provide additional functionality and convenience.

Here is the general tag syntax for JSP standard actions:

<jsp:tag attr1="value1" attr2="value2" ... attrN="valueN">


...body...
</jsp:tag>

Alternatively, if there is no body:

<jsp:tag attr1="value1", ..., attrN="valueN" />

The JSP specification includes the following standard action tags, which are introduced and briefly
discussed immediately below:

jsp:usebean

jsp:setProperty

jsp:getProperty

jsp:param

jsp:include

jsp:forward

jsp:plugin
jsp:useBean tag

The jsp:useBean tag accesses or creates an instance of a Java type, typically a JavaBean class, and
associates the instance with a specified name, or ID. The instance is then available by that ID as a
scripting variable of specified scope. Scripting variables are introduced in "Custom Tag Libraries".
Scopes are discussed in "JSP Objects and Scopes".

The key attributes are class, type, id, and scope. (There is also a less frequently used beanName attribute,
discussed below.)

Use the id attribute to specify the instance name. The JSP container will first search for an object by the
specified ID, of the specified type, in the specified scope. If it does not exist, the container will attempt to
create it.

Intended use of the class attribute is to specify a class that can be instantiated, if necessary, by the JSP
container. The class cannot be abstract and must have a no-argument constructor. Intended use of the type
attribute is to specify a type that cannot be instantiated by the JSP container—either an interface, an
abstract class, or a class without a no-argument constructor. You would use type in a situation where the
instance will already exist, or where an instance of an instantiable class will be assigned to the type. There
are three typical scenarios:

Use type and id to specify an instance that already exists in the target scope.

Use class and id to specify the name of an instance of the class—either an instance that already exists in
the target scope or an instance to be newly created by the JSP container.

Use class, type, and id to specify a class to instantiate and a type to assign the instance to. In this case, the
class must be legally assignable to the type.

Use the scope attribute to specify the scope of the instance—either page for the instance to be associated
with the page context object, request for it to be associated with the HTTP request object, session for it to
be associated with the HTTP session object, or application for it to be associated with the servlet context.

As an alternative to using the class attribute, you can use the beanName attribute. In this case, you have
the option of specifying a serializable resource instead of a class name. When you use the beanName
attribute, the JSP container creates the instance by using the instantiate() method of the java.beans.Beans
class.

The following example uses a request-scope instance reqobj of type MyIntfc. Because MyIntfc is an
interface and cannot be instantiated directly, reqobj would have to already exist.

<jsp:useBean id="reqobj" type="mypkg.MyIntfc" scope="request" />

This next example uses a page-scope instance pageobj of class PageBean, first creating it if necessary:

<jsp:useBean id="pageobj" class="mybeans.PageBean" scope="page" />


The following example creates an instance of class SessionBean and assigns the instance to the variable
sessobj of type MyIntfc:

<jsp:useBean id="sessobj" class="mybeans.SessionBean"


type="mypkg.MyIntfc scope="session" />

jsp:setProperty tag

The jsp:setProperty tag sets one or more bean properties. The bean must have been previously specified in
a jsp:useBean tag. You can directly specify a value for a specified property, or take the value for a
specified property from an associated HTTP request parameter, or iterate through a series of properties
and values from the HTTP request parameters.

The following example sets the user property of the pageBean instance (defined in the preceding
jsp:useBean example) to a value of "Smith":

<jsp:setProperty name="pageBean" property="user" value="Smith" />

The following example sets the user property of the pageBean instance according to the value set for a
parameter called username in the HTTP request:

<jsp:setProperty name="pageBean" property="user" param="username" />

If the bean property and request parameter have the same name (user), you can simply set the property as
follows:

<jsp:setProperty name="pageBean" property="user" />

The following example results in iteration over the HTTP request parameters, matching bean property
names with request parameter names and setting bean property values according to the corresponding
request parameter values:

<jsp:setProperty name="pageBean" property="*" />

When you use the jsp:setProperty tag, string input can be used to specify the value of a non-string
property through conversions that happen behind the scenes. See "Bean Property Conversions from String
Values".

jsp:getProperty tag

The jsp:getProperty tag reads a bean property value, converts it to a Java string, and places the string
value into the implicit out object so that it can be displayed as output. The bean must have been
previously specified in a jsp:useBean tag. For the string conversion, primitive types are converted directly
and object types are converted using the toString() method specified in the java.lang.Object class.

The following example puts the value of the user property of the pageBean bean into the out object:

<jsp:getProperty name="pageBean" property="user" />


jsp:param tag

You can use jsp:param tags in conjunction with jsp:include, jsp:forward, and jsp:plugin tags (described
below).

Used with jsp:forward and jsp:include tags, a jsp:param tag optionally provides name/value pairs for
parameter values in the HTTP request object. New parameters and values specified with this action are
added to the request object, with new values taking precedence over old.

The following example sets the request object parameter username to a value of Smith:

<jsp:param name="username" value="Smith" />

jsp:include tag

The jsp:include tag inserts additional static or dynamic resources into the page at request-time as the page
is displayed. Specify the resource with a relative URL (either page-relative or application-relative). For
example:

<jsp:include page="/templates/userinfopage.jsp" flush="true" />

A "true" setting of the flush attribute results in the buffer being flushed to the browser when a jsp:include
action is executed. The JSP specification and the OC4J JSP container support either a " true" or "false"
setting, with "false" being the default. (The JSP 1.1 specification supported only a "true" setting, with
flush being a required attribute.)

You can also have an action body with jsp:param tags, as shown in the following example:

<jsp:include page="/templates/userinfopage.jsp" flush="true" >


<jsp:param name="username" value="Smith" />
<jsp:param name="userempno" value="9876" />
</jsp:include>

Note that the following syntax would work as an alternative to the preceding example:

<jsp:include page="/templates/userinfopage.jsp?username=Smith&userempno=9876" flush="true" />

jsp:forward tag

The jsp:forward tag effectively terminates execution of the current page, discards its output, and
dispatches a new page—either an HTML page, a JSP page, or a servlet.

The JSP page must be buffered to use a jsp:forward tag; you cannot set buffer="none" in a page directive.
The action will clear the buffer and not output contents to the browser.

As with jsp:include, you can also have an action body with jsp:param tags, as shown in the second of the
following examples:
<jsp:forward page="/templates/userinfopage.jsp" />

or:

<jsp:forward page="/templates/userinfopage.jsp" >


<jsp:param name="username" value="Smith" />
<jsp:param name="userempno" value="9876" />
</jsp:forward>

jsp:plugin tag

The jsp:plugin tag results in the execution of a specified applet or JavaBean in the client browser,
preceded by a download of Java plugin software if necessary.

Specify configuration information, such as the applet to run and the code base, using jsp:plugin attributes.
The JSP container might provide a default URL for the download, but you can also specify attribute
nspluginurl="url" (for a Netscape browser) or iepluginurl="url" (for an Internet Explorer browser).

Use nested jsp:param tags between the jsp:params start-tag and end-tag to specify parameters to the applet
or JavaBean. (Note that the jsp:params start-tag and end-tag are not necessary when using jsp:param in a
jsp:include or jsp:forward action.)

Use a jsp:fallback start -tag and end-tag to delimit alternative text to execute if the plugin cannot run.

The following example, from the Sun Microsystems JavaServer Pages Specification, Version 1.2, shows
the use of an applet plugin:

<jsp:plugin type=applet code="Molecule.class" codebase="/html" >


<jsp:params>
<jsp:param name="molecule" value="molecules/benzene.mol" />
</jsp:params>
<jsp:fallback>
<p> Unable to start the plugin. </p>
</jsp:fallback>
</jsp:plugin>

Many additional parameters—such as ARCHIVE, HEIGHT, NAME, TITLE, and WIDTH—are allowed
in the jsp:plugin tag as well. Use of these parameters is according to the general HTML specification.

Bean Property Conversions from String Values

As noted earlier, when you use a JavaBean through a jsp:useBean tag in a JSP page, and then use a
jsp:setProperty tag to set a bean property, string input can be used to specify the value of a non-string
property through conversions that happen behind the scenes. There are two conversion scenarios, covered
in the following sections:

Typical Property Conversions


Conversions for Property Types with Property Editors

Typical Property Conversions

For a bean property that does not have an associated property editor, Table 1-1 shows how conversion is
accomplished when using a string value to set the property.

Table 1-1 Attribute Conversion Methods

Property Type Conversion

Boolean or boolean According to valueOf(String) method of Boolean class


Byte or byte According to valueOf(String) method of Byte class
Character or char According to charAt(0) method of String class (inputting an index value of 0)
Double or double According to valueOf(String) method of Double class
Integer or int According to valueOf(String) method of Integer class
Float or float According to valueOf(String) method of Float class
Long or long According to valueOf(String) method of Long class
Short or short According to valueOf(String) method of Short class
Object As if String constructor is called, using literal string input

The String instance is returned as an Object instance.

Conversions for Property Types with Property Editors

A bean property can have an associated property editor, which is a class that implements the
java.beans.PropertyEditor interface. Such classes can provide support for GUIs used in editing properties.
Generally speaking, there are standard property editors for standard Java types, and there can be user-
defined property editors for user-defined types. In the OC4J JSP implementation, however, only user-
defined property editors are searched for. Default property editors of the sun.beans.editors package are
not taken into account.

For information about property editors and how to associate a property editor with a type, you can refer to
the Sun Microsystems JavaBeans API Specification.

You can still use a string value to set a property that has an associated property editor, as specified in the
JavaBeans specification. In this situation, the method setAsText(String text) specified in the
PropertyEditor interface is used in converting from string input to a value of the appropriate type. If the
setAsText() method throws an IllegalArgumentException, the conversion will fail.
Custom Tag Libraries

In addition to the standard JSP tags discussed above, the JSP specification lets vendors define their own
tag libraries, and lets vendors implement a framework that allows customers to define their own tag
libraries as well.

A tag library defines a collection of custom tags and can be thought of as a JSP sub-language. Developers
can use tag libraries directly when manually coding a JSP page, but they might also be used automatically
by Java development tools. A standard tag library must be portable between different JSP container
implementations.

Import a tag library into a JSP page using the taglib directive introduced in "Directives".

Key concepts of standard JavaServer Pages support for JSP tag libraries include the following:

Tag library descriptor files

A tag library descriptor (TLD) file is an XML document that contains information about a tag library and
about individual tags of the library. The file name of a TLD has the .tld extension.

Tag handlers

A tag handler specifies the action of a custom tag and is an instance of a Java class that implements either
the Tag, IterationTag, or BodyTag interface in the standard javax.servlet.jsp.tagext package. Which
interface to implement depends on whether the tag has a body and whether the tag handler requires access
to the body content.

Scripting variables

Custom tag actions can create server-side objects available for use by the tag itself or by other scripting
elements such as scriptlets. This is accomplished by creating or updating scripting variables.

Details regarding scripting variables that a custom tag defines are specified in the TLD file or in a
subclass of the TagExtraInfo abstract class (in package javax.servlet.jsp.tagext). This document refers to a
subclass of TagExtraInfo as a tag-extra-info class. The JSP container uses instances of these classes
during translation.

Tag-library-validators

A tag-library-validator class has logic to validate any JSP page that uses the tag library, according to
specified constraints.

Event listeners

You can use servlet 2.3 event listeners with a tag library. This functionality is offered as a convenient
alternative to declaring listeners in the application web.xml file.

Use of web.xml for tag libraries


The Sun Microsystems Java Servlet Specification describes a standard deployment descriptor for servlets:
the web.xml file. JSP applications can use this file in specifying the location of a JSP tag library
descriptor file.

For JSP tag libraries, the web.xml file can include a taglib element and two subelements: taglib-uri and
taglib-location.

For information about these topics, see Chapter 8, "JSP Tag Libraries". For further information, see the
Sun Microsystems JavaServer Pages Specification.

For complete information about the tag libraries provided with OC4J, see the Oracle Application Server
Containers for J2EE JSP Tag Libraries and Utilities Reference.

JSP Execution

This section provides a top-level look at how a JSP page is run, including on-demand translation (the first
time a JSP page is run), the role of the JSP container and the servlet container, and error processing.

JSP Containers in a Nutshell

A JSP container is an entity that translates, executes, and processes JSP pages and delivers requests to
them.

The exact make-up of a JSP container varies from implementation to implementation, but it will consist
of a servlet or collection of servlets. The JSP container, therefore, is executed by a servlet container.
Servlet containers are summarized in "Servlet Containers".

A JSP container can be incorporated into a Web server if the Web server is written in Java, or the
container can be otherwise associated with and used by the Web server.

JSP Execution Models

There are two distinct execution models for JSP pages:

In most implementations and situations, the JSP container translates pages on demand before triggering
their execution; that is, at the time they are requested by the user.

In some scenarios, however, the developer might want to translate the pages in advance and deploy them
as working servlets. Command-line tools are available to translate the pages, load them, and publish them
to make them available for execution. You can have the translation occur either on the client or in the
server. When the user requests the JSP page, it is executed directly, with no translation necessary.

On-Demand Translation Model

It is typical to run JSP pages in an on-demand translation scenario. When a JSP page is requested from a
Web server that incorporates the JSP container, a front-end servlet is instantiated and invoked, assuming
proper Web server configuration. This servlet can be thought of as the front-end of the JSP container. In
OC4J, it is oracle.jsp.runtimev2.JspServlet.
JspServlet locates the JSP page, translates and compiles it if necessary (if the translated class does not
exist or has an earlier timestamp than the JSP page source), and triggers its execution.

Note that the Web server must be properly configured to map the *.jsp file name extension (in a URL) to
JspServlet. This is handled automatically during OC4J installation, as discussed in "JSP Container Setup".

Pretranslation Model

As an alternative to the typical on-demand scenario, developers might want to pretranslate their JSP pages
before deploying them. This can offer the following advantages, for example:

It can save time for the users when they first request a JSP page, because translation at execution time is
not necessary.

It is useful if you want to deploy binary files only, perhaps because the software is proprietary or you
have security concerns and you do not want to expose the code.

For more information, see "JSP Pretranslation" and "Deployment of Binary Files Only".

Oracle supplies the ojspc command-line utility for pretranslating JSP pages. This utility has options that
allow you to set an appropriate base directory for the output files, depending on how you want to deploy
the application. The ojspc utility is documented in "The ojspc Pretranslation Utility".

JSP Pages and On-Demand Translation

Presuming the typical on-demand translation scenario, a JSP page is usually executed as follows:

The user requests the JSP page through a URL ending with a .jsp file name.

Upon noting the .jsp file name extension in the URL, the servlet container of the Web server invokes the
JSP container.

The JSP container locates the JSP page and translates it if this is the first time it has been requested.
Translation includes producing servlet code in a .java file and then compiling the .java file to produce a
servlet .class file.

The servlet class generated by the JSP translator extends a class (provided by the JSP container) that
implements the javax.servlet.jsp.HttpJspPage interface (described in "Standard JSP Interfaces and
Methods"). The servlet class is referred to as the page implementation class. This document will refer to
instances of page implementation classes as JSP page instances.

Translating a JSP page into a servlet automatically incorporates standard servlet programming overhead
into the generated servlet code, such as implementing the HttpJspPage interface and generating code for
its service method.

The JSP container triggers instantiation and execution of the page implementation class.

The JSP page instance will then process the HTTP request, generate an HTTP response, and pass the
response back to the client.
Requesting a JSP Page

A JSP page can be requested either directly through a URL or indirectly through another Web page or
servlet.

Directly Requesting a JSP Page

As with a servlet or HTML page, the user can request a JSP page directly by URL. For example, suppose
you have a HelloWorld JSP page that is located under a myapp directory, as follows, where myapp is
mapped to the myapproot context path in the Web server:

myapp/dir1/HelloWorld.jsp

You can request it with a URL such as the following:

http://host:port/myapproot/dir1/HelloWorld.jsp

The first time the user requests HelloWorld.jsp, the JSP container triggers both translation and execution
of the page. With subsequent requests, the JSP container triggers page execution only; the translation step
is no longer necessary.

Indirectly Requesting a JSP Page

JSP pages, like servlets, can also be executed indirectly—linked from a regular HTML page or referenced
from another JSP page or from a servlet.

When invoking one JSP page from a JSP statement in another JSP page, the path can be either relative to
the application root—known as context-relative or application-relative—or relative to the invoking page
—known as page-relative. An application-relative path starts with "/"; a page-relative path does not.

Be aware that, typically, neither of these paths is the same path as used in a URL or HTML link.
Continuing the example in the preceding section, the path in an HTML link is the same as in the direct
URL request, as follows:

<a href="/myapp/dir1/HelloWorld.jsp" /a>

The application-relative path in a JSP statement is:

<jsp:include page="/dir1/HelloWorld.jsp" flush="true" />

The page-relative path to invoke HelloWorld.jsp from a JSP page in the same directory is:

<jsp:forward page="HelloWorld.jsp" />

("Standard Actions: JSP Tags" discusses the jsp:include and jsp:forward statements.)
UNIT-VIII DATABASE ACCESS
Database Programming in Java Using JDBC

An application that does not persist its data in a database is a rarity. Programming languages reflect this
trend. That's why all languages provide a robust and flexible library for database access. Java is no
exception.

Java provides the Java Database Connectivity (JDBC) API to access different databases. In this
discussion, I will be focusing on the basics of JDBC. I will start with the whys and wherefores of JDBC.
The next section will focus on the steps to use JDBC to access a database. In the final section, I will
develop an application that will access MySQL database server using the steps described in the previous
section. That's the outline for this discussion.

JDBC: What is it?

JDBC, which is short for Java Database Connectivity, can be defined as "An API for the Java
programming language that defines how a client may access a database." In other words, JDBC specifies
the ways and methods that are needed to access a database, more specifically a relational database such as
Oracle , MySQL, and others. The main aspect of JDBC is that it is a specification and not a product. So
different vendors (here RDBMS vendors) provide their own implementation for the specification.

For example, the JDBC implementation for Oracle database is provided by Oracle itself and the same is
the case for all others. The implementations provided by the vendors are known as JDBC Drivers. The
most important point to be kept in mind is that JDBC Drivers are installed at client-side and not at server-
side.

JDBC has been with the Java Standard Edition (JSE) from version 1.1. The latest version is 4 and is being
shipped with JSE 6. Regardless of the version, JDBC supports four types of implementations or drivers.
They are:

1. Type I or JDBC-ODBC Bridge

2. Type II or Partly Java Partly Native


3. Type III or Network Protocol Driver

4. Type IV or Pure Java Driver

The types are defined by how the driver provides communication between the application and the
database server. Here are the details.

A Type I Driver is also called a JDBC-ODBC Bridge. The reason is that in this case JDBC internally
makes calls to the ODBC. It is the ODBC that communicates with the database server. The job of JDBC
is to provide the queries to the ODBC in a form understandable by ODBC and to deliver the result
provided by ODBC to the application in a form that is understandable by the application. This Driver
works mainly with the Windows platform. This is the only type of Driver that is shipped with a Java
installation.

A Type II Driver uses the native API of the target database server to communicate with the server.
Hence it is known as a Native Protocol Driver as well as a Partly Java Partly Native Driver. This Driver
doesn't contain pure Java code as it uses the client-side API provided by the target database server. To call
the client-side API of the database, it uses JNI. However, since it doesn't have the overhead of calling
ODBC, a Type II Driver is faster than a Type I. Also, by using a Type II Driver, one can access
functionalities that are specific to the database server which is being used.

A Type III Driver is also known as Network Protocol Driver. Type III Drivers target the middleware.
The middleware then communicates with the database server. In essence, Type III Drivers are like Type I
with the exception that Type III Drivers are completely written in Java and use the network protocol of
the middleware instead of ODBC API. Type III Drivers are more secure since middleware is in the
picture. In a nutshell, in Type III Drivers the conversion logic is at the middleware level and not at the
client-side.

The Type IV Driver is known as a Pure Java Driver. It is comparable to Type II as it directly interacts
with the database server. Unlike Type II, Type IV doesn't use native API calls. Instead the API has been
written in Java by the vendor. Apart from being a pure Java implementation of database client API, a
Type IV Driver delegates the processing to the database server. That means at client side no processing
related to the database or SQL translation occurs. The only job the client does is connecting to the server,
passing the queries and input to the database server and getting the result back through the same
connection. Due to the delegation of all the processes to the server, the Type IV Driver is also known as
the Thin Client Driver.

The choice of which driver to use depends on the type of application that is being developed. For
example, if the application is web-based, the best option is Type IV as it releases the application server
from being a part of database transactions. In this case the application server would only have to provide
services to look up the name of the connection pool and maintain the pool. All other data-related
operations would be delegated to the database server. Next we will discuss the steps involved in using
JDBC.

Database Programming in Java Using JDBC - Accessing the Database using JDBC, Step by Step
The best part of using JDBC for database programming is that if one has the required type of driver,
regardless of the database server , the steps to connect and query the database remain more or less the
same. The steps to access database for a typical relational database server include:

1. Loading the driver. 


2. Creating a connection.
3. Instantiating a statement object.
4. Retrieving a resultset object.
5. Accessing the data from the resultset object.

All of these steps are the same for any database, be it Oracle or MySQL. The only change comes in the
query to be passed in step four. Here are the details.

STEP 1: Loading the Driver

The driver, regardless of type, can be loaded in one of two ways: using the Class loader, or explicitly
creating the instance. The difference between them, apart from how the driver is instantiated, is whether
the Driver has to be registered explicitly or not.

Using the Class loader

A class can be loaded at runtime using the forName() method of the Class class. The method accepts a
String having the name of the class to be loaded. Also once the class is loaded, calling the newInstance()
method of Class will create a new object of the loaded class. When the forName() method is used, the
Driver need not be registered explicitly. For example, to instantiate a driver of Type I using the forName
method, the statement would be:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

Explicitly creating the instance

The second way to load a driver is to instantiate it explicitly using the new operator. This is similar to that
of creating a new instance of any class. However, when the driver is being explicitly instantiated, one will
have to register the driver with the runtime environment using the register() method of the DriverManager
class. For example to load Type I Driver, the statements would be:

Driver driver=new sun.jdbc.odbc.JdbcOdbcDriver();

DriverManager.register(driver);

Or the statements can be merged as:

DriverManager.register(new sun.jdbc.odbc.JdbcOdbcDriver());

Once the driver is loaded and registered, the next step is to get a connection.
STEP 2:Creating a Connection

Once the driver has been loaded and registered, the next step is creating a connection with the database
server. The connection is created when one creates an instance of Connection. To get an instance of
Connection, the getConnection() method of the DriverManager class has to be called. In reality,
Connection is an interface and when getConnection() is called, the DriverManger provides an instance of
the proper implementing class to a reference variable of Connection. There are three forms of the
getConnection() method which are:

 getConnection(String url) - the URL contains all the necessary information including the URL
of the database server, user name and password.
 getConnection(String url, Properties info) - the URL contains only the URL to the server. The
user name and password are passed as part of the Properties instance. 
 getConnection(String url, String user, String password) - as with the previous form, this form
also contains the URL to the server in the URL parameter. The user name and password are
passed as separate parameters.

The URL is of the form jdbc:<subprotocol>:subname where subprotocol refers to the protocol used by the
database server and subname refers to the database to which the connection has to be made. For example,
an Oracle subname refers to the tablespace within the database server. So in order to create a connection
using the ODBC data source name or DSN, the statement would be:

Connection connection = DriverManager.getConnection ("jdbc:odbc:test", "test1", "test123");

where odbc is the subprotocol and test is the DSN which points to the database to connect to. The next
step is to create a statement object.

STEP 3: Instantiating a statement object

A statement represents a query to be executed at the database server against a database. In other words,
a statement object is responsible for executing a SQL query as well as retrieving the result of the executed
query. JDBC provides three types of statements based on the type of query to be executed. They are:
Statement, PreparedStatement, and CallableStatement. They are based on the type of query to be
executed.

Statement is the simplest type that represents a simple query. Its object can be instantiated using any of
the following forms of the createStatement() method of the Connection interface:

·createStatement() -

Returns a Statement object with default concurrency conditions.

·createStatement(int resultSetType, int resultSetConcurrency)-


Returns a Statement object with concurrency condition and type of ResultSet according to the values
passed as values. The most commonly used resulSetTypes include ResultSet.TYPE_FORWARD_ONLY
(indicating that the data can be read only in forward direction and once read cannot be moved back to a
previous data) and ResultSet.TYPE_SCROLL_SENSITIVE (indicating that the data can be read in both
forward and backward directions, and that the changes done by any other operation are visible instantly).
The commonly used values for resultSetConcurrency are CONCUR_READ_ONLY (indicating that
ResultSet may not be updated) and CONCUR_UPDATABLE (indicating that object may be updated).

For example, to create a Statement object that would provide a ResultSet object which is scrollable and
updatable, the statement would be

Statement statement = connection.createStatement(

ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

PreparedStatement conserves resources. Whenever a query is sent to the database server, it goes
through four steps: parsing the query, compiling the query, linking and executing the query. When a
statement object is used to execute a query all four steps are repeated again and again. This can create
resource hogging. The alternative to it is a PreparedStatement object. If a PreparedStatement object is
used, the first three steps are performed only once at the start and in successive calls; the values are then
passed to the linked query and it is executed. To create an object of PreparedStatement, any of the
following forms of prepareStatement can be used:

·prepareStatement(String query)-

This form accepts a parameterized SQL query as a parameter and returns an object of PreparedStatement.
"Select * from user where user_id=?" is an example of a parameterized query.

·prepareStatement(String query, int resultSetType, int resultSetConcurrency)-

This form is similar to the first form with the added options of specifying whether ResultSets are
scrollable and updatable or not. The values for the two parameters are the same as those described in the
Statement section.

For example, to create an instance of PreparedStatement which provides an updatable and scrollable
ResultSet, the statements would be:
String query= "Select * from user where user_id=?";

PreparedStatement pStatement = connection.prepareStatement(

query,

ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_UPDATABLE);

To call procedures and functions within a database, one can use CallableStatement. However, if the
underlying database doesn't support procedures and functions, then the CallableStatement object won't
work. For example, versions of MySQL database prior to 5.0 didn't support functions and procedures.
To create an object of CallableStatement, use any of the following forms of the prepareCall() method of
Connection:

·prepareCall(String query)-

This returns a CallableStatement object that can be used to execute a procedure or function, which is
passed as the query. The query is of the form "{sum(?,?)}" where sum is the function/procedure to be
called.

·prepareCall(String sql, int resultSetType, int resultSetConcurrency)-

To get a ResultSet which is both updatable and scrollable, this form can be used. The resultSetType and
resultSetConcurrency are same as that used with prepareStatement().

For example, to call a procedure whose name is sum, the statement would be

CallableStatement cStatement = connection.prepareCall(

"{sum(?,?)}");

The next step is to retrieve the ResultSet.

STEP 4:Retrieving the ResultSet object

The rows retrieved by the execution of a SQL query are given back by JDBC in the form of a ResultSet
object. A ResultSet contains all the rows retrieved by a query. To retrieve a ResultSet object, one can call
the executeQuery() method of the Statement object. If the Statement object is of the type
PreparedStatement, then executeQuery() without any argument needs to be called. If it is of the type
Statement, then a SQL query will have to be passed to the method. For example, to retrieve a ResultSet
from a Statement for the query "Select * from user", the code would be

ResultSet result = statement.executeQuery("Select * from user");


The next step is to get data from the ResultSet.

STEP 5:Accessing the data from the Resultset object

The specialty of ResultSet is that it can be iterated over as a collection and for each iteration, the data can
be accessed as it is an array using an index. A ResultSet object can be iterated over using its next()
method. During each iteration, one row is retrieved from the number of rows returned by the execution of
the SQL query. The columns within the row can be accessed using different forms of the get() method of
the ResultSet object. The forms depend upon the data-type of the column to be accessed such as
getString() if the column type is varchar, getInt() if the column type is int, and so on. Mostly getString() is
used to retrieve data from the columns. The argument that needs to be passed to the method is either a
string containing the column name or the integer value representing the index. The index starts from 1
and not 0.

For example, if the user table has a column named "name," then the statements to retrieve the values for
the "name" column would be

while(result.next){

System.out.println(result.getString("name));}

That completes the steps in using JDBC to access the database. Next we will look at an application that
will implement these steps to connect to MySQL.

The time for theorizing is over. Now let's look at implementing what has been discussed. The application
being developed has three classes:

 GenericDAO - Connects to the database and provides a Statement object. It is generic in the
sense that it accepts a driver name and URL as an argument of constructor.
 DataOp - Implements database operations.
 DAOTest - Tests the DAO and DataOp classes.

So here is the GenericDAO class. It accepts the driver class and URL to connect to as constructor
arguments along with the user name and password.

package jdbctest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class GenericDAO
{
Connection connection;
Statement statement;
public GenericDAO()
{
connection=null;
statement=null;
}
public GenericDAO(String driverClass,String connectionURL,String user,String password)
{
try
{
Class.forName(driverClass).newInstance();
connection=DriverManager.getConnection(connectionURL,user,password);
statement=connection.createStatement();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public void setStatement(Statement statement)
{
this.statement = statement;
}
public Statement getStatement()
{
return statement;
}
}

Next is the DataOp class. It has one method that operates on the user table. This class is not generic.
package jdbctest;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class DataOp
{
Statement statement;
public DataOp(Statement statement)
{
this.statement=statement;
}
public List getUserList(String user)
{
List list=new ArrayList();
try
{
ResultSet result=statement.executeQuery("Select * from user where user_id='"+user+"'");
 
while(result.next())
{
list.add(result.getString(1));
}
}
catch (SQLException e)
{
e.printStackTrace();
list=null;
}
return list;
}
}
Last is the class that tests the GenericDAO and DataOp classes. Here we are passing the driver name
corresponding to Type IV of MySQL JDBC driver and the corresponding URL.

package jdbctest;

public class DAOTest

public static void main(String args[])

//create instance of DAO class. Here we are using MySQL Type IV Driver

DAO dao=new
DAO("com.mysql.jdbc.Driver","jdbc:mysql://localhost/test","r

oot","root123");

//Creating instance of DataOp class

DataOp dataOp=new DataOp();

//calling the getUserList method for user whose id is 23

System.out.println(dataOp.getUserList("23"));

}
}
Uses of Package javax.sql:

Packages that use javax.sql

Provides the API for server side data source access and processing from the
javax.sql
JavaTM programming language. 

javax.sql.rowset Standard interfaces and base classes for JDBC RowSet implementations. 

The standard classes and interfaces that a third party vendor has to use in its
javax.sql.rowset.spi
implementation of a synchronization provider

Classes in javax.sql used by javax.sql

ConnectionEvent An Event object that provides information about the source of a connection-
          . related event

ConnectionEventListene
An object that registers to be notified of events generated by a
r
PooledConnection object
          .

PooledConnection
An object that provides hooks for connection pool management
          .

RowSet           The interface that adds support to the JDBC API for the JavaBeans TM
. component model

RowSetEvent
          An Event object generated when an event occurs to a RowSet object
.
RowSetInternal The interface that a RowSet object implements in order to present itself to a
          . RowSetReader or RowSetWriter object

RowSetListener An interface that must be implemented by a component that wants to be


           notified when a significant event happens in the life of a RowSet object.

RowSetMetaData           An object that contains information about the columns in a RowSet
object.

XAConnection
An object that provides support for distributed transactions
          .

RowSet
          The interface that adds support to the JDBC API for the JavaBeans TM component model.

RowSetEvent
          An Event object generated when an event occurs to a RowSet object.

RowSetListener
          An interface that must be implemented by a component that wants to be notified when a
significant event happens in the life of a RowSet object.

RowSetMetaData
          An object that contains information about the columns in a RowSet object.

RowSet
          The interface that adds support to the JDBC API for the JavaBeans TM component model.

RowSetReader
          The facility that a disconnected RowSet object calls on to populate itself with rows of data.

RowSetWriter
          An object that implements the RowSetWriter interface, called a writ

Accessing a database from a jsp page:


I am going to discuss the connectivity from MYSQL database with JSP.we take a example of Books
database. This database contains a table named books_details. This table contains three fields- id,
book_name& author. we starts from very beginning. First we learn how to create tables in MySQl
database after that we write a html page for inserting the values in 'books_details' table in database.
After submitting values a table will be showed that contains the book name and author name.
Database
The database in example consists of a single table of three columns or fields. The database name is
"books" and it contains information about books names & authors.

Table:books_details

         
  Book Name                   Author
ID

          
 Java I/O  Tim Ritchey
1.

            Java & XML,2  Brett McLaughlin


2. Edition   
            Java Swing, 2nd  Dave Wood,
3. Edition Marc Loy,

Start MYSQL prompt and type this SQL statement & press Enter-
MYSQL>CREATE DATABASE `books` ;
This will create "books" database.
Now we create table a table "books_details" in database "books".
                               
                                 MYSQL>CREATE TABLE `books_details` (
                                                `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
                                                `book_name` VARCHAR( 100 ) NOT NULL ,
                                               `author` VARCHAR( 100 ) NOT NULL ,
                                                PRIMARY KEY ( `id` ) 
                                                ) TYPE = MYISAM ;

This will create a table "books_details" in database "books"


JSP Code
The following code contains  html for user interface & the JSP backend-
<%@ page language="java" import="java.sql.*" %>

<%
String driver = "org.gjt.mm.mysql.Driver";
Class.forName(driver).newInstance();
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
try{
String url="jdbc:mysql://localhost/books?user=deepak&password=deepak";
con=DriverManager.getConnection(url);
stmt=con.createStatement();
}
catch(Exception e){
System.out.println(e.getMessage());
}

if(request.getParameter("action") != null){
String bookname=request.getParameter("bookname");
String author=request.getParameter("author");
stmt.executeUpdate("insert into books_details(book_name,author)
values('"+bookname+"','"+author+"')");
rst=stmt.executeQuery("select * from books_details");

%>

<html>
<body>
<center><h2>Books List</h2>
<table border="1" cellspacing="0" cellpadding="0">

<tr><td><b>S.No</b></td><td><b>Book Name</b></td><td><b>Author</.b></td></tr>
<% int no=1;

while(rst.next()){

%>
<tr><td><%=no%></td><td><%=rst.getString("book_name")%></td><td><%=rst.getString("author")
%></td></tr>
<%
no++;
}
rst.close();
stmt.close();
con.close();
%>
<tr>
</table>
</center>
<body>
<html>
<%}else{%>

<html>
<head>
<title>Book Entry FormDocument</title>

<script language="javascript">
function validate(objForm){

if(objForm.bookname.value.length==0){
alert("Please enter Book Name!");
objForm.bookname.focus();
return false;
}

if(objForm.author.value.length==0){
alert("Please enter Author name!");
objForm.author.focus();
return false;
}

return true;
}
</script>

</head>
<body><center>
<form action="BookEntryForm.jsp" method="post" name="entry" onSubmit="return
validate(this)">
<input type="hidden" value="list" name="action">
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<td>
<table>
<tr><td colspan="2"
align="center"><h2>Book Entry Form</h2></td></tr>
<tr><td colspan="2">&nbsp;</td></tr>
<tr><td>Book Name:</td><td><input
name="bookname" type="text" size="50"></td></tr>
<tr><td>Author:</td><td><input
name="author" type="text" size="50"></td></tr>
<tr><td colspan="2" align="center"><input
type="submit" value="Submit"></td></tr>
</table>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
<%}%>
Now we explain the above codes.
Declaring Variables: Java is a strongly typed language which means, that variables must be explicitly
declared before use and must be declared with the correct data types. In the above example code we
declare some variables for making connection. Theses variables are- 
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
The objects of type Connection, ResultSet and Statement are associated with the Java sql. "con" is a
Connection type object variable that will hold Connection type object. "rst" is a ResultSet type object
variable that will hold a result set returned by a database query. "stmt" is a object variable of Statement
.Statement Class methods allow to execute any query.  
Connection to database: The first task of this programmer is to load database driver. This is achieved
using the single line of code :-
String driver = "org.gjt.mm.mysql.Driver";
Class.forName(driver).newInstance();
The next task is to make a connection. This is done using the single line of code :-
String url="jdbc:mysql://localhost/books?user=<userName>&password=<password>";
con=DriverManager.getConnection(url);
When url is passed into getConnection() method of DriverManager class it  returns connection
object.   
Executing Query or Accessing data from database:
This is done using following code :-
stmt=con.createStatement(); //create a Statement object 
rst=stmt.executeQuery("select * from books_details");
stmt is the Statement type variable name and rst is the RecordSet type variable. A query is always
executed on a Statement object.
A Statement object is created by calling createStatement() method on connection object con. 
The two most important methods of this Statement interface are executeQuery() and executeUpdate().
The executeQuery() method executes an SQL statement that returns a single ResultSet object. The
executeUpdate() method executes an insert, update, and delete SQL statement. The method returns the
number of records affected by the SQL statement execution.
After creating a Statement ,a method executeQuery() or  executeUpdate() is called on Statement object
stmt and a SQL query string is passed in method executeQuery() or  executeUpdate().
This will return a ResultSet rst related to the query string.
Reading values from a ResultSet:
while(rst.next()){
  %>
<tr><td><%=no%></td><td><%=rst.getString("book_name")%></td><td><
%=rst.getString("author")%></td></tr>
<% 
}
The ResultSet  represents a table-like database result set. A ResultSet object maintains a cursor
pointing to its current row of data. Initially, the cursor is positioned before the first row. Therefore, to
access the first row in the ResultSet, you use the next() method. This method moves the cursor to the
next record and returns true if the next row is valid, and false if there are no more records in the
ResultSet object.
Other important methods are getXXX() methods, where XXX is the data type returned by the method
at the specified index, including String, long, and int. The indexing used is 1-based. For example, to
obtain the second column of type String, you use the following code:
resultSet.getString(2);
You can also use the getXXX() methods that accept a column name instead of a column index. For
instance, the following code retrieves the value of the column LastName of type String.
resultSet.getString("book_name");
The above example shows how you can use the next() method as well as the getString() method. Here
you retrieve the 'book_name' and 'author' columns from a table called 'books_details'. You then iterate
through the returned ResultSet and print all the book name and author name in the format " book name
| author " to the web page.
Summary:
This presents JDBC and shows how you can manipulate data in a relational database from your  JSP
page. To do this, you need to use  the java.sql package: DriverManager, Connection, Statement, and
ResultSet. Keep in mind, however, that this is only an introduction. To create a Web application, you
need  JDBC to use more features such as prepared statements and connection pooling.

JavaBeans Components in JSP Pages:

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

JavaServer Pages technology directly supports using JavaBeans components with JSP language elements.
You can easily create and initialize beans and get and set the values of their properties. This chapter
provides basic information about JavaBeans components and the JSP language elements for accessing
beans in your JSP pages. For further information about the JavaBeans component model

JavaBeans Component Design Conventions

JavaBeans component design conventions govern the properties of the class, and govern the public
methods that give access to the properties.

A JavaBeans component property can be

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


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

There is no requirement that a property be implemented by an instance variable; the property must simply
be accessible using public methods that conform to certain conventions:

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

In addition to the property methods, a JavaBeans component must define a constructor that takes no
parameters.

The Duke's Bookstore application JSP pages enter.jsp, bookdetails.jsp, catalog.jsp, and showcart.jsp use
the database.BookDB and database.BookDetails JavaBeans components. BookDB provides a JavaBeans
component front end to the enterprise bean BookDBEJB. Both beans are used extensively by bean-
oriented custom tags (see Tags That Define Scripting Variables). The JSP pages showcart.jsp and
cashier.jsp use cart.ShoppingCart to represent a user's shopping cart.

The JSP pages catalog.jsp, showcart.jsp, and cashier.jsp use the util.Currency JavaBeans component to
format currency in a locale-sensitive manner. The bean has two writable properties, locale and amount,
and one readable property, format. The format property does not correspond to any instance variable, but
returns a function of the locale and amount properties.

public class Currency {


private Locale locale;
private double amount;
public Currency() {
locale = null;
amount = 0.0;
}
public void setLocale(Locale l) {
locale = l;
}
public void setAmount(double a) {
amount = a;
}
public String getFormat() {
NumberFormat nf =
NumberFormat.getCurrencyInstance(locale);
return nf.format(amount);
}
}
Why Use a JavaBeans Component?

A JSP page can create and use any type of Java programming language object within a declaration or
scriptlet. The following scriptlet creates the bookstore shopping cart and stores it as a session attribute:
<%
ShoppingCart cart = (ShoppingCart)session.
getAttribute("cart");
// If the user has no cart, create a new one
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("cart", cart);
}
%>
If the shopping cart object conforms to JavaBeans conventions, JSP pages can use JSP elements to create
and access the object. For example, the Duke's Bookstore pages bookdetails.jsp, catalog.jsp, and
showcart.jsp replace the scriptlet with the much more concise JSP useBean element:
<jsp:useBean id="cart" class="cart.ShoppingCart"
scope="session"/>

Creating and Using a JavaBeans Component

You declare that your JSP page will use a JavaBeans component using either one of the following
formats:

<jsp:useBean id="beanName"
class="fully_qualified_classname" scope="scope"/>
or
<jsp:useBean id="beanName"
class="fully_qualified_classname" scope="scope">
<jsp:setProperty .../>
</jsp:useBean>
The second format is used when you want to include jsp:setProperty statements, described in the next
section, for initializing bean properties.

The jsp:useBean element declares that the page will use a bean that is stored within and accessible from
the specified scope, which can be application, session, request, or page. If no such bean exists, the
statement creates the bean and stores it as an attribute of the scope object (see Using Scope Objects). The
value of the id attribute determines the name of the bean in the scope and the identifier used to reference
the bean in other JSP elements and scriptlets.

Note: In the section JSP Scripting Elements we mentioned that you must import any classes and packages
used by a JSP page. This rule is slightly altered if the class is only referenced by useBean elements. In
these cases, you must only import the class if the class is in the unnamed package. For example, in What
Is JSP Page? (page 246), the page index.jsp imports the MyLocales class. However, in the Duke's
Bookstore example, all classes are contained in packages and thus are not explicitly imported.

The following element creates an instance of Currency if none exists, stores it as an attribute of the
session object, and makes the bean available throughout the session by the identifier currency:

<jsp:useBean id="currency" class="util.Currency"


scope="session"/>
Setting JavaBeans Component Properties

There are two ways to set JavaBeans component properties in a JSP page: with the jsp:setProperty
element or with a scriptlet

<% beanName.setPropName(value); %>


The syntax of the jsp:setProperty element depends on the source of the property value. Table 12-1
summarizes the various ways to set a property of a JavaBeans component using the jsp:setProperty
element.
Table 12-1 Setting JavaBeans Component Properties 

Value Source Element Syntax

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

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

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

<jsp:setProperty name="beanName"
Expression property="propName"
value="<%= expression %>"/>

1. beanName must be the same as that specified for the id attribute in a useBean element.
2. There must be a setPropName method in the JavaBeans component.
3. paramName must be a request parameter name.

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

Table 12-2 Valid Value Assignments 

Property Type Conversion on String Value


Bean property Uses setAsText(string-literal)

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

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

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

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

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

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

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

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

Object new String(string-literal)

You would use a runtime expression to set the value of a property whose type is a compound Java
programming language type. Recall from the section Expressions that a JSP expression is used to insert
the value of a scripting language expression, converted into a String, into the stream returned to the client.
When used within a setProperty element, an expression simply returns its value; no automatic conversion
is performed. As a consequence, the type returned from an expression must match or be castable to the
type of the property.

The Duke's Bookstore application demonstrates how to use the setProperty element and a scriptlet to set
the current book for the database helper bean. For example, bookstore3/bookdetails.jsp uses the form

<jsp:setProperty name="bookDB" property="bookId"/>

whereas bookstore2/bookdetails.jsp uses the form

<% bookDB.setBookId(bookId); %>


The following fragments from the page bookstore3/showcart.jsp illustrate how to initialize a currency
bean with a Locale object and amount determined by evaluating request-time expressions. Because the
first initialization is nested in a useBean element, it is only executed when the bean is created.
<jsp:useBean id="currency" class="util.Currency"
scope="session">
<jsp:setProperty name="currency" property="locale"
value="<%= request.getLocale() %>"/>
</jsp:useBean>

<jsp:setProperty name="currency" property="amount"


value="<%=cart.getTotal()%>"/>

Retrieving JavaBeans Component Properties

There are several ways to retrieve JavaBeans component properties. Two of the methods (the
jsp:getProperty element and an expression) convert the value of the property into a String and insert the
value into the current implicit out object:

 <jsp:getProperty name="beanName" property="propName"/>


 <%= beanName.getPropName() %>

For both methods, beanName must be the same as that specified for the id attribute in a useBean element,
and there must be a getPropName method in the JavaBeans component.

If you need to retrieve the value of a property without converting it and inserting it into the out object,
you must use a scriptlet:

<% Object o = beanName.getPropName(); %>


Note the differences between the expression and the scriptlet: the expression has an = after the opening
% and does not terminate with a semicolon, as does the scriptlet.

The Duke's Bookstore application demonstrates how to use both forms to retrieve the formatted currency
from the currency bean and insert it into the page. For example, bookstore3/showcart.jsp uses the form

<jsp:getProperty name="currency" property="format"/>

whereas bookstore2/showcart.jsp uses the form

<%= currency.getFormat() %>

The Duke's Bookstore application page bookstore2/showcart.jsp uses the following scriptlet to retrieve
the number of books from the shopping cart bean and open a conditional insertion of text into the output
stream:

<%
// Print a summary of the shopping cart
int num = cart.getNumberOfItems();
if (num > 0) {
%>
Although scriptlets are very useful for dynamic processing, using custom tags (see Chapter  13) to access
object properties and perform flow control is considered to be a better approach. For example,
bookstore3/showcart.jsp replaces the scriptlet with the following custom tags:
<bean:define id="num" name="cart" property="numberOfItems" />
<logic:greaterThan name="num" value="0" >

Figure 12-1 summarizes where various types of objects are stored and how those objects can be accessed
from a JSP page. Objects created by the jsp:useBean tag are stored as attributes of the scope objects and
can be accessed by jsp:[get|set]Property tags and in scriptlets and expressions. Objects created in
declarations and scriptlets are stored as variables of the JSP page's servlet class and can be accessed in
scriptlets and expressions.

Figure 12-1 Accessing Objects from a JSP Page

Struts Framework

This page will give you a short overview of Struts Framework and its main components. After finishing
reading this, continue on to the tutorial to create a simple Struts-based Web application.

What Is the Struts Framework?

The Struts Framework is a standard for developing well-architected Web applications. It has the
following features:

 Open source
 Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three
levels:
o Model: application state
o View: presentation of data (JSP, HTML)
o Controller: routing of the application flow
 Implements the JSP Model 2 Architecture
 Stores application routing information and request mapping in a single core file, struts-config.xml
The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the
developer.

Architecture Overview

All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration file struts-
config.xml is used by the controller to determine the routing of the flow. This flows consists of an
alternation between two transitions:

From View to A user clicks on a link or submits a form on an HTML or JSP page. The
Action controller receives the request, looks up the mapping for this request, and
forwards it to an action. The action in turn calls a Model layer (Business layer)
service or function.

From Action to After the call to an underlying function or service returns to the action class, the
View action forwards to a resource in the View layer and a page is displayed in a web
browser.
The diagram below describes the flow in more detail:

1. User clicks on a link in an HTML page.


2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and
routes to an action.
3. Action makes a call to a Model layer service.
4. Service makes a call to the Data layer (database) and the requested data is returned.
5. Service returns to the action.
6. Action forwards to a View resource (JSP page)
7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP
page.
8. JSP file is invoked and sent to the browser as HTML.
9. User is presented with a new HTML page in a web browser.
Struts Components

The Controller

This receives all incoming requests. Its primary function is the mapping of a request URI to an action
class selecting the proper application module. It's provided by the framework.
The struts-config.xml File

This file contains all of the routing and configuration information for the Struts application. This XML
file needs to be in the WEB-INF directory of the application.

Action Classes

It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs
and business services. Actions process a request and return an Action Forward object that identifies the
next component to invoke. They're part of the Controller layer, not the Model layer.

View Resources

View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource
bundles, JavaBeans, and Struts JSP tags.

Action Forms

These greatly simplify user form validation by capturing user data from the HTTP request. They act as a
"firewall" between forms (Web pages) and the application (actions). These components allow the
validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be
displayed.

Model Components

The Struts Framework has no built-in support for the Model layer. Struts supports any model
components:

 JavaBeans
 EJB
 CORBA
 JDO
 any other

You might also like