Professional Documents
Culture Documents
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.
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:
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:
If you wanted to center a paragraph, you could write it with this attribute-value combination:
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:
The elements listed in the following could be called document elements because they describe
and define your HTML document.
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:
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.
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.
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.
Importing text into your HTML document is as easy as using the cut and paste options in
Windows.
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.
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:
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.
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>
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.
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:
<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.
The <big>big</big> element and the <small>small</small> element are useful tools.<br>
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.
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 />
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.
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:
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 />
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.
Use the <ins>inserted text</ins> element or the <u>underline</u> element for underlining text.
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:
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.
<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:
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:
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>
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:
<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.
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.
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.
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:
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.
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:
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:
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:
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:
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:
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:
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):
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:
Some browsers will display rules in color. You can choose a color by adding the color attribute:
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 to Add Spaces. The nonbreaking space entity ( ) 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
where you want the spaces inserted.
What do you do if you want to center your text or right-justify a block of text?
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.
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:
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.
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>
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.
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 />.
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:
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>
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:
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:
Try adding a line with a font tag containing the hex code for blue:
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:
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
Inline Styles
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
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 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:
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:
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:
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:
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:
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.
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:
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:
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;
If you divide two integers and the result is not a whole number, it will automatically become a
float:
var decimal = 5 / 4;
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:
Example:
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:
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:
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]);
It's possible to populate an array when it's declared. We simply insert values, separated with
commas, between the square brackets:
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:
A mixed array, containing multiple data types, would look like this:
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
28
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
CONDITIONS AND LOOPS: CONTROLLING PROGRAM FLOW
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);
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 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.
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.
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()
{
}
35
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
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.
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
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.
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):
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).
41
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
43
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
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.
// 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
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
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:
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.
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:
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:
EEE
Book : AI $ 63
CIVIL Author : S.Russel
Publication :
Princeton hall
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
5) REGISTRATION PAGE:
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
52
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE NO. 2
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
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
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
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);
}
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
56
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE NO. 6
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
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);
}
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
58
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE NO. 8
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
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.*;
{
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.*;
{
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
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.*;
{
String un, pw;
un = request.getParameter (“user”);
pw = request.getParameter (“pwd”);
}
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.*;
{
String un1, pw1;
un1 = request.getParameter (“usr”);
pw1 = request.getParameter (“pwd”);
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
68
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE 11
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:
<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:
<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.
%>
</body>
</html>
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
70
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
EXERCISE 12
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:
<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.
Vijay Varma,CSE,ASTRA,Bandlaguda,Hyderabad.
72