You are on page 1of 86

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

S. No Topic Page No.


1 List of Exercises 1
2 Introduction to HTML 2
3 Introduction to CSS 22
4 Introduction to JavaScript 23
5 Introduction to XML 33
6 Introduction to Java Beans 34
7 Introduction to Servlets 38
8 Introduction to JSPs 40
9 Introduction to JDBC 44
10 Exercise 1. Developing static pages of online bookstore 50
11 Exercise 2. Validating the Registration using Java Script 53
12 Exercise 3. Creating an XML Document for users information 54
13 Exercise 4. Creating a Java bean which converts Rs. Into American dollars 55
14 Exercise 5. Creating a bean to count number of clicks 56
15 Exercise 6. Creating a bean to design a calculator 57
16 Exercise 7. Creating a bean of traffic light 58
17 Exercise 8. Procedure for installation of Tomcat Server 59
18 Exercise 9. Program for servlet using cookies 65
19 Exercise 10.Program for servlet using sessions 67
20 Exercise 11.Program for JSP using cookies and sessions 69
21 Exercise 12.Implementing Helloworld using JSP 71
22 Bibliography 72

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

INTRODUCTION TO HTML

HTML stands for Hypertext Markup Language, and it is the language in which virtually all Web
pages are written.

Hypertext refers to the way in which Web pages (HTML documents) are linked together. When
you click a link in a Web page, you are using hypertext. It is this system of linking documents
that has made the World Wide Web the global phenomenon it has become.

Markup Language describes how HTML works. With a markup language, you simply "mark up"
a text document with tags that tell a Web browser how to structure and display it.

Elements

All HTML pages are made up of elements. For example, if you want to put a large heading on a
page, you would enclose it in a heading element <h1> </h1>. If you want to create a table, you
put the table information inside the table element <table> </table>. To construct a form, you
need the form element <form> </form>.

Tags

Often, you'll find the terms element and tag used interchangeably. An element is made up of
two tags: an opening tag and a closing tag.

Attributes and Values

An attribute is used to define the characteristics of an element and is placed inside the
element's opening tag.
For example, to set a paragraph's alignment, you would use the align attribute:

<p align=" ">This is an HTML paragraph.</p>

Values work together with attributes to complete the definition of an element's characteristics.
An attribute names a characteristic; a value describes it. If color is an attribute, red could be a
value. To instruct a browser to display red text, you would write it as follows:

<font color="red">This text will be red.</font>

If you wanted to center a paragraph, you could write it with this attribute-value combination:

<p align="center">This paragraph is now centered.</p>

Nesting

Often you will want to apply more than one element to a portion of your page.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
2
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
For example, because the paragraph <p> element does not accept a color attribute, if you want
to center it and have it display in red text you might use <p> and <font> together:

<p align="center"><font color="red">Centered, Red text.</font></p>

These elements, on the other hand, are overlapping:

<p align="center"><font color="red">Incorrect</p></font>

Understand Document Elements

The elements listed in the following could be called document elements because they describe
and define your HTML document.

<html> </html> Defines the beginning and end of the document.


<head> </head> This is the document header. It works like a storehouse of
important information about the document. This information
generally is not displayed in the document.
<title> </title> The title element is nested inside the header. It displays a page
title in the title bar at the top of the browser.
<body> </body> The main body of the Web page goes inside this element.
<meta> </meta> Goes inside the <head> element and is used to contain even
more detailed information about a document.
<link> </link> This element can be used to link the page to other documents,
such as a style sheet or a JavaScript file.
<style> </style> Allows you to embed style information in the document.
<frameset> </frameset> Used in place of the <head> element when you want to create
a "frames" page.

HTML enables you to define the structure of your page

CREATE A HTML TEMPLATE

An HTML template is simply a file that has all the basic elements for a Web page already
written. It's a good starting place to learn how to create an HTML document. An added benefit is
that it saves you the trouble of typing these elements every time you want to create a new page.
To create an HTML template, follow these steps:

1. Open Notepad or another text editor.


2. In the File menu, choose Save As.
3. Save the file as template.htm.
4. At the top of the page type <html>.
5. Now add the header element: <head> </head>.
6. Inside the header, type <title> </title>.
7. On the next line, type <body> </body>.
8. Finally, type </html>.
9. Click the Save icon.

Your HTML code should look something like this:


<html>
<head><title></title></head>
<body></body>
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
</html>
3
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
CREATE A WEB PAGE

Now that you have a template to work with, it's time to see just how easy it is to create your own
Web page.

1. Open template.htm in Notepad.


2. In between the <title> tags, type First Web Page.
3. In between the <body> tags, type This is my very first Web page!
4. Save the document as page1.htm.

Always save the file with either an .htm or .html extension. If you allow Notepad to save your file
as a text (.txt) file, a Web browser will not be able to read it.

View Your Page in a Web Browser

Once you have saved your page, it's time to see what it looks like. To display your page, follow
these steps:

1. Open your favorite Web browser and click the File menu.
2. In Netscape, choose the Open Page option. Internet Explorer users should choose
the Open option. If you're using another browser, it will have a similar choice.
3. If you're using Internet Explorer, click the Browse button. Netscape users should click
the Choose File button in the Open Page dialog box:

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
4
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
4. Navigate to the directory where you saved the file and click it.
5. IE users click OK; Netscape users click Open. Your file should be displayed in the
browser and should look like the sample in Figure 1-1.

Figure 1-1. Your first web page

Import Text into a HTML Page

Importing text into your HTML document is as easy as using the cut and paste options in
Windows.

1. Open template.htm in Notepad.


2. Open the document you want to import in your word processing program.
3. Select the text you want to import and copy it to the clipboard.
4. In Notepad, paste the text in between the <body> tags and then save the document
under a different file name (so you don't ruin your template).
5. Now, display the page in your browser.

When you import text into an HTML document, it loses any formatting it originally had. It will
simply appear as a solid block of text. If you want the material you imported to be organized or
formatted in some way, you'll have to do it with HTML elements.

Designate Headings with <h#> </h#>

The purpose of the heading element is to indicate different heading levels in a document. The
tags are made up of h with a number following it.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
5
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
For example, to specify a level one heading, you would write:

<h1>This is a level one heading.</h1>

A level two heading would look like this:

<h2>This is a level two heading.</h2>


HTML includes six heading levels: <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>. Although the
primary function of the <h#> element is to specify headings, it also often is used as a quick way
to tell a Web browser to display different sizes of text.

Try typing the following HTML code to see how the six heading levels will display on a Web
browser:

<html>
<head><title>The Heading Element</title></head>
<body>
<h1>This is a level one heading.</h1>
<h2>This is a level two heading.</h2>
<h3>This is a level three heading.</h3>
<h4>This is a level four heading.</h4>
<h5>This is a level five heading.</h5>
<h6>This is a level six heading.</h6>
</body>
</html>

Now, save this file as headings.htm and open it in your Web browser. Figure 1-2 shows you
what you should see when you display your page.

Figure 1-2. Six heading levels

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
6
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
To experiment further, try adding the align attribute to some of the headings and then check
your results. Change the level one heading to read:
<h1 align="center">This is a centered level one heading.</h1>

Now, modify the level three line to read this way:

<h3 align="right">This is a right-justified, level three heading.</h3>


Save the file and display it in your browser. It should look like Figure 1-3.

Figure 1-3. Heading levels with <h1> and <h3> repositioned

CONTROL TEXT WITH CHARACTER ELEMENTS

The character elements give you some basic controls over how text will display on a Web
browser.As you work with these elements, you will notice that some of them are named for how
a character actually will look when it appears on a browser (for example, the bold <b> element
for bold text). These are called physical elements because they describe the physical
appearance of the characters. Other text elements derive their names from the intended
function or purpose of the text (for example, the <strong> element also will display bold
typeface, but the element's name stands for strongly emphasized text). When a character
element is named this way, it is called a logical element because it describes the logical function
of the text.

Display Italicized Text

If you want to display text in italic, you have no less than six different elements to
choose from. Interestingly, each has its own distinct purpose:
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
7
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
<i> </i> The italics element is a physical element for displaying italicized text.
<em> </em> The emphasis element is a logical element for emphasizing important
portions of a document. It generally displays italicized text.
<cite> </cite> The citation element identifies a portion of your document as a reference
to an outside source.
<var> </var> This logical element indicates a variable, as might be used in computer
code.
<dfn> </dfn> This logical element identifies a portion of text as a defining instance of a
term. It also generally displays in italic.
<address> </address> You might use this logical element (which also renders your text
in italics) to set apart your address or personal information at the bottom
of a Web page. This element also generally adds a line break before and
after the address.

To see each of these elements in action, use your template to create a new HTML document,
and save it as text.htm. Then add the following lines in the <body> </body> portion of the page
to get the results shown in the following illustration:

<i>The italics element renders text in italics.</i><br />


<em>The emphasis element also produces italicized text.</em><br />
<cite>The cite element identifies a citation.</cite><br />
<var>The var element marks a variable.</var><br />
<dfn>The dfn element stands for a defining instance.</dfn><br />
<address>The address element marks off address or author information.</address><br />

Display Bold Text

Two different elements allow you to display boldface text:

<b> </b> The bold element is a physical element that allows you to render boldface
text.
<strong> </strong> The strong element also displays in bold. Strictly speaking, this
logical element indicates a heavier or stronger emphasis than does <b>,
but there is usually no difference in how the two look in a browser.

Try this line for a side-by-side comparison, like the one shown in the following illustration:

The <b>bold</b> element and the <strong>strong</strong> element are the same.<br />

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
8
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Display Big and Small Text

If you want a portion of text to appear slightly larger or smaller than the surrounding characters,
you can use the following elements:

<big> </big> This element displays text one font size larger than the surrounding text
<small> </small> This element reduces text by one font size.

To see the difference, put this line in your page.

The <big>big</big> element and the <small>small</small> element are useful tools.<br>

Create Superscripts and Subscripts

Sometimes you might have a need to add a superscript to your text. Maybe you'll be
documenting a source and want to insert a footnote reference at the end of a quotation. Or
perhaps you're a science nut and want to describe the molecular structure of water or carbon
dioxide. Then you'll need to know how to do a subscript.

<sup> </sup> This element creates a superscript.


<sub> </sub> This element forces text to display as a subscript.

To see these elements in action, insert the following line into your page. It will create a line with
both superscripts and subscripts, as in the following illustration:

The <sup>superscript</sup> and <sub>subscript</sub> elements raise and lower text.<br />

Display Monospaced Text

If you ever need to have your text display in a fixed-width or monospaced font, you have several
options available:

<tt> </tt> The "tt" in this case stands for teletype. It is a physical element that forces
text to display in a "typewriter," or courier style font. It derives its name,
obviously, from teletype machines.
<code> </code> This logical element not only displays in a courier, fixedwidth font, but
also indicates that the text is a portion of computer code.
<kbd> </kbd> Standing for keyboard, this logical element identifies its contents as
keyboard input. Generally, it displays as a monospaced font. Some
browsers also might display it as bold.
<samp> </samp> This is another logical element. It describes its contents as sample
output, most often rendering text in a monospaced font.

These elements all produce basically the same results. Add the following lines to your page to
see for yourself, and then compare your results with the following illustration.

The elements <tt>teletype,</tt> <code>code,</code>


<kbd>keyboard,</kbd> and <samp>sample</samp>all produce the same results.<br />

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
9
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Display Strikethroughs

If you want your text to display with a horizontal line drawn through it, you again
have more than one element to choose from:

<s> </s> This physical element will display text as "strikethrough."


<strike> </strike> The strike element is another physical element for producing
strikethrough text.
<del> </del> The deleted element is a logical element that indicates (by a
strikethrough) that the text has been deleted but left in the page.

Try this sample line to see how these three elements compare. Your screen should resemble
the following illustration.

To display <s>strikethrough</s> text, use the <strike>strike</strike> or the <del>deleted</del> elements.<br />

Display Underlined Text

If you want text to display underlined, you again have more than one option:

<u> </u> The underline element will render text with a line underneath.
<ins> </ins> The inserted text element is a logical element that indicates text that has
been inserted since the document was written.

Although either one of these elements will produce underlined text, the <ins> element is
supported only by Internet Explorer 4 and higher. If you want your text underlined, you are
better off using the <u> element.

Try this sample line to see how this works:

Use the <ins>inserted text</ins> element or the <u>underline</u> element for underlining text.

Retain Text Formatting with <pre>

Any special formatting, spacing, and line and paragraph divisions are lost when you bring text
into an HTML document. Elements are provided that will allow you to re-create that formatting.
But what if you don't want to go to all that trouble? By using the preformatted text element, you
can tell a browser to display your text exactly as you entered it. Simply enclose the text between
the <pre> </pre> tags, and the browser will leave it "as is." The downside of this element is that
the browser will display the text in a typewriter-style monospaced font.

To see how <pre> works, try adding the following lines to your sample page. The browser
retains whatever spacing you gave the characters:

<pre>This is a sample of preformatted text:


Thirty days hath September,
April, June, and November.
All the rest have thirty one,
Save February and it has twenty eight.</pre><br />

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
10
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
ORGANIZE YOUR MATERIAL WITH LISTS

HTML lists are a great way to organize material on your Web site. Whether you want to list the
ingredients of your favorite recipe, create a page of links with their descriptions, or offer step-by-
step instructions for washing a dog, you can use list elements to put your material in order.

Create a Bulleted List

You need two elements to create a bulleted (or unordered) list:

<ul> </ul> The unordered list element enables you to create the list.
<li> </li> You specify individual items on the list with the list item element.

Use your template to create a new HTML document. Save it in your HTML reference directory
as ulist.htm. Then, in between the <body> </body> tags:

1. Type an opening unordered list tag: <ul>.


2. Next, add a set of list item tags: <li> </li>.
3. For each new list item, add another set of <li> </li> tags.
4. When the list is complete, type a closing </ul> tag.

The code for a simple unordered list might look something like what you see here:

<html>
<head><title>Unordered Lists</title><head>
<body>
<ul>
<li>This is the first item</li>
<li>This is the second item</li>
<li>This is the third item</li>
<li>This is the fourth item</li>
</ul>
</body>
</html>

When you display your page in a browser, it will produce a bulleted list, like the one in the
illustration here:

When you display the list, your browser supplies a solid disc as the bullet for each item. If you
would prefer a circle or a square, you can specify it by using the type=" " attribute. To specify
the type of bullet for the entire list, put the attribute inside the opening <ul> tag:

To specify a square: <ul type="square">


To specify a circle: <ul type="circle">
To specify a disc: <ul type="disc">

You also can control the type of bullet for each separate item by putting the attribute inside the
<li> tag.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
11
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
For example, the following code will supply a different bullet for each item, as reflected in the
illustration that follows:

<ul>
<li type="square">This supplies a square.</li>
<li type="circle">This supplies a circle.</li>
<li type="disc">This supplies a disc.</li>
</ul>

Create a Multi-Level List

To create a list with multiple levels, you simply nest one or more unordered lists inside each
other. Save ulist.htm with the new name: ulist2.htm. Now make a multi-level list from it:

1. Inside the first set of <li> tags, type <ul>.


2. Add a line that says <li>This is a sub point.</li>.
3. Add another line that reads: <li>This is another sub point.</li>.
4. Close out the sub list with </ul>.

Your list should look like this:

<html>
<head><title>Unordered Lists</title><head>
<body>
<ul>
<li>This is the first item
<ul>
<li>This is a sub point</li>
<li>This is another sub point</li>
</ul></li>
<li>This is the second item
<ul>
<li>This is a sub point</li>
<li>This is another sub point</li>
</ul></li>
<li>This is the third item
<ul>
<li>This is a sub point</li>
<li>This is another sub point</li>
</ul></li>
</ul>
</body>
</html>

If you want to add another level of sub points, you can do it by nesting another complete list
inside each <li> </li> element where you want the next level. A multi-level list such as the one
rendered here will resemble Figure 1-4.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
12
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

Figure 1-4. A multi-level list depends on the proper nesting of elements

CREATE ORDERED LISTS

What if you want to display an outline with numbers and letters delineating the various points?
Or perhaps you want to create a list of instructions in numbered sequence. Lists that arrange
items in sequence by number or letter are called ordered lists in HTML and are quite similar in
their structure to unordered lists.

To create an ordered list, you need the following:

<ol> </ol> The ordered list element


<li> </li> The list item element

Use <ol> to Create a Numbered List

You can create a simple numbered list by enclosing a series of list items inside the ordered list
element, as in the following sample page. Use your template to open a new HTML page and
save it as olist.htm. Then type in this code:

<html>
<head><title>Ordered Lists</title></head>
<body>
<ol>
<li>Ordered lists display items with numbers.</li>
<li>But HTML doesn't sort the items.</li>
<li>It only numbers them.</li>
<li>You have to do the arranging yourself.</li>
</ol>
</body>
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
</html>
13
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
After you save your page, display it in your browser. You should see a numbered list like this:

When you display this in a browser, you will notice that the list is numbered in sequence. The
actual format depends on the browser you use, but normally it is simply a numbered list. One
important difference with numbered lists is that if you nest the lists to create multiple levels, the
browser uses the same numbering system throughout; it does not automatically change to a
different one with each level. You must use the type attribute to specify any changes you want.

Use the type Attribute to Specify Numbers or Letters

Just as you can instruct the browser to use different types of bullets in an unordered list, you
can tell the browser what types of letters or numbers to use. This is very useful if you want to
produce an outline in HTML, as you have a nice range of choices available. You specify
numbers or letters with the type=" " attribute, just as you did for unordered lists. To produce this:

<ul type="I"> Capitalized Roman numerals


<ul type="i"> Lowercase Roman numerals
<ul type="1"> Numbers (default)
<ul type="A"> Capital letters
<ul type="a"> Lowercase letters

As in unordered lists, if you place the type attribute inside the <ol> tag, you can specify your
preferences for the entire list. If you place the attribute inside a <li> tag, it will change only that
particular list item.

Use the start Attribute to Choose a Starting Number

What if you want to begin a list at a point other than 1 or A? All you need to do is include the
start=" " attribute at the point where you want to change the number or letter. The browser will
start the list at the number you choose and continue numbering from that point.

For example, if you want to start a list at the number 23, you might do it this way:

<ol type="1" start="23">

Create a new HTML document and save it as olist2. htm. Now, try typing the following code and
displaying it in your browser to see what a list like this might look like if you did it with Roman
numerals, starting at number 10:

<html>
<head><title>Ordered Lists</title></head>
<body>
<ol type="I" start="10">
<li>This is the tenth list item.</li>
<li>This is the eleventh list item.</li>
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
14
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
<li>This is the twelfth list item.</li>
<li>This is the thirteenth list item.</li>
</ol>
</body></html>

When you display this in your browser, the list will begin with the Roman numeral "X," as in the
following:

Create an Outline with <ol>

To present material in outline format in HTML takes a bit more thought and planning than it does
with an average word processor, but it will produce satisfying results. The following sample
HTML code will produce a 3-point Roman numeral outline with lettered sub points:

<html>
<head><title>A Sample Outline</title></head>
<body>
<ol type="I">
<li>First Main Point
<ol type="A">
<li>First Sub point</li>
<li>Second Sub point</li>
</ol></li>
<li>Second Main Point</li>
<li>Third Main Point</li>
</ol>
</body>
</html>

The following illustration shows how an outline would look on your Web browser:

Create Definition Lists with <dl>

<dl> </dl> The definition list element creates the list.


<dt> </dt> The definition term element identifies the term to be defined.
<dd> </dd> The definition description element sets off the definition.

To see how a definition list works, try typing in the following code and displaying it in your
browser. Save the file as dlist.htm:
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
15
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
<html>
<head><title>Definition Lists</title></head>
<body>
<h1>HTML Terms Defined</h1>
<dl>
<dt>HTML</dt>
<dd>HTML stands for HyperText Markup Language</dd>
<dt>Element</dt>
<dd>An <u>element</u> is made up of two tags.</dd>
<dt>Attribute</dt>
<dd>An <I>attribute</I> describes an element's characteristics</dd>
<dt>Value</dt>
<dd>A <b>value</b> identifies a specific characteristic</dd>
</dl>
</body>
</html>

Displayed in a browser, a definition list will look similar to the one in the following illustration:

.
Create Line Breaks with <br /> and Paragraphs with <p>

These elements are structural in nature and help you control how your text will be divided on the
page. The difference between the line break and the paragraph elements is that when you use
<br /> you're telling a browser to insert a line break and go to the next line. To insert a line
break, use the line break element <br />. The <p> element, on the other hand, will add a blank
line before it starts your new paragraph:

<p>Use the paragraph element to identify paragraphs.</p>

Insert Ruler Lines with <hr />

The horizontal rule element, <hr />, will draw a horizontal line wherever you place it.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
16
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Use the width Attribute to Specify Rule Length

For instance, you can specify the width of the rule by adding the width attribute:

<hr width="25%" />

This creates a rule that covers 25 percent of the screen and tells the browser to draw a
horizontal rule and to size it at 25% of the screen size. You can specify whatever percentage
you want. Another way to select the length of your rule is by the number of pixels (the little
"dots" that make up the pictures on your monitor). To use pixels instead of percentages, simply
include the number without the percent sign:

<hr width="200" />

This creates a rule that is 200 pixels wide.

Specify a Rule's Thickness with the size Attribute

You can specify the thickness of the rule with the size attribute, but this time you must use
pixels instead of percentages. Try modifying your rule to display 3 pixels thick (the default is 1
pixel):

<hr width="25%" size="3" />

Use the noshade Attribute to Turn Off a Rule's Shading

Some browsers display a horizontal rule with shading that gives it a 3D look. If you prefer your
rule to appear as a solid line, add the noshade attribute:

<hr width="25%" size="3" noshade />

Use the color Attribute to Select a Rule's Color

Some browsers will display rules in color. You can choose a color by adding the color attribute:

<hr width="25%" size="3" noshade color="blue" />

Example:

<html>
<head><title>Text Control Elements</title></head>
<body>
<p>In the past, you didn't need to enclose your paragraphs<br /> with the paragraph tags, but now it is advisable to
do so.<br /> Actually, HTML is forgiving enough that it wouldn't be<br /> a problem if you didn't, but you can't count
on that<br /> in the future, when XML rules.</p> <p>The line break tag gives you the ability<br /> to tell HTML where
to break your text<br />
instead of letting the browser do it for you.</p><hr /> <!-- Horizontal rule line here --> <p>To make use of the
horizontal rule, just place<br /> it wherever you want the rule to be.</p>
</body>
</html>

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
17
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Indent Text

When you want to indent text in a word processor, just press the TAB key. In HTML, it's not that
simple. Because Web browsers ignore normal text formatting instructions, you have to be
creative to indent text. Use &nbsp; to Add Spaces. The nonbreaking space entity (&nbsp;) will
instruct a browser to add spaces wherever you want them. However, most commonly it is used
to create an indent at the beginning of a paragraph. To use it, you type the characters &nbsp;
where you want the spaces inserted.

POSITION AND ALIGN TEXT

What do you do if you want to center your text or right-justify a block of text?

Use the align Attribute for Positioning Elements

The align attribute, used with many elements, will allow you to position text (or images) at the
left, center, or right of a page.
For example, to right-justify a single paragraph, add the align attribute to the <p> tag at the
beginning of the paragraph. The tag will look like this: <p align="right">. Everything between the
<p></p> tags would be right-justified.

Use <div> </div> to Position Large Blocks

The <div> element, used with the align attribute, enables you to right-justify a large block of text.
For example, to right-justify several paragraphs, you would simply enclose all the paragraphs
inside the <div> element:

<div align="right">Several Paragraphs</div>

Use <center> to Center Objects and Text

If all you want to do is center your text, the <center> </center> element is the easiest way to do
it. This element works the same way as the <div align="center"> tag. To see how it works,
simply replace your <div> tags with <center> tags.

Experiment with align, <div>, and <center>

Open a new file align.htm. Then enter the code listed here:

<html>
<head><title>Text Alignment</title></head>
<body>
<h1 align="center">The Align Attribute</h1>
<p>This paragraph is left-justified, because that<br />
is what the browser automatically chooses.</p>
<p align="center">This paragraph is centered, because<br />
you used the "center" value for the align attribute.</p>
<p align="right">This paragraph is right-justified because<br />
you used the "right" value for the align attribute.</p>
<hr align="center" width="50%">
<h1 align="center">The Div Element</h1>
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
18
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
<div align="right"><p>These paragraphs are all right-justified,<br />
but because you used the div element, you don't need to<br />
specify the alignment of each paragraph individually.</p>
<p>The div element is a great time-saver when you are<br />
wanting to control the position of a larger block of text</p></div>
<hr align="center" width="50%">
<h1 align="center">The Center Element</h1>
<center><p>And don't forget that the center element is<br />
a great shortcut for centering text.</p></center>
</body>
</html>

CONTROL FONTS WITH THE <font> ELEMENT

To choose or modify the font for a line, a portion of a page, or even an entire page,all you need
to do is enclose the text between <font> </font> tags and specify what changes you want to
make with the size, face, and color attributes. Whatever text is enclosed in the tags will be
changed according to your specifications.

Adjust Font Size with the size Attribute

You can specify seven different sizes for your fonts with the size attribute. These sizes are
conveniently numbered one through seven, with one being the smallest possible size and seven
the largest. It works somewhat the same way as the <h1> through <h6> elements you learned
about earlier, but in this case you get one extra size. The default or automatic font size is 3. To
see size in action, follow these steps:

1. In the HTML page that is already open, choose any paragraph and add the following
tag, just inside the <p> tag: <p><font size="7">.
2. Remember to put a closing </font> tag just inside the closing </p>.
3. Your code should look something like this:

<p><font size="7">Text</font></p>

4. Now view it in your browser. You will see that all the text within those tags is displayed
in a very large font.
5. Try substituting the numbers 1-6 in place of the 7 and see what kind of results you
get. Remember: 3 is the default or normal text size.

That seems easy enough. But what if you want to use a larger font size for the whole page
without having to bother with <font>? For that, you use <basefont />.

Use <basefont /> to Set Default Font Sizes

Remember that the default font setting for a Web page is 3. So, consider 3 to be in the middle
somewhere, an average font. Logically, then, the numbers 4-7 would represent fonts larger
than 3, whereas 1 and 2 would be smaller. Now, if you want a little more flexibility, <basefont />
can help. With the <basefont /> element, you can change the default font setting for the entire
page either higher or lower. So, if all your text should appear in a larger font size, you would put
the basefont element in your page like this:

<basefont size="5" />


Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
19
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
That means you have changed the default font setting from 3 to 5. Now, unless you specify
otherwise by using the <font> element, all your text will appear in this larger font. You can put it
in either the head or body of the page either will work. When you view your page, all the text will
display in whatever font setting you have chosen.

Example:

<html>
<head> <title>Font Size Experiment</title> </head>
<body>
<basefont size="5" />
<p>The default text size for this page is now<br />
basefont 5. That will result in some fairly large<br />
text</p>
<p><font size="3">By choosing a 3 value for<br />
this font, we have reset it to the default size.</p>
<p>Of course, we could have changed just
<font size="+4">one</font>
word<br />
if we'd wanted to.</p>
</body>
</html>

Control Font Styles with the face Attribute

The way to tell the browser to use a different font is with the face attribute. Wherever you want
to change fonts, simply enclose the text in the <font> element and specify the font face in the
first tag. To experiment with an Arial font instead of the default, Times New Roman, add this line
to the HTML page you have been working on:

<font face="Arial">This text is in an Arial font.</font>


<font face="Arial, Verdana">This gives the browser two choices</font>

Select Font Colors with the color Attribute

If you want to dress up your page with different-colored fonts, you can do it by adding the color
attribute to your font tag. Add this line to your HTML page to see a font displayed in red:

<font color="red">This font will be displayed in red</font>

Try adding a line with a font tag containing the hex code for blue:

<font color="#0000ff">This will produce a blue font.</font>

Example:

<html>
<head><title>Experiment with Fonts and Colors</title></head>
<body>
<basefont face="Arial" size="5" color="blue" />
<p>All the text on this page will display in a<br />
blue Arial font. The base size of the font is 5.</p>
<p><font face="Times New Roman" size="-2" color="black">
To change to a smaller, black Times New Roman font,
use the font<br />
element. The -2 in the size indicates
that we are reducing<br />
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
20
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
the font two settings relative to
the basefont of 5.</font></p>
<p>Just for fun<font color="mediumvioletred"> we're going<br />
to change the color of our original font.<br />
Also, did you notice that everything
after the closing font</font><br />
tag is back to the original setting
(except the size, of course).</p>
</body>
</html>

Link to Another Web Site with the Anchor Element, <a> </a>

Hypertext points to a precise location on the Internet by using a URL to identify where
information is and what should be done with it. But how do you create the link? That's where
HTML comes in. HTML stands for Hypertext Markup Language. You can create hypertext links
or hyperlinks using an element specially designed for that purpose: the anchor element, <a>
</a>.

A link is simply a connection between one hypertext document and another, created by
enclosing text or an image inside two anchor tags. However, the link must point somewhere, so
you also must include the href=" " attribute. Href stands for hypertext reference and is the place
where you put the URL or pointer, so your link has a destination. A link that doesn't point
anywhere will look like this:

<a href=" ">This link doesn't go anywhere</a>.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
21
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
CHAPTER 2

Introduction to CSS

Obviously, if the content of a page should be entirely contained within its HTML code, its style— or presentation—should be

fully described in the CSS code that's applied to the page.

CSS styles can be applied to your pages in three ways:

Inline Styles

<a href="evil.html" style="color: red;">

You can apply styles to your content as you create it, without having to switch gears and edit a
separate style sheet.

Embedded Styles

<style type="text/css">
.warning {
color: red;
}
</style>
.
<a href="evil.html" class="warning">

Embedded styles keep your markup clean, but tie your styles to a single document. In most
cases, you'll want to share your styles across multiple pages on your site, so it's best to steer
clear of this approach as well.

External Styles

<link rel="stylesheet" href="styles.css" />


.
<a href="evil.html" class="warning">
styles.css
.warning {
color: red;
}

External styles are really the way to go, because they let you share your styles between multiple
documents, they reduce the amount of code browsers need to download, and they also let you
modify the look of your site without having to get your hands dirty editing HTML.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
22
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
CHAPTER 3

Introduction to JavaScript

As with CSS, you can add JavaScript to your web pages in a number of ways:

- You can embed JavaScript code directly in your HTML content:

<a href="evil.html" onclick="JavaScript code here">

- You can include JavaScript code at the top of your HTML document in a <script> tag:

<script type="text/javascript"><!--//--><![CDATA[//><!--
JavaScript code here
//--><!]]></script>
.
<a href="evil.html" class="warning">

- You can put your JavaScript code in a separate file, then link to that file from as many HTML
documents as you like:

<script type="text/javascript" src="script.js"></script>


.
<a href="evil.html" class="warning">

Running a JavaScript Program

To include some JavaScript on an HTML page, we have to include a <script> tag inside the
head of the document. A script doesn't necessarily have to be JavaScript, so we need to tell the
browser what type of script we're including by adding a type attribute with a value of
text/javascript:

<html >
<head>
<title>The Running Man</title>
<script type="text/javascript">
</script>
</head>
</html>

You can put as much JavaScript code as you want inside that <script> tag—the browser will
execute it as soon as it has been downloaded:

<html >
<head>
<title>The Running Man</title>
<script type="text/javascript">
alert("Arnie says hi!");
</script>
</head>
</html>

Even though it's nice and easy to just type some JavaScript straight into your HTML code, it's
preferable to include your JavaScript in an external file. This approach provides several
advantages:
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
23
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

• It maintains the separation between content and behavior (HTML and JavaScript).
• It makes it easier to maintain your web pages.
• It allows you to easily reuse the same JavaScript programs on different pages of your
site.

To reference an external JavaScript file, you need to use the src attribute on the <script> tag:

<html>
<head>
<title>The Running Man</title>
<script type="text/javascript" src="example.js">
</script>
</head>
</html>

Any JavaScript that you might have included between your <script> and </script> tags can now
be put into that external file and the browser will download the file and run the code.

If you'd like to try out the little program above, create a new HTML document (or open the
closest one to hand) and insert the <script> tag inside the head. Once you've done that, put this
snippet into a file called example.js in the same directory or folder:

alert("Arnie says hi!");

Variables: Storing Data for your Program

In JavaScript, we create a variable by using the keyword var and specifying the name we want
to use:

var chameleon;

This is called declaring a variable. Having been declared, chameleon is ready to have some
data assigned to it. We can do this using the assignment operator (=), placing the variable
name on the left and the data on the right:

var chameleon;
chameleon = "blue";

This whole process can be shortened by declaring and assigning the variable in one go:

var chameleon = "blue";

If you've never referenced a particular variable name before, you can actually assign that
variable without declaring it using var:

chameleon = "blue";

The JavaScript interpreter will detect that this variable hasn't been declared before, and will
automatically declare it when you try to assign a value to it. At first glance, this statement seems
to do exactly the same thing as using the var keyword.

The var keyword has to be used only when you first declare a variable. If you want to change
the value of the variable later, you do so without var:

var chameleon = "blue";


Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
24
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
chameleon = "red";

You can use the value of a variable just by calling its name. Any occurrence of the variable
name will automatically be replaced with its value when the program is run:

var chameleon = "blue";


alert(chameleon);

The second statement in this program tells your browser to display an alert box with the
supplied value, which in this case will be the value of the variable chameleon, as shown below.

Variable Types: Different Types for Different Data

A lot of programming languages feature strictly typed variables. With these, you have to tell
the program what type of data the variable is going to hold when it's declared, and you can't
change a variable's type once it has been created.

JavaScript, however, is loosely typed—the language doesn't care what your variables hold. A
variable could start off holding a number, then change to holding a character, a word, or
anything else you want it to hold. Even though you don't have to declare the data type up front,
it's still vital to know what types of data a variable can store, so that you can use and manipulate
them properly inside your own programs. In JavaScript, you can work with numbers, strings,
Booleans, arrays and objects. We'll take a look at the first four of these types now, but you'll
have to wait till the end of the chapter to read about objects, because they're a bit trickier.

Numbers

To create a variable with numerical data, you just assign a number to a variable name:

var whole = 3;
var decimal = 3.14159265;

Floating point numbers can have as many decimal places as you want:

var shortDecimal = 3.1;


var longDecimal = 3.14159265358979323846264338327950288419716939937;

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
25
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
And both floats and integers can have negative values if you place a minus sign (-) in front of
them:

var negativeInt = -3;


var negativeFloat = -3.14159265;

Mathematical Operations

Numbers can be combined with all of the mathematical operations you'd expect: addition (+),
subtraction (-), multiplication (*), and division (/). They're written in fairly natural notation:

var addition = 4 + 6;
var subtraction = 6 - 4;
var multiplication = 5 * 9;
var division = 100 / 10;
var longEquation = 4 + 6 + 5 * 9 - 100 / 10;

The symbols that invoke these operations in JavaScript—+, -, *, and /—are called

Operators

var unbracketed = 4 + 6 * 5;
var bracketed = (4 + 6) * 5;

Here, the value of unbracketed will be 34, because 6 * 5 is calculated first. The value of
bracketed will be 50, because (4 + 6) is calculated first. You can freely combine integers and
floats in your calculations, but the result will always be a float:

var whole = 3;
var decimal = 3.14159265;
var decimal2 = decimal - whole;
var decimal3 = whole * decimal;

decimal2 now equals 0.14159265 and decimal3 equals 9.42477795.

If you divide two integers and the result is not a whole number, it will automatically become a
float:

var decimal = 5 / 4;

The value of decimal will be 1.25.

Calculations can also involve any combination of numbers or numerical variables:

var dozen = 12;


var halfDozen = dozen / 2;
var fullDozen = halfDozen + halfDozen;

Strings

A string is a series of characters of any length. Those characters could be letters, numbers,
symbols, punctuation marks, or spaces—basically anything you can find on your keyboard.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
26
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
To specify a string, we surround a series of characters with quote marks. These can either be
single or double straight quote marks,1 just as long as the opening quote mark matches the
closing quote mark:

var single = 'Just single quotes';


var double = "Just double quotes";
var crazyNumbers = "18 crazy numb3r5";
var crazyPunctuation = '~cr@zy_punctu&t!on';

Example:

var single = 'Just single quotes';


alert(single);

When you load the HTML page that this file's attached to, you'll see the alert shown below:

Arrays

It is an ordered structure for storing a group of values. You can think of an array as being like a
rack in which each slot is able to hold a distinct value. In order to create an array, we use the
special array markers, which are the opening and closing square brackets:

var rack = [];

The variable rack is now an array, but there's nothing stored in it. Each "slot" in an array is
actually called an element, and in order to put some data into an element you have to correctly
reference which element you want to put it in. This reference is called an index, which is a
number that represents an element's position in an array. The first element in an array has an
index of 0, which can be a little confusing at first, but it's just a programming quirk you have to
get used to. The second element has an index of 1, the third: 2, and so on.

To reference a particular element, we use the variable name, followed by an opening square
bracket, then the index and a closing square bracket, like this:

var rack = [];


rack[0] = "First";
rack[1] = "Second";

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
27
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
When we want to retrieve a particular element, we use the array-index notation just like a
normal variable name. So, if we had an array like the one above, we could create an alert box
displaying the value of the second element like this:

alert(rack[1]);

The resulting alert is shown below:

It's possible to populate an array when it's declared. We simply insert values, separated with
commas, between the square brackets:

var rack = ["First", "Second", "Third", "Fourth"];

That statement says that we should create an array—rack—that has four elements with the
values specified here. The first value will have an index of 0, the second value an index of 1,
and so on.

Arrays can contain any data type—not just strings—so you could have an array of numbers:

var numberArray = [1, 2, 3, 5, 8, 13, 21, 34];

You might have an array of strings:

var stringArray = ["Veni", "Vidi", "Vici"];

A mixed array, containing multiple data types, would look like this:

var mixedArray = [235, "Parramatta", "Road"];

Here's an array of arrays:

var subArray1 = ["Paris", "Lyon", "Nice"];


var subArray2 = ["Amsterdam", "Eindhoven", "Utrecht"];
var subArray3 = ["Madrid", "Barcelona", "Seville"];
var superArray = [subArray1, subArray2, subArray3];

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
28
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
CONDITIONS AND LOOPS: CONTROLLING PROGRAM FLOW

Conditions: Making Decisions


if Statements

The most common conditional statement is an if statement. An if statement checks a condition,


and if that condition is met, allows the program to execute some code. If the condition isn't met,
the code is skipped.

The flow of a program through an if statement can be visualized as shown below:

Written as code, if statements take this form:

if (condition)
{
conditional code;
}

An if statement allows you to execute some code when a condition is met, but doesn't offer any
alternative code for cases when the condition isn't met. That's the purpose of the else
statement.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
29
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
In an if-else statement, you begin just as you would for an if statement, but immediately after the
closing brace of the if, you include an else, which specifies code to be executed when the
condition of the if statement fails:

if (condition)
{
conditional code;
}
else
{
alternative conditional code;
}

while Loops

while is the simplest of the loops. All it needs is a condition, and some conditional code:

while (condition)
{
conditional code;
}

When the program first encounters the while loop, it checks the condition. If the condition
evaluates
VijaytoVarma,CSE,ASTRA,Bandlaguda,Hyderabad.
true, the conditional code will be executed. When the program reaches the end of
30
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
the conditional code, it goes back up to the condition, checks it, and if it evaluates to true, the
conditional code will be executed … and so on, as the following figure shows.

do-while Loops

A do-while loop behaves almost identically to a while loop, with one key difference: the
conditional code is placed before the condition, so the conditional code is always executed at
least once, even if the condition is immediately false. The conditional code is placed inside the
curly braces of the do; the while statement contains the condition right after that:

do
{
conditional code;
}
while (condition);

The flow of the program can be described as in the following figure.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
31
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
32
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
CHAPTER 4

Introduction to XML
XML Is Extensible

HTML is a "fixed" language. That is, you can't modify it to suit your own purposes or needs.
HTML has a set structure that you must follow if you want your pages to work. With HTML you
have a certain collection of elements and attributes with which to work, and you cannot
customize it by adding your own elements. XML, on the other hand, is a meta language in its
own right. You don't use XML to create Web pages; you use XML to create your own "tags."
Then you use your own tags to create the Web pages. That's where the term "extensible"
comes in. You extend XML by creating other markup languages with it.

XML Can Be Used for More than Web Pages

XML is much more than a fancy new way of creating Web pages. Because it is a meta
language, XML can be used to write markup languages for many different kinds of applications,
such as ATM machines, databases, and much more. It is a powerful tool for creating other
languages and works much like its parent language, SGML. XML's advantage over SGML is
that while SGML is extremely complicated, XML is relatively easy to learn and use.

For example, the following code listing provides an example of how the markup in an XML
document might look:

<webpage>
<heading>Welcome to my XML page</heading>
<paragraph1>This is my page of the future.</paragraph1>
<logo> <!-- This will display a logo --> </logo>
<paragraph2>It is written in XML.</paragraph2>
<closing>Good bye!</closing>
</webpage>

Another example demonstrates the possibilities for using XML to create a database markup
language. Suppose an XML-savvy librarian decided to create a "Library Markup Language"
(LML); it might look something like this:

<book>
<title>Friendly Revenge</title>
<author>James H. Pence</author>
<publisher>Hard Shell Word Factory</publisher>
<genre>Young Adult Suspense</genre>
<catalog>F-YA PE</catalog>
<format>Ebook</format>
<isbn>ISBN: 1-58200-518-4</isbn>
</book>

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
33
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

INTRODUCTION TO 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. They are used to encapsulate many objects into a single object (the bean),
so that they can be passed around as a single bean object instead of as multiple individual objects.

The Component Model


Components are self-contained elements of software that can be controlled dynamically and
assembled to form applications. But that's not the end of it. These components must also
interoperate according to a set of rules and guidelines. They must behave in ways that are
expected. It's like a society of software citizens. The citizens (components) bring functionality,
while the society (environment) brings structure and order.
JavaBeans is Java's component model. It allows users to construct applications by piecing
components together either programmatically or visually (or both). Support of visual
programming is paramount to the component model; it's what makes component-based software
development truly powerful.
The model is made up of an architecture and an API (Application Programming Interface).
Together, these elements provide a structure whereby components can be combined to create an
application. This environment provides services and rules, the framework that allows components
to participate properly. This means that components are provided with the tools necessary to work
in the environment, and they exhibit certain behaviors that identify them as such. One very
important aspect of this structure is containment. A container provides a context in which
components can interact. A common example would be a panel that provides layout management
or mediation of interactions for visual components. Of course, containers themselves can be
components.

Persistence
Generally, all components have state. The thermostat component has state that represents the
comfort temperature. If the thermostat were a software component of a computer-based heating
control system, we would want the value of the comfort temperature to be stored on a non-volatile
storage medium (such as the hard disk). This way if we shut down the application and brought it
back up again, the thermostat control would still be set to 70 degrees. The visual representation
and position of the thermostat relative to other components in the application would be restored as
well.
Components must be able to participate in their container's persistence mechanism so that all
components in the application can provide application-wide persistence in a uniform way. If
every component were to implement its own method of persistence, it would be impossible
for an application container to use components in a general way. This wouldn't be an issue if
reuse weren't the goal. If we were building a monolithic temperature control system we
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
might create an application-specific mechanism for storing state. But we want to build the
thermostat component so that it can be used again in JavaBeans Architecture.

34

JavaBeans is an architecture for both using and building components in Java. This architecture
supports the features of software reuse, component models, and object orientation. One of the
most important features of JavaBeans is that it does not alter the existing Java language. If you
know how to write software in Java, you know how to use and create Beans. The strengths of Java
are built upon and extended to create the JavaBeans component architecture.
Although Beans are intended to work in a visual application development tool, they don't
necessarily have a visual representation at run-time (although many will). What this does mean is
that Beans must allow their property values to be changed through some type of visual interface,
and their methods and events should be exposed so that the development tool can write code
capable of manipulating the component when the application is executed.
Creating a Bean doesn't require any advanced concepts. So before I go any further, here is some
code that implements a simple Bean:
public class MyBean implements java.io.Serializable
{
protected int theValue;

public MyBean()
{
}

public void setMyValue(int newValue)


{
theValue = newValue;
}

public int getMyValue()


{
return theValue;
}
}
This is a real Bean named MyBean that has state (the variable theValue) that will automatically be
saved and restored by the JavaBeans persistence mechanism, and it has a property named
MyValue that is usable by a visual programming environment. This Bean doesn't have any visual
representation, but that isn't a requirement for a JavaBean component.
JavaSoft is using the slogan "Write once, use everywhere." Of course "everywhere" means
everywhere the Java run-time environment is available. But this is very important. What it means
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
is that the entire run-time environment required by JavaBeans is part of the Java platform. No
special libraries or classes have to be distributed with your components. The JavaBeans class
libraries provide a rich set of default behaviors for simple components (such as the one shown
earlier). This means that you don't have to spend your time building a lot of support for the Beans
environment into your code.
ther application, so we have to use a standard mechanism for persistence.

35

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

Compact and Easy


JavaBeans components are simple to create and easy to use. This is an important goal of the
JavaBeans architecture. It doesn't take very much to write a simple Bean, and such a Bean is
lightweightit doesn't have to carry around a lot of inherited baggage just to support the Beans
environment. If a Bean does not require the advanced features of the architecture, it doesn't get
them, nor does it get the code that goes with them. This is an important concept. The JavaBeans
architecture scales upward in complexity, not downward like other component models. This
means it really is easy to create a simple Bean. (The previous example shows just how simple a
Bean can be.)

Portable
Since JavaBeans components are built purely in Java, they are fully portable to any platform that
supports the Java run-time environment. All platform specifics, as well as support for JavaBeans,
are implemented by the Java virtual machine. You can be sure that when you develop a
component using JavaBeans it will be usable on all of the platforms that support Java (version 1.1
and beyond). These range from workstation applications and web browsers to servers, and even to
devices such as PDAs and set-top boxes.

Properties, Methods, and Events


Properties are attributes of a Bean that are referenced by name. These properties are usually read
and written by calling methods on the Bean specifically created for that purpose. A property of the
thermostat component mentioned earlier in the chapter could be the comfort temperature. A
programmer would set or get the value of this property through method calls, while an application
developer using a visual development tool would manipulate the value of this property using a
visual property editor.
The methods of a Bean are just the Java methods exposed by the class that implements the Bean.
These methods represent the interface used to access and manipulate the component. Usually, the
set of public methods defined by the class will map directly to the supported methods for the
Bean, although the Bean developer can choose to expose only a subset of the public methods.
Events are the mechanism used by one component to send notifications to another. One
component can register its interest in the events generated by another. Whenever the event occurs,
the interested component will be notified by having one of its methods invoked. The process of
registering interest in an event is carried out simply by calling the appropriate method on the
component that is the source of the event. In turn, when an event occurs a method will be invoked
on the component that registered its interest. In most cases, more than one component can register
for event notifications from a single source. The component that is interested in event
notifications is said to be listening for the event.

Introspection
Introspection is the process of exposing the properties, methods, and events that a JavaBean
component supports. This process is used at run-time, as well as by a visual development tool at
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
36
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
design-time. The default behavior of this process allows for the automatic introspection of any
Bean. A low-level reflection mechanism is used to analyze the Bean's class to determine its
methods. Next it applies some simple design patterns to determine the properties and events that
are supported. To take advantage of reflection, you only need to follow a coding style that
matches the design pattern. This is an important feature of JavaBeans. It means that you

don't have to do anything more than code your methods using a simple convention. If you do,
your Beans will automatically support introspection without you having to write any extra code.
Design patterns are explained in more detail later in the chapter.

This technique may not be sufficient or suitable for every Bean. Instead, you can choose to
implement a BeanInfo class which provides descriptive information about its associated Bean
explicitly. This is obviously more work than using the default behavior, but it might be necessary
to describe a complex Bean properly. It is important to note that the BeanInfo class is separate
from the Bean that it is describing. This is done so that it is not necessary to carry the baggage of
the BeanInfo within the Bean itself.
If you're writing a development tool, an Introspector class is provided as part of the Beans class
library. You don't have to write the code to accomplish the analysis, and every tool vendor uses
the same technique to analyze a Bean. This is important to us as programmers because we want to
be able to choose our development tools and know that the properties, methods, and events that
are exposed for a given component will always be the same.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

37
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

INTRODUCTION TO SERVELETS

The Java Servlet API allows a software developer to add dynamic content to a Web server using
the Java platform. The generated content is commonly HTML, but may be other data such as
XML. Servlets are the Java counterpart to non-Java dynamic Web content technologies such as
PHP, CGI and ASP.NET. Servlets can maintain state across many server transactions by using
HTTP cookies, session variables or URL rewriting.
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.
A Servlet is an object that receives a request and generates a response based on that request. The
basic servlet package defines Java objects to represent servlet requests and responses, as well as
objects to reflect the servlet's configuration parameters and execution environment. The package
javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including
session management objects that track multiple requests and responses between the Web server
and a client. Servlets may be packaged in a WAR file as a Web application.
Servlets can be generated automatically by JavaServer Pages (JSP) compiler, or alternately by
template engines such as WebMacro. Often servlets are used in conjunction with JSPs in a pattern
called "Model 2", which is a flavor of the model-view-controller pattern.

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 which takes the servlet out of service. The
destroy() method like init() is called only once in the lifecycle of a Servlet.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

38

Here is a simple servlet that just generates HTML


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 either the ServletConfig 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.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
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.

39

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

INTRODUCTION TO JAVA SERVER PAGES

JavaServer Pages (JSP) is a Java technology that allows software developers to dynamically
generate HTML, XML or other types of documents in response to a Web client request. The
technology allows Java code and certain pre-defined actions to be embedded into static content.
The JSP syntax adds additional XML-like tags, called JSP actions, to be used to invoke built-in
functionality. Additionally, the technology allows for the creation of JSP tag libraries that act as
extensions to the standard HTML or XML tags. Tag libraries provide a platform independent way
of extending the capabilities of a Web server.
JSPs are compiled into Java Servlets by a JSP compiler. A JSP compiler may generate a servlet in
Java code that is then compiled by the Java compiler, or it may generate byte code for the servlet
directly. JSPs can also be interpreted on-the-fly, reducing the time taken to reload changes.

JSP syntax
A JavaServer Page may be broken down into the following pieces:
• static data such as HTML
• JSP directives such as the include directive
• JSP scripting elements and variables
• JSP actions
• custom tags with correct library
JSP directives control how the JSP compiler generates the servlet. The following directives are
available:
include
The include directive informs the JSP compiler to include a complete file into the current
file. It is as if the contents of the included file were pasted directly into the original file.
This functionality is similar to the one provided by the C preprocessor. Included files
generally have the extension "jspf" (for JSP Fragment):

<%@ include file="somefile.jsp" %>

page
The page directive has several attributes.
import
Results in a Java import statement being inserted into the resulting file.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
contentType
specifies the content that is generated. This should be used if HTML is not used or if the
character set is not the default character set.
errorPage
Indicates the page that will be shown if an exception occurs while processing the
40

HTTP request.

isErrorPage
If set to true, it indicates that this is the error page. Default value is false.

isThreadSafe
Indicates if the resulting servlet is thread safe.
40
autoFlush
To autoflush the contents.A value of true, the default, indicates that the buffer
should be flushed when it is full. A value of false, rarely used, indicates that an exception
should be thrown when the buffer overflows. A value of false is illegal when also using
buffer="none".

session
To maintain session. A value of true (the default) indicates that the predefined
variable session (of type HttpSession) should be bound to the existing session if one exists,
otherwise a new session should be created and bound to it. A value of false indicates that
no sessions will be used, and attempts to access the variable session will result in errors at
the time the JSP page is translated into a servlet.

buffer 40
To set Buffer Size. The default is 8k and it is advisable that you increase it.

language
Defines the scripting language used in scriptlets, expressions and
declarations. Right now, the only possible value is "java".

extends
Defines the superclass of the class this JSP will become. You won't use this
unless you REALLY know what you're doing - it overrides the class hierarchy provided by
the Container.

info
Defines a String that gets put into the translated page, just so that you can
get it using the generated servlet's inherited getServletInfo() method.

pageEncoding

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Defines the character encoding for the JSP. The default is "ISO-8859-
1"(unless the contentType attribute already defines a character encoding, or the page uses
XML document syntax).

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


<%@ page contentType="text/html" %> <%-- example contentType --%>
<%@ page isErrorPage="false" %> <%-- example for non error page --%>
<%@ page isThreadSafe="true" %> <%-- example for a thread safe JSP --%>
<%@ page session="true" %> <%-- example for using session binding --%>
<%@ page autoFlush="true" %> <%-- example for setting autoFlush --%>
<%@ page buffer="20kb" %> <%-- example for setting Buffer Size --%>

41

JSP scripting elements and objects

Scripting elements
There are three basic kinds of scripting elements that allow java code to be inserted directly into
the servlet.
• A declaration tag places a variable definition inside the body of the java servlet class.
Static data members may be defined as well. Also inner classes should be defined here.
<%! int serverInstanceVariable = 1; %>
Declaration tags also allow methods to be defined.
<%!
/**
* Converts the Object into a string or if
* the Object is null, it returns the empty string.
*/
public String toStringOrBlank( Object obj ){
if(obj != null){
return obj.toString();
}
return "";
}
%>

A scriptlet tag places the contained statements inside the _jspService() method of the java servlet
class.
• An expression tag places an expression to be evaluated inside the java servlet class.
Expressions should not be terminated with a semi-colon .
<%= "expanded inline data " + 1 %>

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
• Also we can use the following tag to give comments in jsp:
<%-- give your comments here --%>

JSP actions
JSP actions are XML tags that invoke built-in web server functionality. They are executed at
runtime. Some are standard and some are custom (which are developed by Java developers). The
following list contains the standard ones:
jsp:include
Similar to a subroutine, the Java servlet temporarily hands the request and response off to
the specified JavaServer Page. Control will then return to the current JSP, once the other
JSP has finished. Using this, JSP code will be shared between multiple other JSPs, rather
than duplicated.

jsp:param
Can be used inside a jsp:include, jsp:forward or jsp:params block. Specifies a parameter
that will be added to the request's current parameters.

42

jsp:forward
Used to hand off the request and response to another JSP or servlet. Control will never
return to the current JSP.

jsp:getProperty
Gets a property from the specified JavaBean.

jsp:setProperty
Sets a property in the specified JavaBean.

jsp:useBean
Creates or re-uses a JavaBean available to the JSP page.

Examples of tags

jsp:include

<html>
<head></head>
<body>

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
<jsp:include page="mycommon.jsp" >
<jsp:param name="extraparam" value="myvalue" />
</jsp:include>
name:<%=request.getParameter("extraparam")%>
</body>
</html>

jsp:forward

<jsp:forward page="subpage.jsp" >


<jsp:param name="forwardedFrom" value="this.jsp" />
</jsp:forward>
In this forwarding example, the request is forwarded to "subpage.jsp". The request handling does
not return to this page.

43

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

JAVA DATABASE CONNECTIVITY


Java Database Connectivity (JDBC) is an API for the Java programming language that defines
how a client may access a database. It provides methods for querying and updating data in a
database. JDBC is oriented towards relational databases.
The Java 2 Platform, Standard Edition, version 1.4 (J2SE) includes the JDBC 3.0 API together
with a reference implementation JDBC-to-ODBC Bridge, enabling connections to any ODBC-
accessible data source in the JVM host environment. This Bridge is native code (not Java), closed
source, and only appropriate for experimental use and for situations in which no other driver is
available, not least because it provides only a limited subset of the JDBC 3.0 API, as it was
originally built and shipped with JDBC 1.0 for use with old ODBC v2.0 drivers (ODBC v3.0 was
released in 1996.
JDBC has been part of the Java Standard Edition since the release of JDK 1.1. The JDBC classes
are contained in the Java package java.sql. Starting with version 3.0, JDBC has been developed
under the Java Community Process. JSR 54 specifies JDBC 3.0 (included in J2SE 1.4), JSR 114
specifies the JDBC Rowset additions, and JSR 221 is the specification of JDBC 4.0 (included in
Java SE 6)
JDBC allows multiple implementations to exist and be used by the same application. The API
provides a mechanism for dynamically loading the correct Java packages and registering them
with the JDBC Driver Manager. The Driver Manager is used as a connection factory for creating
JDBC connections.
JDBC connections support creating and executing statements. These may be update statements
such as SQL's CREATE, INSERT, UPDATE and DELETE, or they may be query statements
such as SELECT. Additionally, stored procedures may be invoked through a JDBC connection.
JDBC represents statements using one of the following classes:
• Statement – the statement is sent to the database server each and every time.
• PreparedStatement – the statement is cached and then the execution path is pre determined
on the database server allowing it to be executed multiple times in an efficient manner.
• CallableStatement – used for executing stored procedures on the database.
Update statements such as INSERT, UPDATE and DELETE return an update count that indicates
how many rows were affected in the database. These statements do not return any other
information.
Query statements return a JDBC row result set. The row result set is used to walk over the result
set. Individual columns in a row are retrieved either by name or by column number. There may be
any number of rows in the result set. The row result set has metadata that describes the names of
the columns and their types.
There is an extension to the basic JDBC API in the javax.sql

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

44

Example
The method Class.forName(String) is used to load the JDBC driver class. The line below causes
the JDBC driver from some jdbc vendor to be loaded into the application. (Some JVMs also
require the class to be instantiated with .newInstance().)
Class.forName( "com.somejdbcvendor.TheirJdbcDriver" );
In JDBC 4.0, it's no longer necessary to explicitly load JDBC drivers using Class.forName(). See
JDBC 4.0 Enhancements in Java SE 6
When a Driver class is loaded, it creates an instance of itself and registers it with the
DriverManager. This can be done by including the needed code in the driver class's static block.
e.g. DriverManager.registerDriver(Driver driver)
Now when a connection is needed, one of the DriverManager.getConnection() methods is used to
create a JDBC connection.
Connection conn = DriverManager.getConnection(
"jdbc:somejdbcvendor:other data needed by some jdbc vendor",
"myLogin",
"myPassword" );
The URL used is dependent upon the particular JDBC driver. It will always begin with the "jdbc:"
protocol, but the rest is up to the particular vendor. Once a connection is established, a statement
must be created.
Statement stmt = conn.createStatement();
try {
stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " );
} finally {
//It's important to close the statement when you are done with it
stmt.close();
}
Note that Connections, Statements, and ResultSets often tie up operating system resources such as
sockets or file descriptors. In the case of Connections to remote database servers, further resources
are tied up on the server, e.g., cursors for currently open ResultSets. It is vital to close() any JDBC
object as soon as it has played its part; garbage collection should not be relied upon. Forgetting to
close() things properly results in spurious errors and misbehaviour. The above try-finally
construct is a recommended code pattern to use with JDBC objects.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Data is retrieved from the database using a database query mechanism. The example below shows
creating a statement and executing a query.
Statement stmt = conn.createStatement();
try {
ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" );
try {
while ( rs.next() ) {

45

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

int numColumns = rs.getMetaData().getColumnCount();


for ( int i = 1 ; i <= numColumns ; i++ ) {
// Column numbers start at 1.
// Also there are many methods on the result set to return
// the column as a particular type. Refer to the Sun documentation
// for the list of valid conversions.
System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
Typically, however, it would be rare for a seasoned Java programmer to code in such a fashion.
The usual practice would be to abstract the database logic into an entirely different class and to
pass preprocessed strings (perhaps derived themselves from a further abstracted class) containing
SQL statements and the connection to the required methods. Abstracting the data model from the
application code makes it more likely that changes to the application and data model can be made
independently.
An example of a PreparedStatement query. Using conn and class from first example.
PreparedStatement ps = conn.prepareStatement( "SELECT i.*, j.* FROM Omega i, Zappa j
WHERE i.name = ? AND j.num = ?" );
try {
// In the SQL statement being prepared, each question mark is a placeholder
// that must be replaced with a value you provide through a "set" method invocation.
// The following two method calls replace the two placeholders; the first is
// replaced by a string value, and the second by an integer value.
ps.setString(1, "Poor Yorick");
ps.setInt(2, 8008);

// The ResultSet, rs, conveys the result of executing the SQL statement.
// Each time you call rs.next(), an internal row pointer, or cursor,
// is advanced to the next row of the result. The cursor initially is
// positioned before the first row.
ResultSet rs = ps.executeQuery();
try {
while ( rs.next() ) {
int numColumns = rs.getMetaData().getColumnCount();
for ( int i = 1 ; i <= numColumns ; i++ ) {
// Column numbers start at 1.
// Also there are many methods on the result set to return

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
// the column as a particular type. Refer to the Sun documentation
// for the list of valid conversions.
System.out.println( "COLUMN " + i + " = " + rs.getObject(i) );

46

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

} // for
} // while
} finally {
rs.close();
}
} finally {
ps.close();
} // try
When a database operation fails, an SQLException is raised. There is typically very little one can
do to recover from such an error, apart from logging it with as much detail as possible. It is
recommended that the SQLException be translated into an application domain exception (an
unchecked one) that eventually results in a transaction rollback and a notification to the user.
Here are examples of host database types which Java can convert to with a function.

setXXX() Methods

Oracle Datatype setXXX()

CHAR setString()

VARCHAR2 setString()

NUMBER setBigDecimal()

setBoolean()

setByte()

setShort()

setInt()

setLong()

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

setFloat()

setDouble()

47

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

INTEGER setInt()

FLOAT setDouble()

CLOB setClob()

BLOB setBlob()

RAW setBytes()

LONGRAW setBytes()

setDate()

DATE setTime()

setTimestamp()

For an example of a CallableStatement (to call stored procedures in the database), see the JDBC
API Guide.

JDBC Drivers
JDBC Drivers are client-side adaptors (they are installed on the client machine, not on the server)
that convert requests from Java programs to a protocol that the DBMS can understand.

Types
There are commercial and free drivers available for most relational database servers. These
drivers fall into one of the following types:
• Type 1, the JDBC-ODBC bridge
• Type 2, the Native-API driver
• Type 3, the network-protocol driver
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
• Type 4, the native-protocol drivers

48

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

Internal JDBC driver, driver embedded with JRE in Java-enabled SQL databases. Used for Java
stored procedures. This does not belong to the above classification, although it would likely be
either a type 2 or type 4 driver (depending on whether the database itself is implemented in Java
or not). An example of this is the KPRB driver supplied with Oracle RDBMS.
"jdbc:default:connection" is a relatively standard way of referring making such a connection (at
least Oracle and Apache Derby support it). The distinction here is that the JDBC client is actually
running as part of the database being accessed, so access can be made directly rather than through
network protocols.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

49
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE NO. 1

DEVELOPING STATIC PAGES OF AN ONLINE BOOKSTORE

Problem

Develop static pages of an online bookstore. The pages should resemble amazon.com. The
website should have the following pages information:
1. Home Page
2. Registration Page
3. Login Page
4. Books Catalogue Page
5. Shopping Cart Page
6. Payment by credit card page
7. Order Confirmation Page

1) HOME PAGE:

The static home page must contain three frames.

Top frame: Logo and the college name and links to Home page, Login page, Registration page,
Catalogue page and Cart page (the description of these pages will be given below).

Left frame: At least four links for navigation, which will display the catalogue of respective links.
For e.g.: When you click the link "CSE" the catalogue for CSE Books should be displayed in the
Right frame.

Right frame: The pages to the links in the left frame must be loaded here. Initially this page
contains description of the web site.

Logo Web Site Name


Home Login Registration Catalogue Cart

CSE
ECE
Description of the Web Site
EEE
CIVIL

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
50
Vijay PAGE:
2) LOGIN Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
This page looks like below:

Logo Web Site Name

Home Login Registration Catalogue Cart

CSE
ECE Login :
EEE Password:
CIVIL

Submi Reset

3) CATOLOGUE PAGE:

The catalogue page should contain the details of all the books available in the web site in a
table. The details should contain the following:

1. Snap shot of Cover Page.


2. Author Name.
3. Publisher.
4. Price.
5. Add to cart button.

Web Site Name


Logo
Home Login Registration Catalogue Cart

CSE Book : XML Bible


Author : Winston $ 40.5
ECE Publication : Wiely

EEE
Book : AI $ 63
CIVIL Author : S.Russel
Publication :
Princeton hall

Book : Java 2 $ 35.5


Author : Watson
Publication : BPB
publications

Book : HTML in 24 $ 50
hours
Author : Sam Peter
Publication : Sam
publication
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
51
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
4) CART PAGE:

The cart page contains the details about the books which are added to the cart.
The cart page should look like this:
Web Site Name
Logo
Home Login Registration Catalogue Cart

CSE Book name Price Quantity Amount


ECE
EEE Java 2 $35.5 2 $70
CIVIL XML bible $40.5 1 $40.5

Total amount - $130.5

5) REGISTRATION PAGE:

Create a "registration form "with the following fields

1) Name (Text field)


2) Password (password field)
3) E-mail id (text field)
4) Phone number (text field)
5) Sex (radio button)
6) Date of birth (3 select boxes)
7) Languages known (check boxes - English, Telugu, Hindi, Tamil)
8) Address (text area)

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
52
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE NO. 2

VALIDATING THE REGISTRATION,


USER PROFILE USING JAVA SCRIPT

OBJECTIVE:
To write JavaScript to validate the fields

PREREQUISITES:
Basic knowledge in HTML and Java Script

DESCRIPTION:
The JavaScript validate the fields in registration page

Program
<html>
<head>
<tittle>Display current date & time <tittle>
<Script language = "javascript">
function name()
{
Var res =document.forms[0].elements[0].value;
Var len = res.length;
If(len = = 0)
Window.alert(“username”);
}

</Script>
</head>
</html>

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
53
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

EXERCISE NO. 3

CREATING AN XML DOCUMENT FOR USERS INFORMATION

Write an XML file which will display the Book information which includes the following:
1) Title of the book
2) Author Name
3) ISBN number
4) Publisher name
5) Edition
6) Price
Write a Document Type Definition (DTD) to validate the above XML file.
Display the XML file as follows.
The contents should be displayed in a table. The header of the table should be in color GREY. And the
Author names column should be displayed in one color and should be capitalized and in bold. Use your
own colors for remaining columns.
Use XML schemas XSL and CSS for the above purpose.
Note: Give at least for 4 books. It should be valid syntactically.
Hint: You can use some xml editors like XML-spy

OBJECTIVE :
To display the book information using XML file.

PREREQUISITES:
Basic knowledge in XML,DTD,XSL,CSS

DESCRIPTION :
To display the book information like title of the book, Author name, ISBN number, publisher
name, edition and price in a tabular format by satisfying the given constraints.

Program
<?xml version =”1.0”?>
<xsl:stylesheet version = “1.0” xmlns: xsl/>
<xsl: for-each select = “title/name”/>
<xsl:value-of select = “name”/>
<xsl:value-of select = “title”/>
<xsl: for-each/>

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
54
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE NO. 4

CREATING A JAVA BEAN WHICH CONVERTS


RUPEES INTO AMERICAN DOLLARS

OBJECTIVE :
To converts Rupees into American Dollars

PREREQUISITES:
Knowledge in beans.

DESCRIPTION :
Converting amount given in dollar to rupees.

Program
Import java. awt.*;
Import java.awt.event.*;
Public class convert extends panel implements Actionlistener
{
Textfield t1,t2;
Button b;
}
Public void actionperformed (ActionEvent ae)
{
String s = ae.getActionCommand();
If (s.equals (“to rupees”);
{
String st = t1.getText();
Int a = (Integer.parseInt(st)*38);
T2.setText( “ “ +a);
}

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
55
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE NO. 5

CREATING A BEAN TO COUNT NUMBER OF CLICKS

OBJECTIVE :
To count the number of clicks.

PREREQUISITES:
Knowledge in beans.

DESCRIPTION :
counting the number of clicks

Program
Import java. awt.*;
Import java.awt.event.*;
Public class convert extends panel implements Actionlistener
{
Textfield t1,t2;
Button b;
Int = c = 0;
}
Public click ()
{
l = new Label (‘no of clicks’);
b = new Button (‘click’);
t = new Textfield (10);
}

Public void actionperformed (ActionEvent ae)


{
C++;
t.setText(“ “ +C);
}

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
56
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE NO. 6

CREATING A BEAN TO DESIGN A CALCULATOR

OBJECTIVE :
To design a calculator as reusable component.

PREREQUISITES:
Knowledge in beans.

DESCRIPTION :
Developing and designing a calculator.

Program
Import java. awt.*;
Import java.awt.event.*;
Public class calc extends panel implements Actionlistener
{
Double a,b =0, c =1, d;
Textfield res;
Button b;
Int = c = 0;
Button plus, minus, mul, div, eq;
}
Public calc ( )
{
Res = new Textfield (40);
Add (res);
Plus = (Button) add(plus);
int a = Integer.parseInt(res.getText ( );
}

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
57
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

EXERCISE NO. 7

CREATING A BEAN OF TRAFFIC LIGHT GIVING THE


STATE OF AN AUTO MOBILE

OBJECTIVE :
To create a state of Traffic Light.

PREREQUISITES:
Knowledge in beans.

DESCRIPTION :
Creating a bean of traffic light giving the state of an auto mobile.

Program
Import java. awt.*;
Import java.awt.event.*;
Public class signal extends panel implements Actionlistener
{
Double a,b =0, c =1, d;
Textfield res;
Button b;
Public signals ( )
{
t = new TextField (10);
b1 = new Button (“RED”);
b1.setBackground (Color.RED);
b2 = new Button (“YELLOW”);
b2.setBackground (Color.YELLOW);
b3 = new Button (“GREEN”);
b3.setBackground (Color.GREEN);
}

Public void actionperformed (ActionEvent ae)


{
String s = ae.get.Action Command ( );
if (s.equals (“RED”) )
t.set Text (“Stop”);
else
if (s.equals (“YELLOW”) )
t.set Text (“Ready”);
else
t.set Text (“Go”);
}

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
58
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE NO. 8

PROCEDURE FOR INSTALLATION OF TOMCAT SERVER


1) Install TOMCAT web server and APACHE.
While installation assign port number 4040 to TOMCAT and 8080 to APACHE. Make sure that these ports are available
i.e., no other process is using this port.
2) Access the above developed static web pages for books web site, using these servers by putting the web pages developed
in week-1 and week-2 in the document root.
Access the pages by using the urls : http://localhost:4040/rama/books.html (for tomcat)
http://localhost:8080/books.html (for Apache)

OBJECTIVE :
TOMCAT installation

PREREQUISITES:
TOMCAR webserver, APACHE softwares

DESCRIPTION :
Installation of TOMCAT and APACHE002E

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
61

59
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

60

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

61

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

62

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

63

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

64
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

EXERCISE 9

PROGRAM FOR SERVLET USING COOKIES

HTTP is a stateless protocol. Session is required to maintain the state.


The user may add some items to cart from the catalog page. He can check the cart page for the
selected items. He may visit the catalogue again and select some more items. Here our interest is the
selected items should be added to the old cart rather than a new cart. Multiple users can do the same thing
at a time(i.e., from different systems in the LAN using the ip-address instead of localhost). This can be
achieved through the use of Cookies. Every user will have his own Cookies which will be created after his
successful login to the website. When the user logs out his Cookies should get invalidated (by using the
method Cookies.invalidate() ).
.
OBJECTIVE :
To modify the catalog using Cookies.

PREREQUISITES:
Knowledge in Cookies management.

DESCRIPTION :
Modifying the catalog using Cookies.

Program:

File1.Java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http*;
import javax.servlet.http.cookie.*;

public class file1 extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException

{
String cu,cp;
Cookie c1 = new Cookie (“cu”,usr);
Cookie c2 = new Cookie (“cp”,pwd);
response.addCookie(c1);
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
response.addCookie(c2);
}

65

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

File2.Java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http*;
import javax.servlet.http.cookie.*;

public class file2 extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException

{
Cookie c [ ] = request.getCookies ( );
for(int i=0; i<c.length; i++)
{
out.printin(“User is” +c[i].getName( ));
out.printin(“Password is” +c[i].getValue( ));
}

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

66
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

EXERCISE 10

PROGRAM FOR SERVLET USING SESSIONS

HTTP is a stateless protocol. Session is required to maintain the state.


The user may add some items to cart from the catalog page. He can check the cart page for the
selected items. He may visit the catalogue again and select some more items. Here our interest is the selected
items should be added to the old cart rather than a new cart. Multiple users can do the same thing at a time(i.e.,
from different systems in the LAN using the ip-address instead of localhost). This can be achieved through the
use of sessions. Every user will have his own session which will be created after his successful login to the
website. When the user logs out his session should get invalidated (by using the method session.invalidate() ).

OBJECTIVE :
To modify the catalog using sessions.

PREREQUISITES:
Knowledge in session management.

DESCRIPTION :
Modifying the catalog using sessions.

PROGRAM:

File1.Java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http*;
import javax.servlet.http.session.*;

public class file1 extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException

{
String un, pw;
un = request.getParameter (“user”);
pw = request.getParameter (“pwd”);

HttpSession session = request.getSession (true);


session.setAttribute (“usr”. un);
session.setAttribute (“pwd”. pw);

}
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

67

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

File2.Java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http*;
import javax.servlet.http.session.*;

public class file2 extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException

{
String un1, pw1;
un1 = request.getParameter (“usr”);
pw1 = request.getParameter (“pwd”);

HttpSession session = request.getSession (false);


un1 = session.setAttribute (“usr”). to string ( );
pw1 = session.setAttribute (“pwd”). to string ( );

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

68
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

EXERCISE 11

PROGRAM FOR JSP USING COOKIES AND SESSSIONS

OBJECTIVE :
To validate the user information according to the given data.

PREREQUISITES:
Knowledge in Cookies, servlets and XML.

DESCRIPTION :
To validate the user information according to the given data and display the information
accordingly.

PROGRAM:

COOKIES:

< % @ page contentType = “text/html” % >

< % @ page Encoding = “UTF - 8” % >

<html>
<body>
<%
string n = request.getParameter (“name”);
Cookie c = new cookie (“name”, n);
response.addCookie (c);

if (a.equals (“name”))
{
out.println (“name is” + c[i].getValue ( ) );
}
%>
</body>
</html>

SESSIONS:

< % @ page contentType = “text/html” % >

< % @ page Encoding = “UTF - 8” % >

<html>
<body>
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
<%
string n = request.getParameter (“name”);

69

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

session.setAttribute (“name”, n);


object n1 = session.getAttribute (“name”);

%>
</body>
</html>

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

70
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

EXERCISE 12

IMPLEMETING THE “HELLO WORLD” USING JSP

OBJECTIVE :
To validate the user information according to the given data using JSP.

PREREQUISITES:
Knowledge in JSP.

DESCRIPTION :
Validating the information using any scriptlet tag.

PROGRAM:

< % @ page contentType = “text/html” % >

< % @ page Encoding = “UTF - 8” % >

<html>
<body>
<%
Out.println (“Hello World”);
%>
</html>
</body>

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

71
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.

BIBLIOGRAPHY

1. Web Programming, building internet applications, Chris Bates 2nd edition, WILEY
Dreamtech.

2. The complete Reference Java 2 Fifth Edition by Patrick Naughton and Herbert Schildt,
TMH.

3. Internet and World Wide Web - How to program by Dietel and Nieto PHI/Pearson
Education Asia.

4. Jakarta Struts Cookbook, Bill Siggelkow, S P D O'Reilly.

5. Murach's beginning JAVA JDK 5, Murach, SPD.

6. An Introduction to web Design and Programming -Wang-Thomson.

7. Web Applications Technologies Concepts-Knuckles,John Wiley.

8. Programming world wide web-Sebesta,Pearson.

9. Building Web Applications-NIIT, PHI.

10. Web Warrior Guide to Web Programmming-Bai/Ekedaw-Thomas.

11. Beginning Web Programming-Jon Duckett WROX.

12. Java Server Pages, Pekowsky, Pearson.

13. Java Server Pages -Hans Bergsten, SPD O'Reilly.

Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
72