241254 Web Technology Lab Manual

244
LIST OF PROGRAMS 1. Creation of HTML pages with frames, links, tables and other tags. 2. Usage of internal and external CSS along with HTML pages. 3. Client Side Programming. a. Javascript for displaying date and comparing two dates. b. Form validation including textfield, radio buttons, checkboxes, listbox and other controls 4. Usage of ASP/JSP objects Request, Response, Application, Session, Server, ADO etc. (Writing online applications such as Shopping, railway/air/bus ticket reservation system with set of ASP/JSP pages.) 5. Writing Servlet Program using HTTP Servlet. 6. Any online application with database access. (Write an ASP application for Telephone Directory using MS-ACCESS) 7. Creation of XML document for a specific domain.

description

jkll

Transcript of 241254 Web Technology Lab Manual

Page 1: 241254 Web Technology Lab Manual

LIST OF PROGRAMS

1. Creation of HTML pages with frames, links, tables and other tags.

2. Usage of internal and external CSS along with HTML pages.

3. Client Side Programming.

a. Javascript for displaying date and comparing two dates.

b. Form validation including textfield, radio buttons, checkboxes,

listbox and other controls

4. Usage of ASP/JSP objects Request, Response, Application, Session, Server, ADO

etc. (Writing online applications such as Shopping, railway/air/bus ticket

reservation system with set of ASP/JSP pages.)

5. Writing Servlet Program using HTTP Servlet.

6. Any online application with database access.

(Write an ASP application for Telephone Directory using MS-ACCESS)

7. Creation of XML document for a specific domain.

8. Writing DTD or XML schema for the domain specific XML document.

9. Parsing an XML document using DOM and SAX Parsers.

10. Sample web application development in the open source environment.

Page 2: 241254 Web Technology Lab Manual

INTRODUCTION TO HTML

HTML, which stands for HyperText Markup Language, is the predominant markup language for web pages. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists etc as well as for links, quotes, and other items. It allows images and objects to be embedded and can be used to create interactive forms. It is written in the form of HTML elements consisting of "tags" surrounded by angle brackets within the web page content. It can include or can load scripts in languages such as JavaScript which affect the behavior of HTML processors like Web browsers; and Cascading Style Sheets (CSS) to define the appearance and layout of text and other material. The W3C, maintainer of both HTML and CSS standards, encourages the use of CSS over explicit presentational markup.

HTML <!--...--> tag

Example

An HTML comment:

<!--This is a comment. Comments are not displayed in the browser--><p>This is a paragraph.</p>

Definition and Usage

The comment tag is used to insert a comment in the source code. A comment will be ignored by the browser. Comments can be used to explain the code, which will help when the source code is edited at a later date.

Program-specific information can also be stored inside comments. In this case,they will not be visible for the user, but they are still available to the program. A good practice is to comment the text inside scripts and style elements to prevent older browsers, that do not support scripting or styles, from showing it as plain text.

HTML <!DOCTYPE> Declaration

Page 3: 241254 Web Technology Lab Manual

Example

An HTML document with a doctype of XHTML 1.0 Transitional:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><title>Title of the document</title></head>

<body>The content of the document......</body>

</html>

Definition and Usage

The doctype declaration should be the very first thing in an HTML document, before the <html> tag.

The doctype declaration is not an HTML tag; it is an instruction to the web browser about what version of the markup language the page is written in.

The doctype declaration refers to a Document Type Definition (DTD). The DTD specifies the rules for the markup language, so that the browsers can render the content correctly.

Doctypes Available in the W3C RecommendationsHTML 4.01 Strict

This DTD contains all HTML elements and attributes, but does not include presentational or deprecated elements (like font). Framesets are not allowed.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

HTML 4.01 Transitional

This DTD contains all HTML elements and attributes, including presentational and deprecated elements (like font). Framesets are not allowed.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

Page 4: 241254 Web Technology Lab Manual

HTML 4.01 Frameset

This DTD is equal to HTML 4.01 Transitional, but allows the use of frameset content.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">

XHTML 1.0 Strict

This DTD contains all HTML elements and attributes, but does not include presentational or deprecated elements (like font). Framesets are not allowed. The markup must also be written as well-formed XML.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

XHTML 1.0 Transitional

This DTD contains all HTML elements and attributes, including presentational and deprecated elements (like font). Framesets are not allowed. The markup must also be written as well-formed XML.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

XHTML 1.0 Frameset

This DTD is equal to XHTML 1.0 Transitional, but allows the use of frameset content.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

XHTML 1.1

This DTD is equal to XHTML 1.0 Strict, but allows you to add modules (for example to provide ruby support for East-Asian languages).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

HTML <a> tag

Page 5: 241254 Web Technology Lab Manual

Example

A link to W3Schools.com:

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

Definition and Usage

The <a> tag defines an anchor. An anchor can be used in two ways:

1. To create a link to another document, by using the href attribute 2. To create a bookmark inside a document, by using the name attribute

The a element is usually referred to as a link or a hyperlink.

The most important attribute of the a element is the href attribute, which indicates the link’s destination.

By default, links will appear as follows in all browsers:

An unvisited link is underlined and blue A visited link is underlined and purple An active link is underlined and red

Browser Support

The <a> tag is supported in all major browsers.

Differences Between HTML and XHTML

NONE

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

charset char_encoding Specifies the character encoding of the target URL

STF

coordscoordinates

Used with the shape attribute to specify the size, shape, and placement of a link in an object or img element

STF

href URL Specifies the target URL of the link STF

hreflang language_code Specifies the language of the document in the STF

Page 6: 241254 Web Technology Lab Manual

target URL

name section_name Defines an anchor (use this attribute to create a bookmark in a document)

STF

rel alternatestylesheetstartnextprevcontentsindexglossarycopyrightchaptersectionsubsectionappendixhelpbookmark

Specifies the relationship between the current document and the target URL

STF

rev alternatestylesheetstartnextprevcontentsindexglossarycopyrightchaptersectionsubsectionappendixhelpbookmark

Specifies the relationship between the target URL and the current document

STF

shape rectrectanglecirccirclepolypolygon

Defines the shape of a link STF

target _blank_parent_self_topframename

Specifies where to open the target URLTF

type mime_type Specifies the MIME type of the target URL STF

Page 7: 241254 Web Technology Lab Manual

HTML <abbr> tag

Example

An abbreviation is marked up as follows:

The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.

Definition and Usage

The <abbr> tag describes an abbreviated phrase.

By marking up abbreviations, useful information can be given to browsers, spellcheckers, screen readers, translation systems and search-engines.

Browser Support

The <abbr> tag is supported in all major browsers.

Note: The <abbr> tag is not supported in IE 6 or earlier versions.

Differences Between HTML and XHTML

NONE

Tips and Notes

Tip: The title attribute is used to show the full version of the expression when the mouse is moved over the abbreviation.

HTML <acronym> tag

Example

An acronym is marked up as follows:

Can I get this <acronym title="as soon as possible">ASAP</acronym>?

Page 8: 241254 Web Technology Lab Manual

Definition and Usage

The <acronym> tag defines an acronym.

An acronym can be spoken as if it were a word, example NATO, NASA, ASAP, GUI.

By marking up acronyms,useful information can be given to browsers, spellcheckers, screen readers, translation systems and search-engines.

Browser Support

The <acronym> tag is supported in all major browsers.

Note: The <acronym> tag is not supported in IE 5.5 or earlier versions.

Differences Between HTML and XHTML

NONE

HTML <address> tag

Example

Contact information for W3Schools.com:

<address>Written by W3Schools.com<br /><a href="mailto:[email protected]">Email us</a><br />Address: Box 564, Disneyland<br />Phone: +12 34 56 78</address>

Definition and Usage

The <address> tag is used to mark up contact information for the author or owner of the document. This way, the reader is able to contact the document's owner.

The address element is usually added to the header or footer of a webpage.

Browser Support

The <address> tag is supported in all major browsers.

Page 9: 241254 Web Technology Lab Manual

Differences Between HTML and XHTML

NONE

Most browsers will also add a line break before and after the address element.

HTML <area> tag

Example

An image map, with clickable areas:

<img src ="planets.gif" width="145" height="126" alt="Planets" usemap ="#planetmap" />

<map id ="planetmap" name="planetmap">  <area shape ="rect" coords ="0,0,82,126" href ="sun.htm" alt="Sun" />  <area shape ="circle" coords ="90,58,3" href ="mercur.htm" alt="Mercury" />  <area shape ="circle" coords ="124,58,8" href ="venus.htm" alt="Venus" /></map>

Definition and Usage

The <area> tag defines a region in an image map.

The area element is always nested inside a <map> tag.

Browser Support

The <area> tag is supported in all major browsers.

Differences Between HTML and XHTML

In HTML the <area> tag has no end tag.

In XHTML the <area> tag must be properly closed.

Note: The usemap attribute in the <img> tag refers to the id or name (browser dependant) attribute in <map>, therefore we have added both the id and name attributes to <map>.

Page 10: 241254 Web Technology Lab Manual

Required Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

alt text Specifies an alternate text for the area

STF

Optional AttributesAttribute Value Description DTD

coords if shape="rect" thencoords="left,top,right,bottom"

if shape="circ" thencoords="centerx,centery,radius"

if shape="poly" thencoords="x1,y1,x2,y2,..,xn,yn"

Specifies the coordinates for the clickable area

STF

href URL Specifies the target URL of the area

STF

nohref truefalse

Excludes an area from the image map

STF

shape rectrectanglecirccirclepolypolygon

Defines the shape of the area STF

target _blank_parent_self_top

Where to open the target URL.

_blank - the target URL will open in a new window

_self - the target URL will open in the same frame as it was clicked

_parent - the target URL will open in the parent frameset

_top - the target URL will open in the full body of the window

HTML <tt> <i> <b> <big> <small> tags

Page 11: 241254 Web Technology Lab Manual

Example

Format text in a document:

<tt>Teletype text</tt><i>Italic text</i><b>Bold text</b><big>Big text</big><small>Small text</small>

Definition and Usage

The <tt>, <i>, <b>, <big>, and <small> tags are all font-style tags. They are not deprecated, but it is possible to achieve richer effect with CSS.

<tt> Renders as teletype or mono-spaced text

<i> Renders as italic text

<b> Renders as bold text

<big> Renders as bigger text

<small> Renders as smaller text

Browser Support

The <tt>, <i>, <b>, <big>, and <small> tags are supported in all major browsers.

Differences Between HTML and XHTML

NONE

Standard Attributesid, class, title, style, dir, lang

HTML <base> tag

Page 12: 241254 Web Technology Lab Manual

Example

Specify a default URL and a default target for all links on a page:

<head><base href="http://www.w3schools.com/images/" /><base target="_blank" /></head>

<body><img src="stickman.gif" /><a href="http://www.w3schools.com">W3Schools</a></body>

Try it yourself!

Definition and Usage

The <base> tag specifies a default address for links or a default target for linked documents.

The <base> tag goes inside the head element.

Browser Support

The <base> tag is supported in all major browsers.

Differences Between HTML and XHTML

In HTML the <base> tag has no end tag.

In XHTML the <base> tag must be properly closed.

Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

href URL Specifies the URL to use as the base URL for links in the page STF

target _blank_parent_self_topframename

Where to open all the links on the page. This attribute can be overridden by using the target attribute in each link.

_blank - all the links will open in new windows _self - all the links will open in the same frame they

where clicked _parent - all the links will open in the parent frameset _top - all the links will open in the full body of the

window

framename - the name of the target frame

TF

Page 13: 241254 Web Technology Lab Manual

Standard Attributes and Events

NONE

HTML <bdo> tag

Example

Specify the text direction:

<bdo dir="rtl">Here is some Hebrew text!</bdo>

Try it yourself!

Definition and Usage

bdo stand for bidirectional override.

The <bdo> tag allows you to specify the text direction and override the bidirectional algorithm.

Browser Support

The <bdo> tag is supported in all major browsers.

Note: This tag is not supported in Safari version 2 and earlier.

Differences Between HTML and XHTML

NONE

Required Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

dir ltrrtl

Defines the text direction STF

Standard Attributesid, class, title, style, dir, lang, xml:lang

Page 14: 241254 Web Technology Lab Manual

HTML <blockquote> tag

Example

A long quotation is marked up as follows:

<blockquote>Here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation.</blockquote>

Try it yourself!

Definition and Usage

The <blockquote> tag defines a long quotation.

A browser inserts white space before and after a blockquote element. It also insert margins for the blockquote element.

Browser Support

The <blockquote> tag is supported in all major browsers.

Note: None of the major browsers display the cite attribute correctly.

Differences Between HTML and XHTML

To validate a blockquote element as strict HTML, the element must contain only other block-level elements, like this:

<blockquote><p>Here is a long quotation here is a long quotation</p></blockquote>

Tips and Notes

Tip: Use the q element to mark up short quotations!

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

cite URL URL of the quote, if it is taken from the web STF

Standard Attributesid, class, title, style, dir, lang, xml:lang

HTML <body> tag

Page 15: 241254 Web Technology Lab Manual

Example

A simple HTML document, with the minimum of required tags:

<html><head><title>Title of the document</title></head>

<body>The content of the document......</body>

</html>

Try it yourself!

Definition and Usage

The body element defines the document's body.

The body element contains all the contents of an HTML document, such as text, hyperlinks, images, tables, lists, etc.

Browser Support

The <body> tag is supported in all major browsers.

Differences Between HTML and XHTML

All "presentation attributes" of the body element were deprecated in HTML 4.01, and are not supported in XHTML 1.0 Strict DTD.

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

alink rgb(x,x,x)#xxxxxxcolorname

Deprecated. Use styles instead.Specifies the color of the active links in the document.

TF

background file_name Deprecated. Use styles instead.An image to use as the background.

TF

bgcolor rgb(x,x,x)#xxxxxxcolorname

Deprecated. Use styles instead.The background color of the document.

TF

link rgb(x,x,x)#xxxxxxcolorname

Deprecated. Use styles instead.Specifies the color of all the links in the document.

TF

text rgb(x,x,x)#xxxxxxcolorname

Deprecated. Use styles instead.Specifies the color of the text in the document.

TF

vlink rgb(x,x,x)#xxxxxxcolorname

Deprecated. Use styles instead.Specifies the color of the visited links in the document.

TF

Page 16: 241254 Web Technology Lab Manual

Standard Attributesid, class, title, style, dir, lang, xml:lang

For a full description, go to Standard Attributes.

Event Attributesonload, onunload, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

HTML <br> tag

Example

A line break is marked up as follows:

This text contains<br />a line break.

Try it yourself!

Definition and Usage

The <br> tag inserts a single line break. 

The <br> tag is an empty tag which means that it has no end tag.

Browser Support

The <br> tag is supported in all major browsers.

Differences Between HTML and XHTML

In HTML the <br> tag has no end tag.

In XHTML the <br> tag must be properly closed, like this: <br />.

Tips and Notes

Note: Use the <br> tag to insert line breaks, not to create paragraphs.

Standard Attributesid, class, title, style

HTML <button> tag

Page 17: 241254 Web Technology Lab Manual

Example

A button is marked up as follows:

<button type="button">Click Me!</button>

Try it yourself!

Definition and Usage

The <button> tag defines a push button.

Inside a button element you can put content, like text or images. This is the difference between this element and buttons created with the input element.

Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and the W3C specification) it is "submit".

Browser Support

The <button> tag is supported in all major browsers.

Important: If you use the button element in an HTML form, different browsers will submit different values. Internet Explorer will submit the text between the <button> and </button> tags, while other browsers will submit the content of the value attribute. Use the input element to create buttons in an HTML form.

Differences Between HTML and XHTML

NONE

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

disabled disabled Disables the button STF

name button_name Specifies a name for the button STF

type buttonresetsubmit 

Defines the type of button STF

value some_value Specifies an initial value for the button. The value can be changed by a script

STF

Standard Attributesid, class, title, style, dir, lang, xml:lang, accesskey, tabindex

Event Attributesonfocus, onblur, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove,

Page 18: 241254 Web Technology Lab Manual

onmouseout, onkeypress, onkeydown, onkeyup

HTML <caption> tag

Example

A table with a caption:

<table border="1">  <caption>Monthly savings</caption>  <tr>    <th>Month</th>    <th>Savings</th>  </tr>  <tr>    <td>January</td>    <td>$100</td>  </tr></table>

Try it yourself!

Definition and Usage

The <caption> tag defines a table caption.

The <caption> tag must be inserted immediately after the <table> tag. You can specify only one caption per table. Usually the caption will be centered above the table.

Browser Support

The <caption> tag is supported in all major browsers.

Differences Between HTML and XHTML

The "align" attribute of the caption element was deprecated in HTML 4.01, and is not supported in XHTML 1.0 Strict DTD.

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

align leftrighttopbottom

Deprecated. Use styles instead.How to align the caption.

TF

Standard Attributesid, class, title, style, dir, lang, xml:lang

Page 19: 241254 Web Technology Lab Manual

For a full description, go to Standard Attributes.

Event Attributesonclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

HTML <em> <strong> <dfn> <code> <samp> <kbd> <var> <cite> tags

Example

Format text in a document:

<em>Emphasized text</em><strong>Strong text</strong><dfn>Definition term</dfn><code>Computer code text</code><samp>Sample computer code text</samp><kbd>Keyboard text</kbd><var>Variable</var><cite>Citation</cite>

Try it yourself!

Definition and Usage

The <em>, <strong>, <dfn>, <code>, <samp>, <kbd>, <var>, and <cite> tags are all phrase tags. They are not deprecated, but it is possible to achieve richer effect with CSS.

<em> Renders as emphasized text

<strong> Renders as strong emphasized text

<dfn> Defines a definition term

<code> Defines computer code text

<samp> Defines sample computer code

<kbd> Defines keyboard text

<var> Defines a variable

<cite> Defines a citation

Browser Support

The <em>, <strong>, <dfn>, <code>, <samp>, <kbd>, <var>, and <cite> tags are supported in all major browsers.

Differences Between HTML and XHTML

NONE

Standard Attributesid, class, title, style, dir, lang, xml:lang

For a full description, go to Standard Attributes.

Page 20: 241254 Web Technology Lab Manual

Event Attributesonclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

HTML <em> <strong> <dfn> <code> <samp> <kbd> <var> <cite> tags

Example

Format text in a document:

<em>Emphasized text</em><strong>Strong text</strong><dfn>Definition term</dfn><code>Computer code text</code><samp>Sample computer code text</samp><kbd>Keyboard text</kbd><var>Variable</var><cite>Citation</cite>

Try it yourself!

Definition and Usage

The <em>, <strong>, <dfn>, <code>, <samp>, <kbd>, <var>, and <cite> tags are all phrase tags. They are not deprecated, but it is possible to achieve richer effect with CSS.

<em> Renders as emphasized text

<strong> Renders as strong emphasized text

<dfn> Defines a definition term

<code> Defines computer code text

<samp> Defines sample computer code

<kbd> Defines keyboard text

<var> Defines a variable

<cite> Defines a citation

Browser Support

The <em>, <strong>, <dfn>, <code>, <samp>, <kbd>, <var>, and <cite> tags are supported in all major browsers.

Differences Between HTML and XHTML

NONE

Standard Attributesid, class, title, style, dir, lang, xml:lang

For a full description, go to Standard Attributes.

Page 21: 241254 Web Technology Lab Manual

Event Attributesonclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

For a full description, go to Event Attributes.

HTML <col> tag

Example

col elements that specify different alignment for the three columns in the table:

<table width="100%" border="1">  <col align="left"></col>  <col align="left"></col>  <col align="right"></col>  <tr>    <th>ISBN</th>    <th>Title</th>    <th>Price</th>  </tr>  <tr>    <td>3476896</td>    <td>My first HTML</td>    <td>$53</td>  </tr></table>

Try it yourself!

Definition and Usage

The <col> tag defines attribute values for one or more columns in a table.

The <col> tag is useful for applying styles to entire columns, instead of repeating the styles for each cell, for each row.

The <col> tag can only be used inside a table or a colgroup element.

Browser Support

The <col> tag is supported in all major browsers.

Differences Between HTML and XHTML

In HTML the <col> tag has no end tag.

In XHTML the <col> tag must be properly closed.

Tips and Notes

Tips: Add the class attribute to the <col> tag, and let CSS take care of alignment, widths, colors, etc.!

Also have a look at the <colgroup> tag.

Page 22: 241254 Web Technology Lab Manual

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

align rightleftcenterjustifychar

Defines the horizontal alignment of the content in the table cell, in the column

STF

char character Defines a character to use to align text on (use with align="char")

STF

charoff character-offset Defines an alignment offset to the first character to align on, as set with char

STF

span number Defines the number of columns the <col> should span STF

valign topmiddlebottombaseline

Defines the vertical alignment of the content in the table cell, in the column

STF

width %pixelsrelative_length

Defines the width of the column. Note: Overrides the width set in <colgroup>

STF

Standard Attributesid, class, title, style, dir, lang, xml:lang

For a full description, go to Standard Attributes.

Event Attributesonclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

For a full description, go to Event Attributes.

HTML <colgroup> tag

Page 23: 241254 Web Technology Lab Manual

Example

Two colgroup elements that specify different alignment and style for the three columns in the table (notice that the first colgroup element spans two columns):

<table width="100%" border="1">  <colgroup span="2" align="left"></colgroup>  <colgroup align="right" style="color:#0000FF;"></colgroup>  <tr>    <th>ISBN</th>    <th>Title</th>    <th>Price</th>  </tr>  <tr>    <td>3476896</td>    <td>My first HTML</td>    <td>$53</td>  </tr></table>

Try it yourself!

Definition and Usage

The <colgroup> tag is used to group columns in a table for formatting.

The <colgroup> tag is useful for applying styles to entire columns, instead of repeating the styles for each cell, for each row.

The <colgroup> tag can only be used inside a table element.

Browser Support

The <colgroup> tag is supported in all major browsers.

Differences Between HTML and XHTML

NONE

Tips and Notes

Tips: Add the class attribute to the <colgroup> tag, and let CSS take care of alignment, widths, colors, etc.!

Also have a look at the <col> tag.

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

Page 24: 241254 Web Technology Lab Manual

align rightleftcenterjustifychar

Defines the horizontal alignment of the contents in the column group

STF

char character Defines a character to use to align text on (use with align="char")

STF

charoff character-offset Defines an alignment offset to the first character to align on, as set with char

STF

span number Defines the number of columns the <colgroup> should span

STF

valign topmiddlebottombaseline

Defines the vertical alignment of the contents in the column group

STF

width %pixelsrelative_length

Defines the width of the column group.

Note: The width attribute can be overridden by settings in <col>!

STF

Standard Attributesid, class, title, style, dir, lang, xml:lang

For a full description, go to Standard Attributes.

Event Attributesonclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

HTML <dd> tag

Example

Description of items in a definition list:

<dl>  <dt>Coffee</dt>    <dd>- black hot drink</dd>  <dt>Milk</dt>    <dd>- white cold drink</dd></dl>

Try it yourself!

Definition and Usage

The <dd> tag is used to describe an item in a definition list.

The <dd> tag is used in conjunction with <dl> (defines the definition list) and <dt> (defines the item in the list).

Browser Support

The <dd> tag is supported in all major browsers.

Page 25: 241254 Web Technology Lab Manual

Differences Between HTML and XHTML

NONE

Standard Attributesid, class, title, style, dir, lang, xml:lang

For a full description, go to Standard Attributes.

HTML <del> tag

Example

A text with a deleted part and a new inserted part:

<p>My favorite color is <del>blue</del> <ins>red</ins>!</p>

Try it yourself!

Definition and Usage

The <del> tag defines text that has been deleted from a document.

Browser Support

The <del> tag is supported in all major browsers.

Note: None of the major browsers display the cite or datetime attribute correctly.

Differences Between HTML and XHTML

NONE

Tips and Notes

Tip: Use it together with the <ins> tag to describe updates and modifications in a document.

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

cite URL Defines a URL to another document which explains why the text was deleted or inserted

STF

datetime YYYY-MM-DD Defines the date and time the text was deleted STF

Page 26: 241254 Web Technology Lab Manual

Standard Attributesid, class, title, style, dir, lang, xml:lang

HTML <div> tag

Example

A section in a document that will be displayed in green:

<div style="color:#00FF00">  <h3>This is a header</h3>  <p>This is a paragraph.</p></div>

Try it yourself!

Definition and Usage

The <div> tag defines a division or a section in an HTML document.

The <div> tag is often used to group block-elements to format them with styles.

Browser Support

The <div> tag is supported in all major browsers.

Differences Between HTML and XHTML

The "align" attribute of the div element was deprecated in HTML 4.01, and is not supported in XHTML 1.0 Strict DTD.

Tips and Notes

Tip: The div element is very often used with CSS to layout a web page.

Note: Browsers usually place a line break before and after the div element. 

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

align leftrightcenterjustify

Deprecated. Use styles instead.How to align the text in the div element.

TF

Standard Attributesid, class, title, style, dir, lang, xml:lang

Page 27: 241254 Web Technology Lab Manual

Event Attributesonclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

HTML <em> <strong> <dfn> <code> <samp> <kbd> <var> <cite> tags

Example

Format text in a document:

<em>Emphasized text</em><strong>Strong text</strong><dfn>Definition term</dfn><code>Computer code text</code><samp>Sample computer code text</samp><kbd>Keyboard text</kbd><var>Variable</var><cite>Citation</cite>

Try it yourself!

Definition and Usage

The <em>, <strong>, <dfn>, <code>, <samp>, <kbd>, <var>, and <cite> tags are all phrase tags. They are not deprecated, but it is possible to achieve richer effect with CSS.

<em> Renders as emphasized text

<strong> Renders as strong emphasized text

<dfn> Defines a definition term

<code> Defines computer code text

<samp> Defines sample computer code

<kbd> Defines keyboard text

<var> Defines a variable

<cite> Defines a citation

Browser Support

The <em>, <strong>, <dfn>, <code>, <samp>, <kbd>, <var>, and <cite> tags are supported in all major browsers.

Differences Between HTML and XHTML

NONE

HTML <dl> tag

Page 28: 241254 Web Technology Lab Manual

Example

A definition list:

<dl>  <dt>Coffee</dt>    <dd>- black hot drink</dd>  <dt>Milk</dt>    <dd>- white cold drink</dd></dl>

Try it yourself!

Definition and Usage

The <dl> tag defines a definition list.

The <dl> tag is used in conjunction with <dt> (defines the item in the list) and <dd> (describes the item in the list).

Browser Support

The <dl> tag is supported in all major browsers.

Differences Between HTML and XHTML

NONE

Standard Attributesid, class, title, style, dir, lang, xml:lang

HTML <dt> tag

Example

A definition list:

<dl>  <dt>Coffee</dt>    <dd>- black hot drink</dd>  <dt>Milk</dt>    <dd>- white cold drink</dd></dl>

Try it yourself!

Page 29: 241254 Web Technology Lab Manual

Definition and Usage

The <dt> tag defines an item in a definition list.

The <dt> tag is used in conjunction with <dl> (defines the definition list) and <dd> (describes the item in the list).

Browser Support

The tag is supported in all major browsers.

Differences Between HTML and XHTML

NONE

Standard Attributesid, class, title, style, dir, lang, xml:lang

HTML <fieldset> tag

Example

Group related elements in a form:

<form>  <fieldset>    <legend>Personalia:</legend>    Name: <input type="text" size="30" /><br />    Email: <input type="text" size="30" /><br />    Date of birth: <input type="text" size="10" />  </fieldset></form>

Try it yourself!

Definition and Usage

The <fieldset> tag is used to logically group together elements in a form.

The <fieldset> tag draws a box around the related form elements.

The <legend> tag defines a caption for the fieldset element.

Browser Support

The <fieldset> tag is supported in all major browsers.

Page 30: 241254 Web Technology Lab Manual

Differences Between HTML and XHTML

NONE

Standard Attributesid, class, title, style, dir, lang, xml:lang

For a full description, go to Standard Attributes.

Event Attributesaccesskey, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

HTML <form> tag

Example

A simple HTML form with two input fields and one submit button:

<form action="form_action.asp" method="get">  First name: <input type="text" name="fname" /><br />  Last name: <input type="text" name="lname" /><br />  <input type="submit" value="Submit" /></form>

Try it yourself!  (more examples at the bottom of this page)

Definition and Usage

The <form> tag is used to create an HTML form for user input.

A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A forms can also contain select menus, textarea, fieldset, legend, and label elements.

Forms are used to pass data to a server.

Browser Support

The <form> tag is supported in all major browsers.

Differences Between HTML and XHTML

NONE

Tips and Notes

Note: Form is a block-level element, and creates a line break before and after itself.

Page 31: 241254 Web Technology Lab Manual

Required Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

action URL A URL that defines where to send the data when the submit button is pushed

STF

Optional AttributesAttribute Value Description DTD

accept list of content types A comma separated list of content types that the server that processes this form will handle correctly

STF

accept-charset charset_list A comma separated list of possible character sets for the form data. The default value is "unknown"

STF

enctype mimetype The mime type used to encode the content of the form STF

method getpost

The HTTP method for sending data to the action URL. Default is get.

method="get": This method sends the form contents in the URL: URL?name=value&name=value. Note: If the form values contains non-ASCII characters or exceeds 100 characters you MUST use method="post".

method="post": This method sends the form contents in the body of the request. Note: Most browsers are unable to bookmark post requests.

STF

name form_name Defines a unique name for the form TF

target _blank_self_parent_top

Where to open the target URL.

_blank - the target URL will open in a new window

_self - the target URL will open in the same frame as it was clicked

_parent - the target URL will open in the parent frameset

_top - the target URL will open in the full body of the window

TF

Standard Attributesid, class, title, style, dir, lang, xml:lang

For a full description, go to Standard Attributes.

Event Attributesonsubmit, onreset, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

HTML <frame> tag

Page 32: 241254 Web Technology Lab Manual

Example

A simple three-framed page:

<html>

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

</html>

Try it yourself!  (more examples at the bottom of this page)

Definition and Usage

The <frame> tag defines one particular window (frame) within a frameset.

Each frame in a frameset can have different attributes, such as border, scrolling, the ability to resize, etc.

Browser Support

The <frame> tag is supported in all major browsers.

Differences Between HTML and XHTML

In HTML the <frame> tag has no end tag.

In XHTML the <frame> tag must be properly closed.

Tips and Notes

Note: If you want to validate a page containing frames, be sure the doctype is set to "Frameset DTD". Read more about doctypes.

Important: You cannot use the body element together with the frameset element. However, if you add a <noframes> tag containing some text for browsers that do not support frames, you will have to enclose the text in a body element.

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

frameborder 01

Specifies whether or not to display border around the frame

F

longdesc URL A URL to a long description of the frame contents. Use it for browsers that do not support frames

F

marginheight pixels Defines the top and bottom margins in the frame F

Page 33: 241254 Web Technology Lab Manual

marginwidth pixels Defines the left and right margins in the frame F

name frame_name Defines a unique name for the frame (to use in scripts) F

noresize noresize When set to noresize the user cannot resize the frame F

scrolling yesnoauto

Determines scrollbar action F

src URL Defines the URL of the file to show in the frame F

Standard Attributes

Only allowed in XHTML 1.0 Frameset DTD!!

id, class, title, style

HTML <frameset> tag

Example

A simple three-framed page:

<html>

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

</html>

Try it yourself!  (more examples at the bottom of this page)

Definition and Usage

The <frameset> tag defines a frameset.

The frameset element holds two or more frame elements. Each frame element holds a separate document.

The frameset element states only how many columns or rows there will be in the frameset.

Browser Support

The <frameset> tag is supported in all major browsers.

Differences Between HTML and XHTML

NONE

Page 34: 241254 Web Technology Lab Manual

Tips and Notes

Note: If you want to validate a page containing frames, be sure the doctype is set to "Frameset DTD". Read more about doctypes.

Important: You cannot use the body element together with the frameset element. However, if you add a <noframes> tag containing some text for browsers that do not support frames, you will have to enclose the text in a body element.

Optional Attributes

DTD indicates in which DTD the attribute is allowed. S=Strict, T=Transitional, and F=Frameset.

Attribute Value Description DTD

cols pixels%*

Defines the number and size of columns in a frameset F

rows pixels%*

Defines the number and size of rows in a frameset F

Standard Attributes

Only allowed in XHTML 1.0 Frameset DTD!!

id, class, title, style

Page 35: 241254 Web Technology Lab Manual

Ex.No:

Date :

CREATION OF STUDENT PROFILES USING HTML TAGS

AIM: To develop a webpage to enter the student profiles.

ALGORITHM:

Step1: start the program

Step 2: using html tags, create table to enter the student profile

Step3: For each row of the table, enter the data using <td> such that create student

name,fathers name,address and e-mail,etc..

Step 4:Using <table> we have to enter the qualification of the students.

Step 5:Using radio button,we have to choose the entertainment and software

exposure of the student.

Step 6:Using <form>, we have to create a declare text to type the text.

Step 7:Execute the web page in Internet explorer

Page 36: 241254 Web Technology Lab Manual

PROGRAM :

<html><head><title>Resume page</title></head><body bgcolor="#fffFF"><center><font color="#6600CC"><h1><b><b><u>PROFILE</u></b></b></h1></center></font><form name="input" action ="z:\WebTech Lab\webpageprofile.htm" method="get"><img height=100 width=100 src="z:\WebTech Lab\Photo.jpg" alt="angry face"><table border="3">

<td>Name:</td><td><input type="text" height='10' width='25'></td></tr>

<tr><td>Father Name:</td><td><input type="text" height='10' width='25'></td> </tr>

<tr><td>Mother Name:</td><td><input type="text" height='10' width='25'></td></tr><tr><td>Date Of Birth:</td><td><input type="text" height='10' width='25'></td></tr><tr><td>Marital Status:</td><td><input type="text" height='10' width='25'></td></tr><tr><td>Communication:</td><td colspan="4"><textarea name="male" rows="4" cols='17'></textarea></td></tr><tr><td>Gender:</td><td>Male:<input type="checkbox" name="male">Female:<input type="checkbox" name="female"></td></tr><tr><th colspan="6">Educational Qualifications</th></tr><tr><th>Name of the Deg.</th><th>name of the degree</th><th>Name of the Instistution</th><th>Year of Pass</th><th>Grade</th><th>Specialization</th></tr><tr><td>SSLC:</td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td></tr>

Page 37: 241254 Web Technology Lab Manual

<tr><td>HSC:</td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td></tr><tr><td>D.C.Tech:</td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td></tr><tr><td>M.C.A:</td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td></tr><tr><td>M.E:</td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td><td><input type="text" height='10' width='25'></td></tr><br><br><br><tr><th colspan="6">Software Exposure</th></tr><tr><td>OS:</td><<td colspan="5">Windows XP/00/03<input type="checkbox" name="male">LINUX<input type="checkbox" name="female">UNIX<input type="checkbox" name="female">others<input type="checkbox" name="female"></td></tr><tr><td>Languages:</td><td colspan="5">C:<input type="checkbox" name="male">C++:<input type="checkbox" name="female">Java:<input type="checkbox" name="female">J2EE:<input type="checkbox" name="female"></td></tr><tr><td>Extra Curriculam Acvtivities:</td>

Page 38: 241254 Web Technology Lab Manual

<td colspan="5">Dance:<input type="checkbox" name="male">Swimming:<input type="checkbox" name="female">Shuttle:<input type="checkbox" name="female">Music:<input type="checkbox" name="female"></td></tr><tr><td>Any Other Information:</td><td><input type="text" name="male"></td></tr><tr><center><th>Declaration:</th></center><td colspan="5"><textarea name="male" rows="5" cols='70'></textarea></td></tr><tr><td>Date:</td><td><input type="text" name="male"></td><td>Place:</td><td><input type="text" name="male" ></td></tr><tr><td><input type="Submit" value="submit"> <A href="webpageprofile.htm"></A><br CLEAR=both></td><td><input type="reset" value="reset"></td></tr></center></body></html>

Page 39: 241254 Web Technology Lab Manual

SAMPLE OUTPUT :

RESULT:

Thus the web page for student profile has been created.

Page 40: 241254 Web Technology Lab Manual

INTRODUCTION TO CASCADING STYLE SHEETS (CSS)

CSS is the W3C standard for defining the visual presentation for web pages. HTML was designed as a structural markup language, but the demands of users and designers encouraged browser manufacturers to support and develop presentation-oriented tags. These tags “polluted” HTML, pushing the language toward one of decorative style rather than logical structure. Its increasing complexity made life hard for web designers, and source code began to balloon for even basic presentation-oriented tasks. Along with creating needlessly large HTML files, things like font tags created web pages that weren’t consistent across browsers and platforms, and styles had to be applied to individual elements—a time-consuming process.

The concept behind CSS was simple, yet revolutionary: remove the presentation and separate design from content. Let HTML (and later XHTML) deal with structure, and use a separate CSS document for the application of visual presentation.

The idea caught on, albeit slowly. The initial problem was browser support. At first, most browsers supported only a small amount of the CSS standard—and badly at that. But Internet Explorer 5 for Mac made great strides with regard to CSS support, and it was soon joined by other browsers fighting for the crown of standards king. These days, every up-to-date browser supports the majority of commonly used CSS properties and values, and more besides.

Another problem has been educating designers and encouraging them to switch from old to new methods. Benefits constantly need to be outlined and proven, and the new methods taught. Most designers these days style text with CSS, but many still don’t use CSS for entire web page layouts, despite the inherent advantages in doing so. This, of course, is one of the reasons for this book: to show you, the designer, how CSS can be beneficial to you—saving you (and your clients) time and money—and to provide examples for various areas of web page design and development that you can use in your sites.

Separating content from design

Use tables for website layout Use invisible GIFs to “push” elements around your web page Hack Photoshop documents to bits and stitch them back together in a web page to

create navigation elements and more Get frustrated when any combination of the previous leads to unwieldy web pages

that are a pain to editThe idea of separating content from design should appeal to you. On one hand, you

have your HTML documents, which house content marked up in a logical and semantic manner. On the other hand, you have your CSS documents, giving you site-wide control of the presentation of your web page elements from a single source. Instead of messing around with stretching transparent GIFs, and combining and splitting table cells, you can edit CSS rules to amend the look of your site, which is great for not only those times when things just need subtle tweaking, but also when you decide everything needs a visual overhaul.

After all, if presentation is taken care of externally, you can often just replace the CSS to provide your site with a totally new design. Designers (and clients paying for their

Page 41: 241254 Web Technology Lab Manual

time) aren’t the only ones to benefit from CSS. Visitors will, too, in terms of faster download times, but also with regard to accessibility.

The rules of CSSStyle sheets consist of a number of rules that define how various web page elements should be displayed. Although sometimes bewildering to newcomers, CSS rules are simple to break down. Each rule consists of a selector and a declaration. The selector begins a CSS rule and specifies which part of the HTML document the rule will be applied to. The declaration consists of a number of property/value pairs that set specific properties and determine how the relevant element will look. In the following example, p is the selector and everything thereafter is the declaration:

p {color: blue;}

As you probably know, p is the HTML tag for a paragraph. Therefore, if we attach this rule to a web page (see the section “Adding styles to a web page” later on in this chapter for how to do so), the declaration will be applied to any HTML marked up as a paragraph, thereby setting the color of said paragraphs to blue.

CSS property names are not case sensitive, but it’s good to be consistent in web design—it’s highly recommended to always use lowercase. Note, though, that XML is case sensitive, so when using CSS with XHTML documents served with the proper XHTML MIME type, everything must be consistent. Also, the W3 specifications recommend that CSS style sheets for XHTML should use lowercase element and attribute names.

Types of CSS selectors

In the previous example, the most basic style of selector was used: an element selector. This defines the visual appearance of the relevant HTML tag. In the sections that follow, we ’ll examine some other regularly used (and well-supported) CSS selectors: class, ID, grouped, and contextual.

Class selectors

In some cases, you may wish to modify an element or a group of elements. For instance,you may wish for your general website text to be blue, as in the examples so far, but some portions of it to be red. The simplest way of doing this is by using a class selector. In CSS, a class selector’s name is prefixed by a period (.), like this:

.warningText {color: red;}

Page 42: 241254 Web Technology Lab Manual

This style is applied to HTML elements in any web page the style sheet is attached to using the class attribute, as follows:

<h2 class="warningText">This heading is red.</h2><p class="warningText">This text is red.</p><p>This is a paragraph, <span class="warningText">and this text is red</span>.</p>

ID selectors

ID selectors can be used only once on each web page. In HTML, you apply a unique identifier to an HTML element with the id attribute:

<p id="footer">&copy; 200X The Company. All rights reserved.</p>

To style this element in CSS, precede the ID name with a hash mark (#):

p#footer {padding: 20px;}In this case, the footer div would have 20 pixels of padding on all sides.

Grouped selectors

Should you wish to set a property value for a number of different selectors, you can usegrouped selectors, which take the form of a comma-separated list:

Example:

h1, h2, h3, h4, h5, h6 {color: green;background-color:yellow;}

h1 {font-size: 1.5em;}

h2 {font-size: 1.2em;}

Contextual selectors

This selector type is handy when working with advanced CSS. As the name suggests, contextual selectors define property values for HTML elements depending on context. Take, for instance, the following example:

Page 43: 241254 Web Technology Lab Manual

<p>I am a paragraph.</p><p>So am I.</p><div id="navigation"><p>I am a paragraph within the navigation div.</p><p>Another paragraph within the navigation div.</p></div>

You can style the page’s paragraphs as a whole and then define some specific values for those within the navigation div by using a standard element selector for the former and a contextual selector for the latter:

p {color: black;}#navigation p {color: blue;font-weight: bold;}

Adding styles to a web page

The most common (and useful) method of applying CSS rules to a web page is by using external style sheets. CSS rules are defined in a text document, which is saved with the file suffix .css. This document is attached to an HTML document in one of two ways, both of which require the addition of HTML elements to the head section.

The first method of attaching a CSS file is to use a link tag:

<link rel="stylesheet" href="mystylesheet.css" type="text/css" media="screen" />

Alternatively, import the style sheet into the style element:

<style type="text/css" media="screen">/* <![CDATA[ */@import url(mystylesheet.css);/* ]]> */</style>

The second of these methods was initially used to “hide” CSS rules from noncompliant browsers, thereby at least giving users of such devices access to the website’s content, if not its design. In some browsers (notably Internet Explorer), however, this can cause a “flash” of unstyled content before the page is loaded. This flash doesn’t occur when a link element is also present.

Page 44: 241254 Web Technology Lab Manual

The style tag can also be used to embed CSS directly into the head section of a specific HTML document, like this:

<head><style type="text/css">/* <![CDATA[ */p {color: black;}#navigation p {color: blue;font-weight: bold;}/* ]]> */</style></head>

You’ll find that many visual web design tools create CSS in this manner, but adding rules to a style element is only worth doing if you have a one-page website, or if you want to affect tags on a specific page, overriding those in an attached style sheet (see the next section for more information). There’s certainly no point in adding styles like this to every page, because updating them would then require every page to be updated, rather than just an external style sheet. The third method of applying CSS is to do so as an inline style, directly in an element’s HTML tag:

<p style="color: blue;">This paragraph will be displayed in blue.</p>

As you can see, this method involves using the style attribute, and it’s only of use in very specific, one-off situations. There’s no point in using inline styles for all styling on your website—to do so would give few benefits over the likes of archaic font tags. Inline styles also happen to be deprecated in XHTML 1.1, so they’re eventually destined for the chop.

The cascade

It’s possible to define the rule for a given element multiple times: you can do so in the same style sheet, and several style sheets can be attached to an HTML document. On top of that, you may be using embedded style sheets and inline styles. The cascade is a way of dealing with conflicts, and its simple rule is this: In the following example, the second font-size setting for paragraphs takes precedence because it’s closest to paragraphs in the HTML: The value closest to the element in question is the one that is applied.

p {font-size: 1.1em;}p {font-size: 1.2em;}

Page 45: 241254 Web Technology Lab Manual

EX.No:DATE :

DEVELOPING WEB SITE USING INTERNAL AND EXTERNAL CSS ALONG WITH HTML PAGES.

AIM:

To develop a web site application using various html tags, forms, attributes, css

properties.

ALGORITHM:

Step 1: Start the program.

Step 2: Using html tags create a main page .

Step 3:Using link tags, open the various pages which links with the main page.

Step 4:Using img tag, place the pictures in web page, wherever it is needed.

Step 5:Using css properties create the link pages.

Step 6:Enter the details in link pages using html tags.

Step 7: Run the home page and click the link pages to view the details.

Step 8:Stop the program.

Page 46: 241254 Web Technology Lab Manual

PROGRAM:

Home.Html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Home Page</title><link href="css/style.css" rel="stylesheet" type="text/css" /></head><body>

<!-- Top panel -->

<table border="0" cellpadding="0" cellspacing="0" width="1000" align="center"><tr><td valign="top" class="tp_bg1"><a href="home.html"><img src="images/menu_home.gif" width="32" height="10" alt="" class="flt menu_home"/></a><a href="aboutus.html"><img src="images/menu_about.gif" width="50" height="10" alt="" class="flt menu_about" /></a><a href="#"><img src="images/menu_accnt.gif" width="52" height="10" alt="" class="flt menu_accnt" /></a><img src="images/menu_tour.gif" width="30" height="10" alt="" class="flt menu_tour" /></a><a href="#"><img src="images/menu_spl.gif" width="78" height="12" alt="" class="flt menu_spl" /></a><a href="contact.html"><img src="images/menu_cntrl.gif" width="49" height="10" alt="" class="flt menu_cntrl" /></a></td> </tr> <tr><td valign="top" class="tp_bg2"><a href="#"><img src="images/logo.gif" width="169" height="54" alt="" class="flt logo"/></a> </td></tr></table><!-- Top panel endz -->

<!-- Content panel -->

<table border="0" cellpadding="0" cellspacing="0" width="1000" style="background-color:#E4E6BE;" align="center"><tr> <td valign="top" width="698" style="padding-left:26px;"><p>&nbsp;</p><p><p><h2>Your interesting Air Travel</h2> </p><p> Curabitur mi nibh, cursus vel, laoreet sit amet, aliquet sit amet, justo. Lorem ipsum dolor sit amet, con- sectetuer adipiscing elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean vel magna. Nunc accumsan nulla. Nunc feugiat cursus lorem. Cras turpis. <br /><br />

Page 47: 241254 Web Technology Lab Manual

Curabitur vel velit. Curabitur mi nibh, cursus vel, laoreet sit amet, aliquet sit amet, justo. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id nibh. Sed risus. Fusce quis velit eu felis vestibulum sceleris- que. Nam lectus dolor, interdum at, mollis et, vehicula ut, sem. <a href="#"></a> </p><p>&nbsp;</p> <p>&nbsp;</p> <p>Latest News Lorem ipsum dolor sit amet, con- sectetuer adipiscing elit. Aenean vel magna. Nunc accumsan nulla. <a href="#"></a> Curabitur mi nibh, cursus vel, laoreet sit amet, aliquet sit amet, justo. Lorem ipsum dolor.Curabitur mi nibh, cursus vel, laoreet. <a href="#"></a> </p>

<p>&nbsp;</p><table align="left" border="1" color="blue"> <tbody> <tr> <td>&nbsp;USERNAME&nbsp;</td> <td><input name="Input" /></td></tr><tr> <td>&nbsp;PASSWORD&nbsp;</td> <td><input name="password" type="password" value="" /></td> </tr> <tr> <td colspan="4"><input type="button" value="SUBMIT" name="submit" /> &nbsp; &nbsp;&nbsp;&nbsp; <input type="reset" value=" RESET " name="clear" width="20" /></td> </tr> </tbody> </table>

<p>&nbsp;</p> <p><h2>&nbsp;</h2>

<p>&nbsp;</p> <h2>Hot Tours</h2> </p> <p><img src="images/cp_chinatwr.gif" width="273" height="92" alt=""

class="flt cp_chinatwr" /></p> <p>&nbsp; </p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp;</p> <p>&nbsp; </p> <p>&nbsp;</p> <p><a href="#"><img height="7" alt="" src="aboutus_cp_arrw.gif"

width="5" />Dolor sit amet, consectetuer adipis</a><br /><img height="7" alt="" src="aboutus_cp_arrw.gif" width="5" /><a href="#">Aliquam erat volutpat. Nulla id orci.</a><br /><img height="7" alt="" src="aboutus_cp_arrw.gif" width="5" /><a href="#">Phasellus congue justo quis leo.</a><br /><img height="7" alt="" src="aboutus_cp_arrw.gif" width="5" /><a href="#">sed urna imperdiet suscipit.</a> </p><p>&nbsp;</p> <p>&nbsp;</p></td><td valign="top" width="41"><img src="images/spacer.gif" /></td>

</tr> <tr><td valign="top" colspan="4" style="background-color:#ffffff;">&nbsp;</td></tr></table><!-- Content panel endz -->

Page 48: 241254 Web Technology Lab Manual

<!-- Footer panel --><table border="0" cellpadding="0" cellspacing="0" width="1000" align="center">

<tr> <td valign="top" class="footer_bg">

<a href="#" class="cp_anchrtxt1">Home</a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="aboutus.html#" class="cp_anchrtxt1"> About us </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="accounts.html" class="cp_anchrtxt1"> Accounts </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="booking.html" class="cp_anchrtxt1">Booking </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="specialoffer.html" class="cp_anchrtxt1"> Special Offers </a> <span style="margin:0px 11px 0px 11px;">|</span><a href="contact.html" class="cp_anchrtxt1"> Contacts</a><br /></td></tr></table><!-- Footer panel endz --></body></html>

Aboutus.Html<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Home Page</title><link href="css/style.css" rel="stylesheet" type="text/css" /></head><body><!-- Top panel --><table border="0" cellpadding="0" cellspacing="0" width="1000" align="center"><tr><td valign="top" class="tp_bg1"><a href="home.html"><img src="images/menu_home.gif" width="32" height="10" alt="" class="flt menu_home"/></a><a href="aboutus.html"><img src="images/menu_about.gif" width="50" height="10" alt="" class="flt menu_about" /></a><a href="#"><img src="images/menu_accnt.gif" width="52" height="10" alt="" class="flt menu_accnt" /></a><img src="images/menu_tour.gif" width="30" height="10" alt="" class="flt menu_tour" /></a><a href="#"><img src="images/menu_spl.gif" width="78" height="12" alt="" class="flt menu_spl" /></a><a href="contact.html"><img src="images/menu_cntrl.gif" width="49" height="10" alt="" class="flt menu_cntrl" /></a></td></tr><tr><td valign="top" class="tp_bg2"><a href="#"><img src="images/logo.gif" width="169" height="54" alt="" class="flt logo"/></a></td>

Page 49: 241254 Web Technology Lab Manual

</tr></table><!-- Top panel endz --><!-- Content panel --><table border="0" cellpadding="0" cellspacing="0" width="1000" style="background-color:#E4E6BE;" align="center">

<tr> <td valign="top" width="698" style="padding-left:26px;"><p>&nbsp;</p>

<p><h2>About us </h2><p>To render adequate, efficient, safe and economical air services Best airlines began its operation on 1st August, 2000 following the enactment of Air Corporations Act 2000. Today, Best Airlines, together with its fully owned subsidiary Alliance Air, has a fleet of 70 aircrafts. Since its very inception Indian Airlines has been setting standards for civil aviation. With many first in its credit, Indian Airlines has been feeding both the lavish and economical requirements of passengers across the globe. Over the years, Indian Airline has turned out to be synonymous with service, reliability and efficiency. Best Airlines' network covers Singapore in the East and Kuwait in the west and connects 18 destinations abroad. It's international network spans Oman, Kuwait, UAE, Qatar and Bahrain in West Asia; Singapore, Thailand, Malaysia and Mayanmar in South East Asia and Afghanistan, Pakistan, Nepal, Bangladesh, Sri Lanka and Maldives in the South Asia sub-continent. With a staff of over 500 thousand, Indian Airlines offers services which are simply exemplary and quite unmatched.</p></p> </p><ul> <li>Business to Consumer Solutions </li> </ul> <ul> <li>Internet Banking Solutions </li> </ul> <ul> <li>Intranet Workflow Solutions </li> </ul><ul> <li>E-Governance Solutions </li> </ul><ul> <li>Corporate Wide E-Mail Infrastructure </li> </ul><ul><li>Internet/Intranet Security Solutions Dynamic Web Design and Consultancy </li> </ul><ul><li>Domain Name Registration </li> </ul><ul> <li>Key Name Registration </li> </ul><ul><li>Web Sever Co-location Solutions </li> </ul><ul> <li>Call center Solutions </li> </ul><ul> <li>Company Wide Internet Connectivity </li> </ul><ul> <li>Web Hosting solutions </li> </ul><ul> <li>Shared Hosting Services </li> </ul> <ul> <li>Customer Relation Management (CRM) Solutions </li> </ul>

<p style="float:left;width:641px;margin-top:22px;"><span style="float:left;font:11px/20px verdana;color:#29022A;margin:20px 0px 0px 0px;"><a href="#"></a> </span> </p>

</td><td valign="top" width="41"><img src="images/spacer.gif" /></td>

</tr><tr>

<td valign="top" colspan="4" style="background-color:#ffffff;">&nbsp;</td></tr></table><!-- Content panel endz --><!-- Footer panel -->

Page 50: 241254 Web Technology Lab Manual

<table border="0" cellpadding="0" cellspacing="0" width="1000" align="center"><tr>

<td valign="top" class="footer_bg"><a href="#" class="cp_anchrtxt1">Home</a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="aboutus.html#" class="cp_anchrtxt1"> About us </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="accounts.html" class="cp_anchrtxt1"> Accounts </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="booking.html" class="cp_anchrtxt1">Booking </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="specialoffer.html" class="cp_anchrtxt1"> Special Offers </a> <span style="margin:0px 11px 0px 11px;">|</span><a href="contact.html" class="cp_anchrtxt1"> Contacts</a><br /></td></tr></table><!-- Footer panel endz --></body></html>

Booking.Html<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Home Page</title><link href="css/style.css" rel="stylesheet" type="text/css" /></head><body><!-- Top panel --><table border="0" cellpadding="0" cellspacing="0" width="1000" align="center"><tr><td valign="top" class="tp_bg1"><a href="home.html"><img src="images/menu_home.gif" width="32" height="10" alt="" class="flt menu_home"/></a><a href="aboutus.html"><img src="images/menu_about.gif" width="50" height="10" alt="" class="flt menu_about" /></a><a href="#"><img src="images/menu_accnt.gif" width="52" height="10" alt="" class="flt menu_accnt" /></a><img src="images/menu_tour.gif" width="30" height="10" alt="" class="flt menu_tour" /></a><a href="#"><img src="images/menu_spl.gif" width="78" height="12" alt="" class="flt menu_spl" /></a><a href="contact.html"><img src="images/menu_cntrl.gif" width="49" height="10" alt="" class="flt menu_cntrl" /></a></td> </tr> <tr><td valign="top" class="tp_bg2"><a href="#"><img src="images/logo.gif" width="169" height="54" alt="" class="flt logo"/></a> </td> </tr></table><!-- Top panel endz --><!-- Content panel --><Form>

Page 51: 241254 Web Technology Lab Manual

<center><h2 style="color:BLUE">Ticket Booking </h2></center><table align=center border=2><tr><td>Departure <Input type=radio name="desparture"></td><td>Arriaval <Input type=radio name="arrival"></td></tr><tr></tr><tr><td> From <Select><option> Chennai </option><option> Delhi</option><option> Kolkata</option><option> bangalore </option><option> London </option><option> Mumbai </option><option> Singapore</option><option> muscat</option></select></td><td>To <Select><option> Chennai </option><option> Delhi</option><option> Kolkata</option><option> bangalore </option><option> London </option><option> Mumbai </option><option> Singapore</option><option> muscat</option></select></td></tr><tr><td colspan=2> Date <Input type="text" ></td></tr><tr><td> Adult <Select><option> 1</option><option> 2</option><option> 3</option><option> 4 </option><option> 5 </option><option> 6 </option><option> 7</option><option> 8 </option></select></td> <td> Child <Select><option> 1</option><option> 2</option><option> 3</option><option> 4 </option><option> 5 </option><option> 6 </option><option> 7</option><option> 8 </option></select></td></tr><tr><td> Pay by Bank<Select><option> Indian bank</option><option> State bank</option><option> ICICI BANK</option><option> HDFC BANK </option><option> AXIS BANK </option><option> IDBI Bank </option><option> Indian overseas Bank</option><option> CITY BANK </option></select></td><td>Amount <Input type="text" ></td></tr><tr><td align=center colspan=2><Input type=submit value="submit"><Input type=Reset value="Reset"></td></tr></table></form>

Page 52: 241254 Web Technology Lab Manual

<!-- Content panel endz -->

<!-- Footer panel -->

<table border="0" cellpadding="0" cellspacing="0" width="1000" align="center"><tr>

<td valign="top" class="footer_bg"><a href="#" class="cp_anchrtxt1">Home</a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="aboutus.html#" class="cp_anchrtxt1"> About us </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="accounts.html" class="cp_anchrtxt1"> Accounts </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="booking.html" class="cp_anchrtxt1">Booking </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="specialoffer.html" class="cp_anchrtxt1"> Special Offers </a> <span style="margin:0px 11px 0px 11px;">|</span><a href="contact.html" class="cp_anchrtxt1"> Contacts</a><br /></td> </tr></table><!-- Footer panel endz -->

</body></html>

Contacts.html :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Home Page</title><link href="css/style.css" rel="stylesheet" type="text/css" /></head><body>

<!-- Top panel -->

<table border="0" cellpadding="0" cellspacing="0" width="1000" align="center"><tr><td valign="top" class="tp_bg1"><a href="home.html"><img src="images/menu_home.gif" width="32" height="10" alt="" class="flt menu_home"/></a><a href="aboutus.html"><img src="images/menu_about.gif" width="50" height="10" alt="" class="flt menu_about" /></a><a href="#"><img src="images/menu_accnt.gif" width="52" height="10" alt="" class="flt menu_accnt" /></a><img src="images/menu_tour.gif" width="30" height="10" alt="" class="flt menu_tour" /></a><a href="#"><img src="images/menu_spl.gif" width="78" height="12" alt="" class="flt menu_spl" /></a><a href="contact.html"><img src="images/menu_cntrl.gif" width="49" height="10" alt="" class="flt menu_cntrl" /></a></td>

Page 53: 241254 Web Technology Lab Manual

</tr><tr><td valign="top" class="tp_bg2"><a href="#"><img src="images/logo.gif" width="169" height="54" alt="" class="flt logo"/></a></td></tr></table>

<!-- Top panel endz -->

<!-- Content panel -->

<table border="0" cellpadding="0" cellspacing="0" width="1000" style="background-color:#E4E6BE;" align="center"><tr>

<td valign="top" width="698" style="padding-left:26px;"><p>&nbsp;</p><p><h2>Email Supporting </h2><p>Use the form below to get in touch with us in connection with the travel related queries. </p><table><tbody><tr><td>Name</td><td><input name="Input" width="25" height="10" /></td></tr><tr><td>email ID</td><td><input name="Input2" width="25" height="10" /></td></tr><tr><td>subject</td><td><select name="subject"><option value="Delhi" selected="selected">Delhi</option><option value="mumbai">mumbai</option><option value="chennai">chennai</option><option value="kolkata">kolkata</option><option value="bangalore">bangalore</option><option value="covai">covai</option><option value="singapure">singapure</option><option value="muscat">muscat</option></select></td></tr><tr><td>location</td><td><select name="location"><option value="reservation" selected="selected">reservation</option><option value="product and services">product and services</option><option value="complients and compliments">complients and compliments</option><option value="fares and tickets">fares and tickets</option>

Page 54: 241254 Web Technology Lab Manual

<option value="frequently flyer">frequently flyer</option><option value="feedback">feedback</option><option value="others">others</option>&gt;</select></td></tr><tr><td>Descrption</td><td colspan="5"><textarea name="male" rows="5" cols="70"></textarea></td></tr></tbody></table></td><td valign="top" width="41"><img src="images/spacer.gif" /></td></tr><tr><td valign="top" colspan="4" style="background-color:#ffffff;">&nbsp;</td></tr></table><!-- Content panel endz --><!-- Footer panel --><table border="0" cellpadding="0" cellspacing="0" width="1000" align="center"><tr><td valign="top" class="footer_bg"><a href="#" class="cp_anchrtxt1">Home</a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="aboutus.html#" class="cp_anchrtxt1"> About us </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="accounts.html" class="cp_anchrtxt1"> Accounts </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="booking.html" class="cp_anchrtxt1">Booking </a> <span style="margin:0px 11px 0px 11px;">|</span> <a href="specialoffer.html" class="cp_anchrtxt1"> Special Offers </a> <span style="margin:0px 11px 0px 11px;">|</span><a href="contact.html" class="cp_anchrtxt1"> Contacts</a><br /></td></tr></table><!-- Footer panel endz --></body></html>

Page 55: 241254 Web Technology Lab Manual

Sample Output :

Page 56: 241254 Web Technology Lab Manual

RESULT:

Thus the website has been developed sucessfully.

Page 57: 241254 Web Technology Lab Manual

INTRODUCTION TO CLIENT SIDE PROGRAMMING (JAVA SCRIPT-Validation)

JavaScript: A Language for All

Sun’s Java language is derived from C and C++, but it is a distinct language. Its main audience is the experienced programmer. That leaves out many Web-page authors. I was dismayed by this situation when I first read about Java’s preliminary specifications in 1995. I would have preferred a language that casual programmers and scripters who were comfortable with authoring tools, such as Apple’s once-formidable HyperCard and Microsoft’s Visual Basic, could adopt quickly. As these accessible development platforms have shown, nonprofessional authors can dream up many creative applications, often for very specific tasks that no professional programmer would have the inclination to work on. Personal needs often drive development in the classroom, office, den, or garage. But Java was not going to be that kind of inclusive language.

Live Script becomes JavaScript

In early December 1995, just prior to the formal release of Navigator 2, Netscape and Sun Microsystems jointly announced that the scripting language thereafter would be known as JavaScript. Though Netscape had several good marketing reasons for adopting this name, the changeover may have contributed more confusion to both the Java and HTML scripting worlds than anyone expected.

Before the announcement, the language was already related to Java in some ways. Many of the basic syntax elements of the scripting language were reminiscent of the Java style. For client-side scripting, the language was intended for very different purposes than Java—essentially to function as a programming language integrated into HTML documents rather than as a language for writing applets that occupy a fixed rectangular area on the page (and that are oblivious to anything else on the page). Instead of Java’s full-blown programming language vocabulary (and conceptually more difficult to learn object-oriented approach), JavaScript had a small vocabulary and a more easily digestible programming model.

The true difficulty, it turned out, was making the distinction between Java and JavaScript clear to the world. Many computer journalists made major blunders when they said or implied that JavaScript provided a simpler way of building Java applets. To this day, some new programmers believe JavaScript is synonymous with the Java language: They post Java queries to JavaScript-specific Internet newsgroups and mailing lists. The fact remains that client-side Java and JavaScript are more different than they are similar. The two languages employ entirely different interpreter engines to execute their lines of code.

JavaScript: The Right Tool for the Right Job

Knowing how to match an authoring tool to a solution-building task is an important part of being a wellrounded Web site author. A Web designer who ignores JavaScript is akin to a plumber who bruises his knuckles by using pliers instead of the wrench from the bottom of the toolbox.

Page 58: 241254 Web Technology Lab Manual

By the same token, JavaScript won’t fulfill every dream. The more you understand about JavaScript’s intentions and limitations, the more likely you will be to turn to it immediately when it is the proper tool. In particular, look to

JavaScript for the following kinds of solutions:

Getting your Web page to respond or react directly to user interaction with form elements (input

fields, text areas, buttons, radio buttons, checkboxes, selection lists) and hypertext links

Distributing small collections of databaselike information and providing a friendly interface to that data

Controlling multiple-frame navigation, plug-ins, or Java applets based on user choices in the HTML document

Preprocessing data on the client before submission to a serverChanging content and styles in modern browsers dynamically and instantly in response to userInteraction At the same time, it is equally important to understand what JavaScript is not capable of doing. Scripters waste many hours looking for ways of carrying out tasks for which JavaScript was not designed. Most of the limitations are designed to protect visitors from invasions of privacy or unauthorized access to their desktop computers. Therefore, unless a visitor uses a modern browser and explicitly gives you permission to access protected parts of his or her computer, JavaScript cannot surreptitiously perform any of the following actions:

Setting or retrieving the browser’s preferences settings, main window appearance features, action buttons, and printing

Launching an application on the client computer Reading or writing files or directories on the client or server computer Capturing live data streams from the server for retransmission Sending secret e-mails from Web site visitors to you

Follow these steps to enter and preview your first JavaScript script:

1. Activate your text editor and create a new, blank document.2. Type the script in the window exactly as shown in Listing 3-1.Follow the example slowly and carefully, paying special attention to:a. The uppercase and lowercase lettersb. The placement of single (‘) and double (“) quote symbolsc. The usage of parentheses, angle brackets (< and >), and curly braces ({ and })

LISTING 3-1

Source Code for script1.html<html><head><title>My First Script</title><style type=”text/css”>.highlight {color: red}</style>

Page 59: 241254 Web Technology Lab Manual

<script type=”text/javascript”>function showBrowserType() {document.getElementById(“readout”).innerHTML =“Your browser says it is: “ +“<span class=’highlight’>” +navigator.userAgent + “</span>.<hr />”;}window.onload = showBrowserType;</script></head><body><h1>Let’s Script...</h1><hr><h1>Let’s Script...</h1><hr /><div id=”readout”></div></body></html>

3. Save the document with the name script1.html.4. Switch to your browser.5. Choose Open (or Open File on some browsers) from the File menu, and select script1.html.(On some browsers, you have to click a Browse button to reach the File dialog box.)

When to Use JavaScriptWith so many web-oriented development tools and languages at your disposal, you should focus your client-side JavaScript efforts on tasks for which they are best suited. When faced with a web application task, I look to client-side JavaScript for help with the following requirements:

Data entry validation. If form fields need to be filled out for processing on the server, I let clientsidescripts prequalify the data entered by the user.

Serverless CGIs. I use this term to describe processes that, were it not for JavaScript, would be programmed as CGIs on the server, yielding slow performance because of the interactivity required between the program and user. This includes tasks such as small data collection lookup, modification of images, and generation of HTML in other frames and windows based on user input.

Dynamic HTML interactivity. It’s one thing to use DHTML’s capabilities to position elements precisely on the page; you don’t need scripting for that. But if you intend to make the content dance on the page, scripting makes that happen.

CGI prototyping. Sometimes you want a CGI program to be at the root of your application because it reduces the potential incompatibilities among browser brands and versions. It may be easier to create a prototype of the CGI in client-side JavaScript. Use this opportunity to polish the user interface before implementing the application as a CGI.

Page 60: 241254 Web Technology Lab Manual

Offloading a busy server. If you have a highly trafficked web site, it may be beneficial to convert frequently used CGI processes to client-side JavaScript scripts. After a page is downloaded, the server is free to serve other visitors. Not only does this lighten server load, but users also experience quicker response to the application embedded in the page.

Adding life to otherwise-dead pages. HTML by itself is pretty flat. Adding a blinking chunk of text doesn’t help much; animated GIF images more often distract from, rather than contribute to, the user experience at your site. But if you can dream up ways to add some interactive zip to your page, it may engage the user and encourage a recommendation to friends or repeat visits.

Creating web pages that “think.” If you let your imagination soar, you may develop new, intriguing ways to make your pages appear “smart.” For example, in the application Intelligent “Updated” Flags (Chapter 54 on the CD-ROM), you see how (without a server CGI or database) an HTML page can “remember” when a visitor last came to the page. Then any items that have been updated since the last visit—regardless of the number of updates you’ve done to the page—are flagged for that visitor. That’s the kind of subtle, thinking web page that best displays JavaScript’s powers.

The Document Object ModelBefore you can truly start scripting, you should have a good feel for the kinds of objects you will be scripting. A scriptable browser does a lot of the work of creating software objects that generally represent the visible objects you see in an HTML page in the browser window. Obvious objects include form controls (text boxes and buttons) and images. However, there may be other objects that aren’t so obvious by looking at a page but that make perfect sense when you consider the HTML tags used to generate a page’s content— paragraph objects or frames of a frameset, for example. To help scripts control these objects—and to help authors see some method to the madness of potentially dozens of objects on a page—the browser makers define a document object model (DOM). A model is like a prototype or plan for the organization of objects on a page. Evolution of browser DOMs has caused much confusion and consternation among scripters due to a lack of compatibility across succeeding generations and brands of browsers. Fortunately, the DOM world is stabilizing around a formal specification published by the World Wide Web Consortium (W3C). Today’s modern browsers continue to support some of the “old ways” of the earliest DOM because so much existing script code on the Web relies on these traditions continuing to work (you’ll see some of these in Chapter 9). But with the vast majority of browsers in use today supporting the basic W3C DOM syntax and terminology, scripters should aim toward standards compatibility whenever possible.

HTML structure and the DOMAn important trend in HTML markup is applying markup solely to define the structure of a document and the context of each piece of content in the document. The days of using HTML tags solely to influence the appearance of a chunk of text are drawing to a close. It is no longer acceptable to enclose a line of text in, say, an <h1> tag because you want the line to appear in the text size and weight that browsers automatically apply to text tagged in that way. An <h1> element has a special context within a document’s structure: a first-level heading. In today’s HTML world, if you wish to display a stand-alone line of text with a particular style, the text would likely be in a simple paragraph (<p>) tag; the precise look of that paragraph would be under the control of a Cascading Style Sheet (CSS) rule. Current practice even frowns upon the application

Page 61: 241254 Web Technology Lab Manual

of <b> and <i> tags to assign boldface and italic styles to a span of text. Instead, surround the text with a contextual tag (such as the <em> element to signify emphasis), and define the CSS style you wish applied to any emphasized text in the document.

A simple documentFigure 4-3 shows the HTML and corresponding object model for a document that I’ll be adding to in a moment. The figure shows only the document object portion; the window object and its other top-level objects (including the document object) are always there, even for an empty document. When this page loads, the browser maintains in its memory a map of the objects generated by the HTML tags in the document. At this point, only three objects exist inside the document object: one for the outermost html element and one each for its two nested elements.

Element hierarchy of an empty HTML document.

Add a paragraph elementNow I modify the HTML file to include an empty paragraph element and reload the document. Figure 4-4 shows what happens to both the HTML (changes in boldface) and the object map as constructed by the browser. Even though no content appears in the paragraph, the <p> tags are enough to tell the browser to create that p element object. Also note that the p element object is contained by the body element object in the hierarchy of objects in the current map. In other words, the p element object is a child of the body element object. The object hierarchy matches the HTML tag containment hierarchy.

The DOM in a browser windowAs its name implies, the formal DOM focuses primarily on the HTML document and the content nested inside it. From a practical standpoint, however, scripters often need to control the environment that contains the document: the window. The window object is the top of the hierarchy that browser scripts work with. The basic structure of the object model in modern browsers (given an empty HTML document) is shown in Figure.

Basic object model for all modern browsers.

Page 62: 241254 Web Technology Lab Manual

The relationships among these top-level objects, the following describes their respective roles:window object. At the very top of the hierarchy is the window. This object represents the content area of the browser window where HTML documents appear. In a multiple-frame environment, each frame is also a window (but don’t concern yourself with this just yet). Because all document action takes place inside the window, the window is the outermost element of the object hierarchy. Its physical borders contain the document.

navigator object. This is the closest your scripts come to accessing the browser program, primarily to read the brand and version of browser that holds the current document. This object is read-only, protecting the browser from inappropriate manipulation by rogue scripts.

screen object. This is another read-only object that lets scripts learn about the physical environmentin which the browser is running. For example, this object reveals the number of pixels highand wide available in the monitor.

history object. Although the browser maintains internal details about the browser’s recent history(such as the list available under the Back button), scripts have no access to the details. At most, this object assists a script in simulating a click of the Back or Forward button.

location object. This object is the primary avenue to loading a different page into the current window or frame. URL information about the window is available under very controlled circumstances so that scripts cannot track access to other web sites.

document object. Each HTML document that gets loaded into a window becomes a document object. The document object contains the content that you are likely to script. Except for the html, head, and body element objects that are found in every HTML document, the precise makeup and structure of the element object hierarchy of the document depend on the content you put into the document.

A simple HTML document node tree.

Page 63: 241254 Web Technology Lab Manual

JavaScript StatementsVirtually every line of code that sits between a <script>... </script> tag pair is a JavaScript statement. To be compatible with habits of experienced programmers, JavaScript accepts a semicolon at the end of every statement (the computer equivalent of a period at the end of a sentence). Fortunately for newcomers, this semicolon is optional: The carriage return at the end of a statement suffices for JavaScript to know that the statement has ended. It is possible that in the future, the semicolon will be required, so it’s a good idea to get into the semicolon habit now.

A statement must be in the script for a purpose. Therefore, every statement does something relevant to the script. The kinds of things that statements do are

Define or initialize a variable Assign a value to a property or variable Change the value of a property or variable Invoke an object’s method Invoke a function routine Make a decision

When Script Statements ExecuteNow that you know where scripts go in a document, it’s time to look at when they run. Depending on what you need a script to do, you have four choices for determining when a script runs:

While a document loads Immediately after a document loads In response to user action When called upon by other script statements

While a document loads: immediate executionListing is a variation of your first script from Chapter 3. In this version, the script

writes the browser information to the page while the page loads. The document.write() method is the primary way to cause dynamic content—the values of the two navigator object properties in this case—to be rendered in the page during loading. I call the kinds of statements that run as the page loads immediate statements.

LISTING

HTML Page with Immediate Script Statements<html><head><title>My First Script--II</title><style type=”text/css”>.highlight {font-weight: bold}</style></head><body><h1>Let’s Script...</h1><hr><script type=”text/javascript”><!-- hide from old browsersdocument.write(“This browser is version “ + navigator.appVersion);document.write(“ of <span class=’highlight’>” + navigator.appName + “</span>.”);// end script hiding -->

Page 64: 241254 Web Technology Lab Manual

</script></body></html>

Deferred scriptsThe other three ways that script statements run are grouped together as what I call deferred scripts. To demonstrate these deferred script situations, A function defines a block of script statements summoned to run some time after those statements load into the browser. Functions are clearly visible inside a <script> tag because each function definition begins with the word function followed by the function name (and parentheses). After a function is loaded into the browser (commonly in the Head portion so that it loads early), it stands ready to run whenever called upon.

Run after loadingOne of the times a function is called upon to run is immediately after a page loads. The window object has an event handler property called onload. Unlike most event handlers, which are triggered in response to user action (for example, clicking a button), the window’s onload event handler fires the instant that all of the page’s components (including images, Java applets, and embedded multimedia) are loaded into the browser.

There are two cross-browser ways to connect the onload event handler to a function: via an HTML event attribute or an object event property. For the HTML attribute approach, the <body> element stands in to represent the window. Therefore, you can include the onload event attribute in the <body> tag, as shown in Listing. Recall from Chapter 4 (Listing 4-1) that an event handler can run a script statement directly. But if the event handler must run several script statements, it is usually more convenient to put those statements in a function definition and then have the event handler invoke that function. That’s what happens in Listing 5-7: When the page completes loading, the onload event handler triggers the done() function. That function (simplified for this example) displays an alert dialog box.

LISTING Running a Script from the onload Event Handler<html><head><title>An onload script</title><script type=”text/javascript”><!--function done() {alert(“The page has finished loading.”);}// --></script></head><body onload=”done()”>Here is some body text.</body></html>

Page 65: 241254 Web Technology Lab Manual

Viewing Script ErrorsIn the early days of JavaScript in browsers, script errors displayed themselves in very obvious dialog boxes. These boxes were certainly helpful for scripters who wanted to debug their scripts. However, if a bug got through to a page served up to a nontechnical user, the error alert dialog boxes were not only disruptive, but also scary. To prevent such dialog boxes from disturbing unsuspecting users, the browser makers tried to diminish the visual impact of errors in the browser window. Unfortunately for scripters, it is often easy to overlook the fact that your script contains an error because the error is not so obvious. Recent browser versions have different ways of letting scripters see the errors. In IE5+, you can set its preferences so that scripts do not generate error dialog boxes (choose Tools ->Internet Options -> Advanced -> Browsing, and find the checkbox entry that says Display a notification about every script error). Even with error dialog boxes turned off, error indications are displayed subtly at the left edge of the browser window’s status bar. An alert icon and message (“Error on page”) appear in the status bar. If you double-click the icon, the error dialog box appears (see Figure 5-1). Be sure to expand the dialog box by clicking the Show Details button. Unless you turn on script-error dialog boxes and keep them coming, you have to train yourself to monitor the status bar when a page loads and after each script runs.

FIGURE 5-1The expanded IE error dialog box.

For Mozilla-based browsers, choose Tools Web Development JavaScript (or Error)➪ ➪ Console. The JavaScript console window opens to reveal the error message details (see Figure 5-2). You can keep this window open all the time if you like. Unless you clear the window, subsequent error messages are appended to the bottom of the window.

Page 66: 241254 Web Technology Lab Manual

EX.No : 3a

Date :

CLIENT SIDE PROGRAMMING JAVASCRIPT FOR DISPLAYING DATE AND COMPARING TWO DATES

AIM:

To validate the student profile using javascript.

ALGORITHM:

Step 1: start the program.

Step 2: Design a home page student profile using different html tags,forms and

attributes.

Step 3:Using javascript, we validate whether the text and other text fields are

empty or to be filled.

Step 4:Check whether the checkbox has been already checked or not.

Step 5: Check whether the radio button has been already checked or not.

Step 6: Check whether the nick name is used as a password or not.

Step 7: Validate the date of birth that should be in date format(dd-mm-yy) or not.

Step 8: Allow the age field size should be two and only be the numbers.

Step 9:In the name field,ensure that it should allow only the capital letters.

Step 10:Check that the password field contains only the 8 characters.

Step 11:Execute the program in Internet explorer.

Step 12:Stop the program.

Page 67: 241254 Web Technology Lab Manual

PROGRAM:<html>

<head>

<title>Compare Dates</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<Script Language=Javascript>

function CompareDates()

{

var str1 = document.getElementById("Fromdate").value;

var str2 = document.getElementById("Todate").value;

var dt1 = parseInt(str1.substring(0,2),10);

var mon1 = parseInt(str1.substring(3,5),10);

var yr1 = parseInt(str1.substring(6,10),10);

var dt2 = parseInt(str2.substring(0,2),10);

var mon2 = parseInt(str2.substring(3,5),10);

var yr2 = parseInt(str2.substring(6,10),10);

var date1 = new Date(yr1, mon1, dt1);

var date2 = new Date(yr2, mon2, dt2);

if(date2 < date1)

{

alert("To date cannot be greater than from date");

return false;

}

else

{

alert("Submitting ...");

document.form1.submit();

}

}

</Script>

</head>

Page 68: 241254 Web Technology Lab Manual

<body bgcolor="#FFFFdd" text="#000000">

<br>

<br>

<h1 align=center style={color:maroon}><u>Date Comparison</u></h1><br><br>

<center>

<form name="form1" method="post" action="">

<input type="text" name="fromdate" id="fromdate" value="">

<input type="text" name="todate" id="todate" value=""><br><br><br>

<input type="button" value="compare dates" onclick="CompareDates()">

</form>

</center>

</body>

</html>

Page 69: 241254 Web Technology Lab Manual

Sample Output:

RESULT:

Thus the program for Javascript for displaying date and comparing two Dates has been successfully compiled and executed..

Page 70: 241254 Web Technology Lab Manual

EX.NO: 3b

DATE:

FORM VALIDATION INCLUDING TEXTFIELD, RADIO BUTTONS,

CHECKBOXES, LISTBOX AND OTHER CONTROLS

AIM:

To validate the student profile using javascript.

ALGORITHM:

Step 1: start the program.

Step 2: Design a home page student profile using different html tags,forms and

attributes.

Step 3:Using javascript, we validate whether the text and other text fields are

empty or to be filled.

Step 4:Check whether the checkbox has been already checked or not.

Step 5: Check whether the radio button has been already checked or not.

Step 6: Check whether the nick name is used as a password or not.

Step 7: Validate the date of birth that should be in date format(dd-mm-yy) or not.

Step 8: Allow the age field size should be two and only be the numbers.

Step 9:In the name field,ensure that it should allow only the capital letters.

Step 10:Check that the password field contains only the 8 characters.

Step 11:Execute the program in Internet explorer.

Step 12:Stop the program.

Page 71: 241254 Web Technology Lab Manual

PROGRAM :

<html>

<head><title> from validation </title>

function checkEmail (strng) {var error="";if (strng == "") { error = "You didn't enter an email address.\n";}

var emailFilter=/^.+@.+\..{2,3}$/; if (!(emailFilter.test(strng))) { error = "Please enter a valid email address.\n"; } else {//test email for illegal characters var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ if (strng.match(illegalChars)) { error = "The email address contains illegal characters.\n"; } }return error; }

// phone number - strip out delimiters and check for 10 digits

function checkPhone (strng) {var error = "";if (strng == "") { error = "You didn't enter a phone number.\n";}

var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters if (isNaN(parseInt(stripped))) { error = "The phone number contains illegal characters."; } if (!(stripped.length == 10)) {

error = "The phone number is the wrong length. Make sure you included an area code.\n"; } return error;}

// password - between 6-8 chars, uppercase, lowercase, and numeral

Page 72: 241254 Web Technology Lab Manual

function checkPassword (strng) {var error = "";if (strng == "") { error = "You didn't enter a password.\n";}

var illegalChars = /[\W_]/; // allow only letters and numbers if ((strng.length < 6) || (strng.length > 8)) { error = "The password is the wrong length.\n"; } else if (illegalChars.test(strng)) { error = "The password contains illegal characters.\n"; } else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) { error = "The password must contain at least one uppercase letter, one lowercase letter, and one numeral.\n"; } return error; }

// username - 4-10 chars, uc, lc, and underscore only.

function checkUsername (strng) {var error = "";if (strng == "") { error = "You didn't enter a username.\n";}

var illegalChars = /\W/; // allow letters, numbers, and underscores if ((strng.length < 4) || (strng.length > 10)) { error = "The username is the wrong length.\n"; } else if (illegalChars.test(strng)) { error = "The username contains illegal characters.\n"; } return error;}

// non-empty textbox

function isEmpty(strng) {var error = ""; if (strng.length == 0) { error = "The mandatory text area has not been filled in.\n" }return error;

Page 73: 241254 Web Technology Lab Manual

}

// was textbox altered

function isDifferent(strng) {var error = ""; if (strng != "Can\'t touch this!") { error = "You altered the inviolate text area.\n"; }return error;}

// exactly one radio button is chosen

function checkRadio(checkvalue) {var error = ""; if (!(checkvalue)) { error = "Please check a radio button.\n"; }return error;}

// valid selector from dropdown list

function checkDropdown(choice) {var error = ""; if (choice == 0) { error = "You didn't choose an option from the drop-down list.\n"; } return error;}

</head>

</html>

Page 74: 241254 Web Technology Lab Manual

Sample output:

RESULT:

Thus the web page for student profile has been developed and validated

successfully.

Page 75: 241254 Web Technology Lab Manual

INTRODUCTION TO JSP

Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSP pages are loaded in the server and operated from a structured special installed Java server packet called a Java EE Web Application, often packaged as a .war or .ear file archive.

JSP allows Java code and certain pre-defined actions to be interleaved with static web markup content, with the resulting page being compiled and executed on the server to deliver an HTML or XML document. The compiled pages and any dependent Java libraries use Java bytecode rather than a native software format, and must therefore be executed within a Java virtual machine (JVM) that integrates with the host operating system to provide an abstract platform-neutral environment.

JSP syntax is a fluid mix of two basic content forms: scriptlet elements and markup. Markup is typically standard HTML or XML, while scriptlet elements are delimited blocks of Java code which may be intermixed with the markup. When the page is requested the Java code is executed and its output is added, in situ, with the surrounding markup to create the final page. Because Java is a compiled language, not a scripting language, JSP pages must be compiled to Java bytecode classes before they can be executed, but such compilation generally only occurs once each time a change to the source JSP file occurs.

Java code is not required to be complete (self contained) within its scriptlet element block, but can straddle markup content providing the page as a whole is syntactically correct (for example, any Java if/for/while blocks opened in one scriptlet element must be correctly closed in a later element for the page to successfully compile). This system of split inline coding sections is called step over scripting because it can wrap around the static markup by stepping over it. Markup which falls inside a split block of code is subject to that code, so markup inside an if block will only appear in the output when the if condition evaluates to true; likewise markup inside a loop construct may appear multiple times in the output depending upon how many times the loop body runs.

The JSP syntax adds additional XML-like tags, called JSP actions, 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. JVM operated Tag libraries provide a platform independent way of extending the capabilities of a web server. Note that not all company makes of Java servers are Java EE specification compliant.

Starting with version 1.2 of the JSP specification, JavaServer Pages have been developed under the Java Community Process. JSR 53 defines both the JSP 1.2 and Servlet 2.3 specifications and JSR 152 defines the JSP 2.0 specification. As of May 2006 the JSP 2.1 specification has been released under JSR 245 as part of Java EE 5. As of Dec 10, 2009 the JSP 2.2 specification has been released as a maintenance release of JSR 245.

Page 76: 241254 Web Technology Lab Manual

You create dynamic content by accessing Java programming language objects from within scripting elements.

Using Objects within JSP Pages

You can access a variety of objects, including enterprise beans and JavaBeans components, within a JSP page. JSP technology automatically makes some objects available, and you can also create and access application-specific objects.

Implicit Objects

Implicit objects are created by the Web container and contain information related to a particular request, page, or application. Many of the objects are defined by the Java Servlet technology underlying JSP technology and are discussed at length in Chapter 10. Table 11-2 summarizes the implicit objects.

Table 11-2 Implicit Objects 

Variable Class Description

application javax.servlet.ServletContext

The context for the JSP page's servlet and any Web components contained in the same application. See Accessing the Web Context.

config javax.servlet.ServletConfigInitialization information for the JSP page's servlet.

exception java.lang.ThrowableAccessible only from an error page. See Handling Errors.

out javax.servlet.jsp.JspWriter The output stream.

page java.lang.ObjectThe instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors.

pageContext javax.servlet.jsp.PageContext

The context for the JSP page. Provides a single API to manage the various scoped attributes described in Sharing Information.This API is used extensively when implementing tag handlers. See Tag Handlers.

requestSubtype of javax.servlet.ServletRequest

The request triggering the execution of the JSP page. See Getting Information from Requests.

responseSubtype of javax.servlet.ServletResponse

The response to be returned to the client. Not typically used by JSP page authors.

Page 77: 241254 Web Technology Lab Manual

session javax.servlet.http.HttpSessionThe session object for the client. See Accessing the Web Context.

Application-Specific Objects

When possible, application behavior should be encapsulated in objects so that page designers can focus on presentation issues. Objects can be created by developers who are proficient in the Java programming language and in accessing databases and other services. There are four ways to create and use objects within a JSP page:

Instance and class variables of the JSP page's servlet class are created in declarations and accessed in scriptlets and expressions.

Local variables of the JSP page's servlet class are created and used in scriptlets and expressions.

Attributes of scope objects (see Using Scope Objects) are created and used in scriptlets and expressions.

JavaBeans components can be created and accessed using streamlined JSP elements. These elements are discussed in Chapter 12. You can also create a JavaBeans component in a declaration or scriptlet and invoke the methods of a JavaBeans component in a scriptlet or expression.

Declarations, scriptlets, and expressions are described in JSP Scripting Elements.

Shared Objects

The conditions affecting concurrent access to shared objects described in Sharing Information apply to objects accessed from JSP pages that run as multithreaded servlets. You can indicate how a Web container should dispatch multiple client requests with the following page directive:

<%@ page isThreadSafe="true|false" %>

When isThreadSafe is set to true, the Web container may choose to dispatch multiple concurrent client requests to the JSP page. This is the default setting. If using true, you must ensure that you properly synchronize access to any shared objects defined at the page level. This includes objects created within declarations, JavaBeans components with page scope, and attributes of the page scope object.

If isThreadSafe is set to false, requests are dispatched one at a time, in the order they were received, and access to page-level objects does not have to be controlled. However, you still must ensure that access to attributes of the application or session scope objects and to JavaBeans components with application or session scope is properly synchronized.

JSP Scripting Elements

JSP scripting elements are used to create and access objects, define methods, and manage the flow of control. Since one of the goals of JSP technology is to separate static template data from the code needed to dynamically generate content, very sparing use of JSP

Page 78: 241254 Web Technology Lab Manual

scripting is recommended. Much of the work that requires the use of scripts can be eliminated by using custom tags, described in Extending the JSP Language.

JSP technology allows a container to support any scripting language that can call Java objects. If you wish to use a scripting language other than the default, java, you must specify it in a page directive at the beginning of a JSP page:

<%@ page language="scripting language" %> Since scripting elements are converted to programming language statements in the JSP page's servlet class, you must import any classes and packages used by a JSP page. If the page language is java, you import a class or package with the page directive:

<%@ page import="packagename.*, fully_qualified_classname" %> For example, the bookstore example page showcart.jsp imports the classes needed to implement the shopping cart with the following directive:

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

Declarations

A JSP declaration is used to declare variables and methods in a page's scripting language. The syntax for a declaration is as follows:

<%! scripting language declaration %> When the scripting language is the Java programming language, variables and methods in JSP declarations become declarations in the JSP page's servlet class.

The bookstore example page initdestroy.jsp defines an instance variable named bookDBEJB and the initialization and finalization methods jspInit and jspDestroy discussed earlier in a declaration:

<%! private BookDBEJB bookDBEJB;

public void jspInit() { ... } public void jspDestroy() { ... }%> Scriptlets

A JSP scriptlet is used to contain any code fragment that is valid for the scripting language used in a page. The syntax for a scriptlet is as follows:

<% scripting language statements%> When the scripting language is set to java, a scriptlet is transformed into a Java programming language statement fragment and is inserted into the service method of the

Page 79: 241254 Web Technology Lab Manual

JSP page's servlet. A programming language variable created within a scriptlet is accessible from anywhere within the JSP page.

The JSP page showcart.jsp contains a scriptlet that retrieves an iterator from the collection of items maintained by a shopping cart and sets up a construct to loop through all the items in the cart. Inside the loop, the JSP page extracts properties of the book objects and formats them using HTML markup. Since the while loop opens a block, the HTML markup is followed by a scriptlet that closes the block.

<% Iterator i = cart.getItems().iterator(); while (i.hasNext()) { ShoppingCartItem item = (ShoppingCartItem)i.next(); BookDetails bd = (BookDetails)item.getItem();%> <tr> <td align="right" bgcolor="#ffffff"> <%=item.getQuantity()%> </td> <td bgcolor="#ffffaa"> <strong><a href=" <%=request.getContextPath()%>/bookdetails?bookId= <%=bd.getBookId()%>"><%=bd.getTitle()%></a></strong> </td> ...<% // End of while }%> The output appears in Figure 11-2.

Expressions

A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client. When the scripting language is the Java programming language, an expression is transformed into a statement that converts the value of the expression into a String object and inserts it into the implicit out object.

The syntax for an expression is as follows:

<%= scripting language expression %> Note that a semicolon is not allowed within a JSP expression, even if the same expression has a semicolon when you use it within a scriptlet.

The following scriptlet retrieves the number of items in a shopping cart:

<% // Print a summary of the shopping cart int num = cart.getNumberOfItems();

Page 80: 241254 Web Technology Lab Manual

if (num > 0) {%>

EX.NO:4

Date :

STUDENT INFORMATION SYTEM USING JSP AND SERVLET

AIM:To develop the student webpage information using java servlet and JDBC.

ALGORITHM :

start the programcreate main HTML page for student database maintenance select option to do the following operation insertion, search ,delete and modify or update the student recode

Page 81: 241254 Web Technology Lab Manual

Main.Html

<html><body bgcolor=yellow text=red><div align=center><label><h2>Student database maintenance</h2> </label><TABLE><TR><TD><a href="http://localhost:7001/student/register.html">REGISTER</a></TD></TR><TR><TD><a href="http://localhost:7001/student/find3">SEARCH</a></TD></TR><TR><TD><a href="http://localhost:7001/student/viewall">VIEW ALL </a></TD></TR><TR><TD><a href="http://localhost:7001/student/delete2.html">DELETE</a></TD></TR><!--<TR><TD><a href="http://localhost:7001/student/update">UPDATE</a></TD></TR>--></table></div></body></html>

Register.HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><TITLE> registration </TITLE></HEAD><BODY bgcolor=teak text=red><form action="http://localhost:7001/student/register1" method=post><pre>Enter Id : <input type=text name="id" size=4 ><br>Enter Name : <input type=text name="name" size=20 ><br>Enter Age : <input type=text name="age" size=4 ><br>Enter Branch: <input type=text name="branch" size=10 ><br>Enter Mark1 : <input type=text name="m1" size=4 ><br>Enter Mark2 : <input type=text name="m2" size=4 ><br>Enter Mark3 : <input type=text name="m3" size=4 ><br>Enter Grade : <input type=text name="grade" size=20 ><br>Click : <input type="submit" name="submit" value=register></pre></form></BODY></HTML>

Page 82: 241254 Web Technology Lab Manual

Insert.Html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><TITLE> registration </TITLE></HEAD><BODY bgcolor=teak text=red><form action="http://localhost:7001/student/insert" method=post><pre><div align=center>Enter Id : <input type=text name="id" size=4 ><br>Enter Name : <input type=text name="name" size=20 ><br>Enter Age : <input type=text name="age" size=4 ><br>Enter Branch: <input type=text name="branch" size=10 ><br>Enter Mark1 : <input type=text name="m1" size=4 ><br>Enter Mark2 : <input type=text name="m2" size=4 ><br>Enter Mark3 : <input type=text name="m3" size=4 ><br>Enter Grade : <input type=text name="grade" size=4 ><br><input type="submit" name="submit" value=register></div></pre></form></BODY></HTML>

Delete.Html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><TITLE> DELETE STUDENT RECORD </TITLE></HEAD><BODY bgcolor=yellow text=cyan><form action="http://localhost:7001/student/delete2" method=post><pre>Enter the ID :<input type=text name="idno" size=4 ><br>Click :<input type="submit" name=submit value=delete></pre></form></BODY></HTML>

Page 83: 241254 Web Technology Lab Manual

Second.java

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.sql.*;import java.lang.*;public class second extends HttpServlet{

public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException

{loginform(res,false);

}//goGet()private void loginform(HttpServletResponse res,boolean error)throws ServletException,IOException

{res.setContentType("text/html");PrintWriter pr=res.getWriter();

pr.println("<html><body bgcolor=blue text=red>");pr.println("<div align=center>");if(error){

pr.println("<H2>LOGIN FAILED, PLEASE TRY AGAIN!!!</H2>");

}pr.println("<form method=post NAME=FORM>");pr.println("<table><TR><TD><label> please enter your name and

password</label></TR></TD>");pr.println("<TR><TD>Username:<input type=text name=username> ");pr.println("<TR><TD>Password:<input type=password

name=password><br></TR></TD><hr width=100%></TR></TD>");pr.println("<TR><TD>Press:<input type=submit name=submit

value=Continue></TR></TD>");pr.println("<TR><TD>clear:<input type=reset name =reset

value=Clear></TR></TD></TABLE>");pr.println("</form></div></body></html>");

}//loginform()public void doPost(HttpServletRequest req,HttpServletResponse res)throws

ServletException,IOException{String name=req.getParameter("username");String pass=req.getParameter("password");if(logindb(name,pass))

{RequestDispatcher rd=req.getRequestDispatcher("/main.html");rd.forward(req,res);}

else{

Page 84: 241254 Web Technology Lab Manual

loginform(res,true);}

}//doPost()

boolean logindb(String name, String pass){

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection

con=DriverManager.getConnection("jdbc:odbc:logindb");Statement s=con.createStatement();String sql="select * from stu where username= '" + name + "' AND

password= '" + pass + "' ";ResultSet rs=s.executeQuery(sql);if(rs.next()){

return true;}con.close();

}catch(SQLException s){

s.printStackTrace();}catch(Exception e){

e.printStackTrace();}return false;

}//login()};

Page 85: 241254 Web Technology Lab Manual

Register1.java

/* INSERTING THE DATA */import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.sql.*;import java.lang.*;public class register1 extends HttpServlet{

public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

{try{

res.setContentType("Text/html");PrintWriter pr=res.getWriter();int id=Integer.parseInt(req.getParameter("id"));String name=req.getParameter("name");int age=Integer.parseInt(req.getParameter("age"));String branch=req.getParameter("branch");int m1=Integer.parseInt(req.getParameter("m1"));int m2=Integer.parseInt(req.getParameter("m2"));int m3=Integer.parseInt(req.getParameter("m3"));String grade=req.getParameter("grade");pr.println("<html><body bgcolor=yellow text=red><div

align=center>");Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con=DriverManager.getConnection("jdbc:odbc:ss");//pr.println("student information are successfully registered");//pr.println("<a href=http://localhost:7001/student/main.html>goto main

page</a>");PreparedStatement pst=con.prepareStatement("Insert into studata

values(?,?,?,?,?,?,?,?) ");pst.setInt(1,id);pst.setString(2,name);pst.setInt(3,age);pst.setString(4,branch);pst.setInt(5,m1);pst.setInt(6,m2);pst.setInt(7,m3);pst.setString(8,grade);pst.executeQuery();

pr.println("student information are successfully registered");pr.println("<a href=http://localhost:7001/student/main.html>goto main

page</a>");pr.println("</html></body>");con.commit();

Page 86: 241254 Web Technology Lab Manual

}catch(SQLException e)

{System.out.println(e.getMessage());

}catch(Exception e)

{e.printStackTrace();

}}

};

Page 87: 241254 Web Technology Lab Manual

Insert.java

import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.sql.*;import java.lang.*;public class register extends HttpServlet{

public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

{try{

res.setContentType("Text/html");PrintWriter pr=res.getWriter();int id=Integer.parseInt(req.getParameter("id"));String name=req.getParameter("name");int age=Integer.parseInt(req.getParameter("age"));String branch=req.getParameter("branch");int m1=Integer.parseInt(req.getParameter("m1"));int m2=Integer.parseInt(req.getParameter("m2"));int m3=Integer.parseInt(req.getParameter("m3"));String grade=req.getParameter("grade");

pr.println("<html><body bgcolor=yellow text=red><div align=center>");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con=DriverManager.getConnection("jdbc:odbc:ss");

// pr.println("Get connection");PreparedStatement pst=con.prepareStatement("Insert into studata

values(?,?,?,?,?,?,?,?) ");pst.setInt(1,id);pst.setString(2,name);pst.setInt(3,age);pst.setString(4,branch);pst.setInt(5,m1);pst.setInt(6,m2);pst.setInt(7,m3);pst.setString(8,grade);pst.executeQuery();con.commit();pr.println("student information are successfully registered");pr.println("<a href=http://localhost:7001/student/main.html>goto main

page</a>");pr.println("</html></body>");

con.close();}catch(SQLException e)

Page 88: 241254 Web Technology Lab Manual

{System.out.println(e.getMessage());

}catch(Exception e)

{e.printStackTrace();

}}

};

Find3.Java

/* SEARCH THE PARTICULAR RECORD */import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.sql.*;import java.lang.*;public class find3 extends HttpServlet{public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

{res.setContentType("Text/html");PrintWriter pr=res.getWriter();pr.println("<html><body bgcolor=black text=green><div align=center>");pr.println("<form action=http://localhost:7001/student/find3 method=post

name=form1>");pr.println("<h4>Enter the student ID:</h4><input type=text name=id >");pr.println("<h4>click:</h4><input type=submit name=submit value=search>");pr.println("</form></div></body></html>");}public void doPost(HttpServletRequest req,HttpServletResponse res)throws

ServletException, IOException{try{

res.setContentType("Text/html");PrintWriter pr=res.getWriter();String id =req.getParameter("id");int idno=Integer.parseInt(id);pr.println("<html><body bgcolor=black text=green><div align=center>");Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con=DriverManager.getConnection("jdbc:odbc:ss");

//PreparedStatement pst=con.prepareStatement("select * from studata where ID= '" + idno + "' ");PreparedStatement pst=con.prepareStatement("select * from studata where ID= ? ");

pst.setInt(1,idno);ResultSet r=pst.executeQuery();

while(r.next())

Page 89: 241254 Web Technology Lab Manual

{pr.println(r.getInt(1)+"\t"+r.getString(2)+"\t"+r.getInt(3)+"\

t"+r.getString(4)+"\t"+r.getInt(5)+"\t"+r.getInt(6)+"\t"+r.getInt(7)+"\t"+r.getString(8));pr.println("<br>");}

pr.println("<a href=http://localhost:7001/student/main.html>goto main page</a>");pr.println("</html></body>");

}catch(SQLException e)

{System.out.println(e.getMessage());

} catch(Exception e)

{e.printStackTrace();

}}

};

Page 90: 241254 Web Technology Lab Manual

Delete2.javaimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.util.*;import java.sql.*;import java.lang.*;public class delete2 extends HttpServlet{

public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException, IOException

{try{res.setContentType("Text/html");PrintWriter pr=res.getWriter();pr.println("<html><body bgcolor=black text=yellow>");String idno=req.getParameter("idno");int id=Integer.parseInt(idno);Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con=DriverManager.getConnection("jdbc:odbc:ss");pr.println("get connected");//PreparedStatement pst=con.prepareStatement("Delete from studata where ID= '"

+ id + "' ");PreparedStatement pst=con.prepareStatement("Delete from studata where ID= ?

");pst.setInt(1,id);pst.executeUpdate();pr.println("<h2>student record is successfully deleted");pr.println("<a href=http://localhost:7001/student/main.html>goto main

page</a>");pr.println("</html></body>");

con.commit();}catch(SQLException e)

{System.out.println(e.getMessage());

}catch(Exception e){

e.printStackTrace();}

}};

Page 91: 241254 Web Technology Lab Manual

Output:

Studenttable.

Page 92: 241254 Web Technology Lab Manual
Page 93: 241254 Web Technology Lab Manual

RESULT :

Thus student information java script program is successfully completed.

Page 94: 241254 Web Technology Lab Manual

INTRODUCTION TO HTTP SERVLETS

The rise of server-side Java applications is one of the latest and most exciting trends in Java programming. The Java language was originally intended for use in small, embedded devices. It was first hyped as a language for developing elaborate client-side web content in the form of applets. Until recently, Java's potential as a server-side development platform had been sadly overlooked. Now, Java is coming into its own as a language ideally suited for server-side development.

Businesses in particular have been quick to recognize Java's potential on the server--Java is inherently suited for large client/server applications. The cross-platform nature of Java is extremely useful for organizations that have a heterogeneous collection of servers running various flavors of the Unix and Windows operating systems. Java's modern, object-oriented, memory-protected design allows developers to cut development cycles and increase reliability. In addition, Java's built-in support for networking and enterprise APIs provides access to legacy data, easing the transition from older client/server systems.

Java servlets are a key component of server-side Java development. A servlet is a small, pluggable extension to a server that enhances the server's functionality. Servlets allow developers to extend and customize any Java-enabled server--a web server, a mail server, an application server, or any custom server--with a hitherto unknown degree of portability, flexibility, and ease. But before we go into any more detail, let's put things into perspective.

History of Web Applications

While servlets can be used to extend the functionality of any Java-enabled server, today they are most often used to extend web servers, providing a powerful, efficient replacement for CGI scripts. When you use a servlet to create dynamic content for a web page or otherwise extend the functionality of a web server, you are in effect creating a web application. While a web page merely displays static content and lets the user navigate through that content, a web application provides a more interactive experience. A web application can be as simple as a keyword search on a document archive or as complex as an electronic storefront. Web applications are being deployed on the Internet and on corporate intranets and extranets, where they have the potential to increase productivity and change the way that companies, large and small, do business. To understand the power of servlets, we need to step back and look at some of the other approaches that can be used to create web applications.

Common Gateway Interface

The Common Gateway Interface, normally referred to as CGI, was one of the first practical techniques for creating dynamic content. With CGI, a web server passes certain requests to an external program. The output of this program is then sent to the client in place of a static file. The advent of CGI made it possible to implement all sorts of new functionality in web pages, and CGI quickly became a de facto standard, implemented on dozens of web servers.

Page 95: 241254 Web Technology Lab Manual

It's interesting to note that the ability of CGI programs to create dynamic web pages is a side effect of its intended purpose: to define a standard method for an information server to talk with external applications. This origin explains why CGI has perhaps the worst life cycle imaginable. When a server receives a request that accesses a CGI program, it must create a new process to run the CGI program and then pass to it, via environment variables and standard input, every bit of information that might be necessary to generate a response. Creating a process for every such request requires time and significant server resources, which limits the number of requests a server can handle concurrently. Figure 1-1 shows the CGI life cycle.

Figure 1- The CGI life cycle

Even though a CGI program can be written in almost any language, the Perl programming language has become the predominant choice. Its advanced text-processing capabilities are a big help in managing the details of the CGI interface. Writing a CGI script in Perl gives it a semblance of platform independence, but it also requires that each request start a separate Perl interpreter, which takes even more time and requires extra resources.

Another often-overlooked problem with CGI is that a CGI program cannot interact with the web server or take advantage of the server's abilities once it begins execution because it is running in a separate process. For example, a CGI script cannot write to the server's log file.

Java Servlets

Enter Java servlets. As was said earlier, a servlet is a generic server extension--a Java class that can be loaded dynamically to expand the functionality of a server. Servlets are commonly used with web servers, where they can take the place of CGI scripts. A servlet is similar to a proprietary server extension, except that it runs inside a Java Virtual Machine (JVM) on the server (see Figure 1-4), so it is safe and portable. Servlets operate solely within the domain of the server: unlike applets, they do not require support for Java in the web browser.

Page 96: 241254 Web Technology Lab Manual

Figure 2 The servlet life cycle

Unlike CGI and FastCGI, which use multiple processes to handle separate programs and/or separate requests, servlets are all handled by separate threads within the web server process. This means that servlets are also efficient and scalable. Because servlets run within the web server, they can interact very closely with the server to do things that are not possible with CGI scripts.

Another advantage of servlets is that they are portable: both across operating systems as we are used to with Java and also across web servers. As you'll see shortly, all of the major web servers support servlets. We believe that Java servlets offer the best possible platform for web application development.

Although servlets are most commonly used as a replacement for CGI scripts on a web server, they can extend any sort of server. Imagine, for example, a Java-based FTP server that handles each command with a separate servlet. New commands can be added by simply plugging in new servlets. Or, imagine a mail server that allows servlets to extend its functionality, perhaps by performing a virus scan on all attached documents or handling mail filtering tasks.

Support for Servlets

Like Java itself, servlets were designed for portability. Servlets are supported on all platforms that support Java, and servlets work with all the major web servers. Java servlets, as defined by the Java Software division of Sun Microsystems (formerly known as JavaSoft), are the first standard extension to Java. This means that servlets are officially blessed by Sun and are part of the Java language, but they are not part of the core Java API. Therefore, although they may work with any Java Virtual Machine (JVM), servlet classes need not be bundled with all JVMs.

. Note that several web server vendors have their own server-side Java implementations, some of which have also been given the name "servlets". These are generally incompatible with Java servlets as defined by Sun. Most of these vendors are converting their Java support to standard servlets, or are introducing standard servlet support in parallel, to allow backward compatibility.

To make it easy for you to develop servlets, Sun has made publicly available a set of classes that provide basic servlet support. The javax.servlet and javax.servlet.http packages constitute this Servlet API. Version 2.0 of these classes comes bundled with the Java Servlet Development Kit (JSDK) for use with the Java Development Kit version 1.1 and above.

Page 97: 241254 Web Technology Lab Manual

At one point it was planned the contents of the JSDK would come bundled as part of JDK 1.2. However, it was later decided to keep the servlet classes separate from the JDK, to better allow for timely revisions and corrections to the JSDK.

Many web server vendors have incorporated these classes into their servers to provide servlet support, and several have also provided additional functionality. Sun's Java Web Server, for instance, includes a proprietary interface to the server's security features.

It doesn't much matter where you get the servlet classes, as long as you have them on your system, since you need them to compile your servlets. In addition to the servlet classes, you need a servlet engine, so that you can test and deploy your servlets. Your choice of servlet engine depends in part on the web server(s) you are running. There are three flavors of servlet engines: standalone, add-on, and embeddable.

Standalone Servlet Engines

A standalone engine is a server that includes built-in support for servlets. Such an engine has the advantage that everything works right out of the box. One disadvantage, however, is that you have to wait for a new release of the web server to get the latest servlet support. Because servlets are still fairly new, this sort of server is still a bit of a rarity. As the various vendors upgrade their web servers, we expect that many of the servers will provide built-in support for servlets.

Standalone engines in web servers include the following:

Sun's Java Web Server (formerly called "Jeeves"), unofficially considered the reference implementation for how a servlet engine should support servlets. Written entirely in Java (except for two native code libraries that enhance its functionality but are not needed).

Add-on Servlet Engines

An add-on servlet engine functions as a plug-in to an existing server--it adds servlet support to a server that was not originally designed with servlets in mind. Add-on servlet engines have been written for many servers including Apache, Netscape's FastTrack Server and Enterprise Server, Microsoft's Internet Information Server and Personal Web Server, O'Reilly's WebSite, Lotus Domino's Go Webserver, StarNine's WebSTAR, and Apple's AppleShare IP. This type of engine acts as a stopgap solution until a future server release incorporates servlet support. A plug-in also can be used with a server that provides a poor or outdated servlet implementation.

Add-on servlet engines include these:

The Java-Apache project's JServ module is a freely available servlet engine that adds servlet support to the extremely popular Apache server. Live Software's JRun, a freely available plug-in designed to support the full Servlet API on all the popular web servers on all the popular operating systems. The latest version even features a basic web server for development purposes.

Page 98: 241254 Web Technology Lab Manual

Embeddable Servlet Engines

An embeddable engine is generally a lightweight servlet deployment platform that can be embedded in another application. That application becomes the true server.

Embeddable servlet engines include the following:

Sun's JavaServer Engine, a high-quality, high-end framework for designing and building Java servers. Sun's Java Web Server and IBM's WebSphere Application Server were built using the Java Server Engine.

The Power of Servlets

So far, we have portrayed servlets as an alternative to other dynamic web content technologies, but we haven't really explained why we think you should use them. What makes servlets a viable choice for web development? We believe that servlets offer a number of advantages over other approaches, including: portability, power, efficiency, endurance, safety, elegance, integration, extensibility, and flexibility. Let's examine each in turn.

Portability

Because servlets are written in Java and conform to a well-defined and widely accepted API, they are highly portable across operating systems and across server implementations. You can develop a servlet on a Windows NT machine running the Java Web Server and later deploy it effortlessly on a high-end Unix server running Apache. With servlets, you can truly "write once, serve everywhere."

Servlet portability is not the stumbling block it so often is with applets, for two reasons. First, servlet portability is not mandatory. Unlike applets, which have to be tested on all possible client platforms, servlets have to work only on the server machines that you are using for development and deployment. Unless you are in the business of selling your servlets, you don't have to worry about complete portability. Second, servlets avoid the most error-prone and inconsistently implemented portion of the Java language: the Abstract Windowing Toolkit (AWT) that forms the basis of Java graphical user interfaces.

Power

Servlets can harness the full power of the core Java APIs: networking and URL access, multithreading, image manipulation, data compression, database connectivity, internationalization, remote method invocation (RMI), CORBA connectivity, and object serialization, among others. If you want to write a web application that allows employees to query a corporate legacy database, you can take advantage of all of the Java Enterprise APIs in doing so. Or, if you need to create a web-based directory lookup application, you can make use of the JNDI API.

As a servlet author, you can also pick and choose from a plethora of third-party Java classes and JavaBeans components. In the future, you'll even be able to use newly introduced Enterprise JavaBeans components. Today, servlets can use third-party code to handle tasks such as regular expression searching, data charting, advanced database access, and advanced networking.

Page 99: 241254 Web Technology Lab Manual

Servlets are also well suited for enabling client/server communication. With a Java-based applet and a Java-based servlet, you can use RMI and object serialization to handle client/server communication, which means that you can leverage the same custom code on the client as on the server. Using CGI for the same purpose is much more complicated, as you have to develop your own custom protocol to handle the communication.

Efficiency and Endurance

Servlet invocation is highly efficient. Once a servlet is loaded, it generally remains in the server's memory as a single object instance. Thereafter, the server invokes the servlet to handle a request using a simple, lightweight method invocation. Unlike with CGI, there's no process to spawn or interpreter to invoke, so the servlet can begin handling the request almost immediately. Multiple, concurrent requests are handled by separate threads, so servlets are highly scalable. Servlets, in general, are naturally enduring objects. Because a servlet stays in the server's memory as a single object instance, it automatically maintains its state and can hold on to external resources, such as database connections, that may otherwise take several seconds to establish.

Safety

Servlets support safe programming practices on a number of levels. Because they are written in Java, servlets inherit the strong type safety of the Java language. In addition, the Servlet API is implemented to be type-safe. While most values in a CGI program, including a numeric item like a server port number, are treated as strings, values are manipulated by the Servlet API using their native types, so a server port number is represented as an integer. Java's automatic garbage collection and lack of pointers mean that servlets are generally safe from memory management problems like dangling pointers, invalid pointer references, and memory leaks.

Servlets can handle errors safely, due to Java's exception-handling mechanism. If a servlet divides by zero or performs some other illegal operation, it throws an exception that can be safely caught and handled by the server, which can politely log the error and apologize to the user. If a C++-based server extension were to make the same mistake, it could potentially crash the server.

A server can further protect itself from servlets through the use of a Java security manager. A server can execute its servlets under the watch of a strict security manager that, for example, enforces a security policy designed to prevent a malicious or poorly written servlet from damaging the server file system.

Elegance

The elegance of servlet code is striking. Servlet code is clean, object oriented, modular, and amazingly simple. One reason for this simplicity is the Servlet API itself, which includes methods and classes to handle many of the routine chores of servlet development. Even advanced operations, like cookie handling and session tracking, are abstracted into convenient classes. A few more advanced but still common tasks were left out of the API, and, in those places, we have tried to step in and provide a set of helpful classes in the com.oreilly.servlet package.

Page 100: 241254 Web Technology Lab Manual

Integration

Servlets are tightly integrated with the server. This integration allows a servlet to cooperate with the server in ways that a CGI program cannot. For example, a servlet can use the server to translate file paths, perform logging, check authorization, perform MIME type mapping, and, in some cases, even add users to the server's user database. Server-specific extensions can do much of this, but the process is usually much more complex and error-prone.

Extensibility and Flexibility

The Servlet API is designed to be easily extensible. As it stands today, the API includes classes that are optimized for HTTP servlets. But at a later date, it could be extended and optimized for another type of servlets, either by Sun or by a third party. It is also possible that its support for HTTP servlets could be further enhanced.

Servlets are also quite flexible. As you'll see in the next chapter, an HTTP servlet can be used to generate a complete web page; it can be added to a static page using a <SERVLET> tag in what's known as a server-side include; and it can be used in cooperation with any number of other servlets to filter content in something called a servlet chain. In addition, just before this book went to press, Sun introduced JavaServer Pages, which offer a way to write snippets of servlet code directly within a static HTML page, using a syntax that is curiously similar to Microsoft's Active Server Pages (ASP). Who knows what they (or you) will come up with next.

HTTP Servlet Basics:

Requests, Responses, and Headers

HTTP is a simple, stateless protocol. A client, such as a web browser, makes a request, the web server responds, and the transaction is done. When the client sends a request, the first thing it specifies is an HTTP command, called a method , that tells the server the type of action it wants performed. This first line of the request also specifies the address of a document (a URL) and the version of the HTTP protocol it is using. For example: GET /intro.html HTTP/1.0

This request uses the GET method to ask for the document named intro.html, using HTTP Version 1.0. After sending the request, the client can send optional header information to tell the server extra information about the request, such as what software the client is running and what content types it understands. This information doesn't directly pertain to what was requested, but it could be used by the server in generating its response. Here are some sample request headers:

User-Agent: Mozilla/4.0 (compatible; MSIE 4.0; Windows 95)Accept: image/gif, image/jpeg, text/*, */*The User-Agent header provides information about the client software, while the

Accept header specifies the media (MIME) types that the client prefers to accept. (We'll talk more about request headers in the context of servlets in Chapter 4, "Retrieving Information".) After the headers, the client sends a blank line, to indicate the end of the header section. The client can also send additional data, if appropriate for the method being used, as it is with the POST method that we'll discuss shortly. If the request doesn't send any data, it ends with an empty line.

Page 101: 241254 Web Technology Lab Manual

After the client sends the request, the server processes it and sends back a response. The first line of the response is a status line that specifies the version of the HTTP protocol the server is using, a status code, and a description of the status code. For example:

HTTP/1.0 200 OKThis status line includes a status code of 200, which indicates that the request was successful, hence the description "OK". Another common status code is 404, with the description "Not Found"--as you can guess, this means that the requested document was not found.

After the status line, the server sends response headers that tell the client things like what software the server is running and the content type of the server's response. For example: Date: Saturday, 23-May-98 03:25:12 GMTServer: JavaWebServer/1.1.1MIME-version: 1.0Content-type: text/htmlContent-length: 1029Last-modified: Thursday, 7-May-98 12:15:35 GMT

The Server header provides information about the server software, while the Content-type header specifies the MIME type of the data included with the response. The server sends a blank line after the headers, to conclude the header section. If the request was successful, the requested data is then sent as part of the response. Otherwise, the response may contain human-readable data that explains why the server couldn't fulfill the request.

GET and POST

When a client connects to a server and makes an HTTP request, the request can be of several different types, called methods. The most frequently used methods are GET and POST. Put simply, the GET method is designed for getting information (a document, a chart, or the results from a database query), while the POST method is designed for posting information (a credit card number, some new chart data, or information that is to be stored in a database). To use a bulletin board analogy, GET is for reading and POST is for tacking up new material.

The GET method, although it's designed for reading information, can include as part of the request some of its own information that better describes what to get--such as an x, y scale for a dynamically created chart. This information is passed as a sequence of characters appended to the request URL in what's called a query string. Placing the extra information in the URL in this way allows the page to be bookmarked or emailed like any other. Because GET requests theoretically shouldn't need to send large amounts of information, some servers limit the length of URLs and query strings to about 240 characters.

The POST method uses a different technique to send information to the server because in some cases it may need to send megabytes of information. A POST request passes all its data, of unlimited length, directly over the socket connection as part of its HTTP request body. The exchange is invisible to the client. The URL doesn't change at all. Consequently, POST requests cannot be bookmarked or emailed or, in some cases,

Page 102: 241254 Web Technology Lab Manual

even reloaded. That's by design--information sent to the server, such as your credit card number, should be sent only once.

In practice, the use of GET and POST has strayed from the original intent. It's common for long parameterized requests for information to use POST instead of GET to work around problems with overly-long URLs. It's also common for simple forms that upload information to use GET because, well--why not, it works! Generally, this isn't much of a problem. Just remember that GET requests, because they can be bookmarked so easily, should not be allowed to cause damage for which the client could be held responsible. In other words, GET requests should not be used to place an order, update a database, or take an explicit client action in any way.

The Servlet API

Now that you have a basic understanding of HTTP, we can move on and talk about the Servlet API that you'll be using to create HTTP servlets, or any kind of servlets, for that matter. Servlets use classes and interfaces from two packages: javax.servlet and javax.servlet.http . The javax.servlet package contains classes to support generic, protocol-independent servlets. These classes are extended by the classes in the javax.servlet.http package to add HTTP-specific functionality. The top-level package name is javax instead of the familiar java, to indicate that the Servlet API is a standard extension.

Every servlet must implement the javax.servlet.Servlet interface. Most servlets implement it by extending one of two special classes: javax. servlet.GenericServlet or javax.servlet.http.HttpServlet . A protocol-independent servlet should subclass GenericServlet, while an HTTP servlet should subclass HttpServlet, which is itself a subclass of GenericServlet with added HTTP-specific functionality.

Unlike a regular Java program, and just like an applet, a servlet does not have a main() method. Instead, certain methods of a servlet are invoked by the server in the process of handling requests. Each time the server dispatches a request to a servlet, it invokes the servlet's service() method.

A generic servlet should override its service() method to handle requests as appropriate for the servlet. The service() method accepts two parameters: a request object and a response object. The request object tells the servlet about the request, while the response object is used to return a response. Figure 2-1 shows how a generic servlet handles requests.

Figure 2-1. A generic servlet handling a request

Page 103: 241254 Web Technology Lab Manual

In contrast, an HTTP servlet usually does not override the service() method. Instead, it overrides doGet() to handle GET requests and doPost() to handle POST requests. An HTTP servlet can override either or both of these methods, depending on the type of requests it needs to handle. The service() method of HttpServlet handles the setup and dispatching to all the doXXX() methods, which is why it usually should not be overridden. Figure 2-2 shows how an HTTP servlet handles GET and POST requests.

Figure 3 An HTTP servlet handling GET and POST requests

An HTTP servlet can override the doPut() and doDelete() methods to handle PUT and DELETE requests, respectively. However, HTTP servlets generally don't touch doHead(), doTrace(), or doOptions() . For these, the default implementations are almost always sufficient.

The remainder in the javax.servlet and javax.servlet.http packages are largely support classes. For example, the ServletRequest and ServletResponse classes in javax.servlet provide access to generic server requests and responses, while HttpServletRequest and HttpServletResponse in javax.servlet.http provide access to HTTP requests and responses. The javax.servlet.http package also contains an HttpSession class that provides built-in session tracking functionality and a Cookie class that allows you to quickly set up and process HTTP cookies.

Page 104: 241254 Web Technology Lab Manual

EX.No:5

Date :

SERVLET PROGRAM USING HTTP SERVLET

AIM:

To create a servlet program and check the script validation.

ALGORITHM:

Step 1:Start the program.

Step 2:Get the context text at Servlet at text html.

Step 3:Get the response from the user by entering the username field.

Step 4: Get the response from the user by entering the password field.

Step 5:If the username and password are correct, then the user is authenticated

and can enter into web page.

Step 6:Execute the program in Internet Explorer.

Stepe 7:Stop the program.

Page 105: 241254 Web Technology Lab Manual

PROGRAM

HTML Code :

<HTMl>

<HEAD><CENTER> </CENTER></HEAD>

<CENTER>

<body bgcolor="green">

<form action="http://localhost:7001/parthi_servlet/servlet1" method="get">

<h1>USERNAME AND PASSWORD></h1>

<TABLE >

<TR>

<TD>USERNAME<INPUT TYPE="TEXT" name="username"></TD></TR>

<TR>

<TD> PASSWORD<INPUT TYPE="password" name="password"></TD></TR>

<TR>

<TD> <INPUT TYPE="submit" VALUE="SUBMIT" NAME=SUB></TD>

<TD> <INPUT TYPE="reset" VALUE="CLEAR" NAME=CLA></TD>

</TR>

</TABLE></CENTER>

</form>

</body>

</HTML>

Page 106: 241254 Web Technology Lab Manual

Java Servlet Code :

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class servlet1 extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res)throws

ServletException,IOException

{

res.setContentType("text/html");

PrintWriter pw=res.getWriter();

String admin=req.getParameter("username");

String pass=req.getParameter("password");

pw.println(admin);

pw.println(pass);

if((admin.equals("admin2010")) && (pass.equals("abc123")))

{

pw.println("Authorized user");

}

else

{

pw.println("not an Authorized user");

}

}

}

Page 107: 241254 Web Technology Lab Manual

Sample output:

RESULT:

Thus the servlet program has been created and validated successfully.

Page 108: 241254 Web Technology Lab Manual

JDBC - Java Database Connectivity

JDBC Driver Manager

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple.

This is a very important class. Its main purpose is to provide a means of managing the different types of JDBC database driver. On running an application, it is the DriverManager's responsibility to load all the drivers found in the system property jdbc. drivers. For example, this is where the driver for the Oracle database may be defined. This is not to say that a new driver cannot be explicitly stated in a program at runtime which is not included in jdbc.drivers. When opening a connection to a database it is the DriverManager' s role to choose the most appropriate driver from the previously loaded drivers.

The JDBC API defines the Java interfaces and classes that programmers use to connect to databases and send queries. A JDBC driver implements these interfaces and classes for a particular DBMS vendor.

A Java program that uses the JDBC API loads the specified driver for a particular DBMS before it actually connects to a database. The JDBC DriverManager class then sends all JDBC API calls to the loaded driver.

JDBC Driver

This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for some applications than others.

Types of JDBC drivers

This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for some applications than others. There are four types of JDBC drivers known as:                       

JDBC-ODBC bridge plus ODBC driver, also called Type 1.

Native-API, partly Java driver, also called Type 2.

JDBC-Net, pure Java driver, also called Type 3.

Native-protocol, pure Java driver, also called Type 4.

Type 1 Driver- the JDBC-ODBC bridge

Page 109: 241254 Web Technology Lab Manual

The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database.

The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition. The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. Also, using this driver has got other dependencies such as ODBC must be installed on the computer having the driver and the database which is being connected to must support an ODBC driver. Hence the use of this driver is discouraged if the alternative of a pure-Java driver is available.

Type 1 is the simplest of all but platform specific i.e only to Microsoft platform. A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers.

Note that some ODBC native code and in many  cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of  driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see JDBC-ODBC Bridge Driver.

Type 1 drivers are "bridge" drivers. They use another technology such as Open Database Connectivity (ODBC) to communicate  with a database. This is an advantage because ODBC drivers exist for many Relational Database Management System (RDBMS) platforms. The Java Native Interface (JNI) is used to call ODBC functions from the JDBC driver.

A Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it. This can be a serious drawback for a production application. Type 1 drivers cannot be used in an applet since applets cannot load native code.

Functions:  Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver. Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source.Client -> JDBC Driver -> ODBC Driver -> DatabaseThere is some overhead associated with the translation work to go from JDBC to ODBC. Advantages:

Almost any database for which ODBC driver is installed, can be accessed.

Disadvantages: Performance overhead since the calls have to go through the JDBC overhead

bridge to the ODBC driver, then to the native database connectivity interface. The ODBC driver needs to be installed on the client machine. Considering the client-side software needed, this might not be suitable for applets.

Type 2 Driver - the Native-API DriverThe JDBC type 2 driver, also known as the Native-API driver is a database driver

implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API.

Page 110: 241254 Web Technology Lab Manual

The type 2 driver is not written entirely in Java as it interfaces with non-Java code that makes the final database calls. The driver is compiled for use with the particular operating system. For platform interoperability, the Type 4 driver, beinga full-Java implementation, is preferred over this driver.

A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

However the type 2 driver provides more functionality and performance than the type 1 driver as it does not have the overhead of the additional ODBC function calls.

Type 2 drivers use a native API to communicate with a database system. Java native methods are used to invoke the API functions that perform database operations. Type 2 drivers are generally faster than Type 1 drivers.

Type 2 drivers need native binary code installed and configured to work. A Type 2 driver also uses the JNI. You cannot use a Type 2 driver in an applet since applets cannot load native code. A Type 2 JDBC driver may require some Database Management System (DBMS) networking software to be installed. The Developer Kit for Java JDBC driver is a Type 2 JDBC driver.

Functions: This type of driver converts JDBC calls into calls to the client API for that database. Client -> JDBC Driver -> Vendor Client DB Library -> Database

Advantage Better performance than Type 1 since no jdbc to odbc translation is needed.

Disadvantages The vendor client library needs to be installed on the client machine. Cannot be used in internet due the client side software needed. Not all databases give the client side library.

Type 3 driver - the Network-Protocol DriverThe JDBC type 3 driver, also known as the network-protocol driver is a database

driver implementation which makes use of a middle-tier between the calling program and the database. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol.

This differs from the type 4 driver in that the protocol conversion logic resides not at the client, but in the middle-tier. However, like type 4 drivers, the type 3 driver is written entirely in Java.

The same driver can be used for multiple databases. It depends on the number of databases the middleware has been configured to support. The type 3 driver is platform-independent as the platform-related differences are taken care by the middleware. Also, making use of the middleware provides additional advantages of security and firewall access.

A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this

Page 111: 241254 Web Technology Lab Manual

solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to     their existing database middleware products.

These drivers use a networking protocol and middleware to communicate with a server. The server then translates the protocol to DBMS function calls specific to DBMS.

Type 3 JDBC drivers are the most flexible JDBC solution because they do not require any native binary code on the client. A Type 3 driver does not need any client installation.

Functions: Follows a three tier communication approach. Can interface to multiple databases - Not vendor specific. The JDBC Client driver written in java, communicates with a middleware-net-

server using a database independent  protocol, and then this net server translates this request into database commands for that database.

Thus the client driver to middleware communication is database independent. Client -> JDBC Driver -> Middleware-Net Server -> Any Database

Advantages Since the communication between client and the middleware server is database

independent, there is no need for the vendor db library on the client machine. Also the client to middleware needn’t be changed for a new database.

The Middleware Server (Can be a full fledged J2EE Application server) can provide typical middleware services like caching (connections, query results, and so on), load balancing, logging, auditing etc..

eg. for the above include jdbc driver features in Weblogic. Can be used in internet since there is no client side software needed. At client side a single driver can handle any database.(It works provided the

middlware supports that database!!)

Disadvantages Requires database-specific coding to be done in the middle tier. An extra layer added may result in a time-bottleneck. But typically this is

overcome by providing efficient middleware services described above.

Type 4 - the Native-Protocol DriverThe JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol.

The type 4 driver is written completely in Java and is hence platform independent. It is installed inside the Java Virtual Machine of the client. It provides better performance over the type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC or database API calls. Unlike the type 1 and 2 drivers, it does not need associated software to work.

A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the

Page 112: 241254 Web Technology Lab Manual

primary source for this style of driver. Several database vendors have these in progress. As the database protocol is vendor-specific, separate drivers, usually vendor-supplied, need to be used to connect to the database.

A Type 4 driver uses Java to implement a DBMS vendor networking protocol. Since the protocols are usually proprietary, DBMS vendors are generally the only companies providing a Type 4 JDBC driver.

Type 4 drivers are all Java drivers. This means that there is no client installation or configuration. However, a Type 4 driver may not be suitable for some applications if the underlying protocol does not handle issues such as security and network connectivity well.

The IBM Toolbox for Java JDBC driver is a Type 4 JDBC driver, indicating that the API is a pure Java networking protocol driver.

Functions Type 4 drivers are entirely written in Java that communicate directly with a

vendor's database through socket connections. No translation or middleware layers, are required, improving performance.

The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server.

Completely implemented in Java to achieve platform independence. e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver

which connect to jdbc:oracle:thin URL format. Client Machine -> Native protocol JDBC Driver -> Database server

Advantages

These drivers don't translate the requests into db request to ODBC or pass it to client api for the db, nor do they need a middleware layer for request indirection. Thus the performance is considerably improved.

Disadvantage

At client side, a separate driver is needed for each database.

The JDBC APIPreviously, we’ve assumed that you have a general working knowledge of the various Java APIs. Because even experienced Java programmers may have had relatively little experience with databases, this section provides a general introduction to JDBC. If this is your first foray into the world of databases, we strongly recommend that you take a breather and find a book on general database and JDBC

JDBC is a SQL-level API—one that allows you to execute SQL statements and retrieve the results, if any. The API itself is a set of interfaces and classes designed to perform actions against any database. Figure 9-2 shows how JDBC programs interact with databases.

Page 113: 241254 Web Technology Lab Manual

When the driver is loaded into memory, it registers itself with the java.sql. DriverManager class as an available database driver. The next step is to ask the DriverManager class to open a connection to a given database, where the database is specified by a specially formatted URL. The method used to open the connection is DriverManager.getConnection(). It returns a class that implements the java.sql.Connection interface:

Connection con = DriverManager.getConnection("jdbc:odbc:somedb", "user", "passwd");

A JDBC URL identifies an individual database in a driver-specific manner. Different drivers may need different information in the URL to specify the host database. JDBC URLs usually begin with jdbc:subprotocol:subname. For example, the Oracle JDBC-Thin driver uses a URL of the form ofjdbc:oracle:thin:@dbhost:port:sid; the JDBC-ODBC bridge uses jdbc:odbc:datasourcename; odbcoptions.

During the call to getConnection(), the DriverManager object asks each registered driver if it recognizes the URL. If a driver says yes, the driver manager uses that driver to create the Connection object. Here is a snippet of code a servlet might use to load its database driver with the JDBC-ODBC bridge and create an initial connection:

Connection con = null;try {// Load (and therefore register) the JDBC-ODBC Bridge// Might throw a ClassNotFoundExceptionClass.forName("sun.jdbc.odbc.JdbcOdbcDriver");// Get a connection to the database

Page 114: 241254 Web Technology Lab Manual

// Might throw an SQLExceptioncon = DriverManager.getConnection("jdbc:odbc:somedb", "user", "passwd");// The rest of the code goes here.}catch (ClassNotFoundException e) {// Handle an error loading the driver}catch (SQLException e) {// Handle an error getting the connection}finally {// Close the Connection to release the database resources immediately.try {if (con != null) con.close();}catch (SQLException ignored) { }}

Executing SQL Queries

To really use a database, we need to have some way to execute queries. The simplest way to execute a query is to use the java.sql.Statement class. Statement objects are never instantiated directly; instead, a program calls the createStatement() method of Connection to obtain a new Statement object:

Statement stmt = con.createStatement();

A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java.sql. ResultSet that encapsulates the retrieved data:

ResultSet rs = stmt.executeQuery("SELECT * FROM CUSTOMERS");

You can think of a ResultSet object as a representation of the query result returned one row at a time. You use the next() method of ResultSet to move from row to row. The ResultSet interface also boasts a multitude of methods designed for retrieving data from the current row. The getString() and getObject() methods are among the most frequently used for retrieving columnvalues:

while(rs.next()) {String event = rs.getString("event");Object count = (Integer) rs.getObject("count");}The ResultSet is linked to its parent Statement. Therefore, if a Statement is closed or used to execute another query, any related ResultSet objects are closed automatically.Ex.No:6

Date

IMPLEMENTATION OF JAVA DATABASE CONNECTIVITY(JDBC)

Page 115: 241254 Web Technology Lab Manual

AIM:

To connect the database using jdbc connectivity in java.

ALGORITHM:

Step 1:Start the program.

Step2 :Write the source code for connectivity.

Step 3:Using MS-Access, save the database.

Step 4:connect the database using ODBC Source connection.

Step 5: Add the database name in ODBC data source administrator.

Step 6:Add the table name to connection.

Step 7:Compile the program and execute it.

Step 8:Stop the program.

Page 116: 241254 Web Technology Lab Manual

PROGRAM

import java.sql.*;

import java.io.*;

public class jdbcdemo

{

public static void main(String args[])

{

Connection c= null;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

c=DriverManager.getConnection("jdbc:odbc:jdbcdemodb");

Statement stmt=c.createStatement();

ResultSet rs=stmt.executeQuery("select * from Employee");

System.out.println("name and password are");

while(rs.next())

{

System.out.println(rs.getString(1)+"\t"+rs.getInt(2)+"\t"+rs.getDouble(3));

}

c.close();

}

catch(SQLException e1)

{

e1.printStackTrace();

}

catch(Exception e)

{

System.out.println("error"+e.getMessage());

}

}

}

Page 117: 241254 Web Technology Lab Manual

Sample output:

RESULT:

Thus the implementation of Java Database connectivity has been executed successfully.

Page 118: 241254 Web Technology Lab Manual

Ex.No: 6b

Date :

IMPLEMENTATION OF SERVLET - JDBC DEMO PROGRAM

AIM:To create a servlet with JDBC connectivity in java.

ALGORITHM:

Step 1:Start the program.

Step 2:Get the context text at Servlet at text html.

Step 3:Get the response from the user by entering the username field.

Step 4: Get the response from the user by entering the password field.

Step 5:If the username and password are correct, then the user is authenticated

and can enter into web page.

Step 6:Execute the program in Internet Explorer.

Step 7 :Write the source code for connectivity.

Step 8:Using MS-Access, save the database.

Step 9:connect the database using ODBC Source connection.

Step 10: Add the database name in ODBC data source administrator.

Step 11:Add the table name to connection.

Step 12:Compile the program and execute it.

Step 13 :Stop the program.

Page 119: 241254 Web Technology Lab Manual

PROGRAM

import javax.servlet.*;

import java.io.*;

import java.sql.*;

public class servletdemojdbc implements Servlet

{

public void init(ServletConfig c) throws ServletException

{

//super.init(c);

System.out.println("joint method");

}

public void service(ServletRequest req,ServletResponse res)throws

ServletException,IOException

{

Connection c= null;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

c=DriverManager.getConnection("jdbc:odbc:jdbcdemo");

Statement stmt=c.createStatement();

ResultSet rs=stmt.executeQuery("select * from Employee");

System.out.println("name and password are");

while(rs.next())

{

System.out.println(rs.getString(1)+"\t"+rs.getInt(2)+"\t"+rs.getDouble(3));

}

c.close();

}

catch(SQLException e1)

{

e1.printStackTrace();

}

catch(Exception e)

{

Page 120: 241254 Web Technology Lab Manual

System.out.println("error"+e.getMessage());

}

System.out.println("exec ");

}

public String getServletInfo()

{

String author="raman";

String program="c";

System.out.println(author+"wrote"+program);

return null;

}

public ServletConfig getServletConfig()

{

return null;

}

public void destroy()

{

}

}

Page 121: 241254 Web Technology Lab Manual

Sample output:

RESULT:

Thus the program for database connectivity using jdbc has been created and executed successfully

Page 122: 241254 Web Technology Lab Manual

EX.No:7

Date:

SAMPLE WEB APPLICATION DEVELOPMENT IN THE OPEN SOURCE ENVIRONMENT WITH DATABASE ACCESS.

AIM:

To create Sample web application development in the open source environment.

ALGORITHM :

Step1: start the program

Step2: Inside the asp definiton tag include the html contents

Step3: include the code for the database connectivity using the ado object

Step4: select all the datas form the student table

Step5: Traverse all the tuples in the table

Step6: Print the datas

Step7: close the connection

Step8: stop the program

Page 123: 241254 Web Technology Lab Manual

Programs:

access.asp file:<% Option Explicit %>

<html>

<% DIM name

set con=Server.CreateObject("ADODB.Connection">

con.open "dsn=cse;"

set rs=Server.Createobject("ADODB.RecordSet")

set rs=con.Execute("select * from student where name="&name&")%>

<table border="," width="50"%>

<% while NOT rs.EOF %>

<tr><% for t=0 to 6 %>

<td><% Response.write(rs(i)) %>

<% NEXT %></td></tr>

<% Move Next wend %></table>

<%con.close%>

</html>

stuaccess.html file:

<html>

<form action="access.asp" method="post">

Name<input type="text" name="Name"><br><br>

<input type="submit">

<input type="reset">

</form>

</html>

Page 124: 241254 Web Technology Lab Manual

Sample Output:

RESULT :

Thus the Sample web application development in the open source environment has been executed successfully executed.

Page 125: 241254 Web Technology Lab Manual

INTRODUCTION TO XML

XML stands for EXtensible Markup Language XML is a markup language much like HTML. XML was designed to describe data. XML tags are not predefined in XML. You must define your own tags. XML is self describing. XML uses a DTD (Document Type Definition) to formally describe the data.

The main difference between XML and HTML

XML is not a replacement for HTML. XML and HTML were designed with different goals:XML was designed to describe data and to focus on what data is. HTML was designed to display data and to focus on how data looks.

HTML is about displaying information, XML is about describing information.

How can XML be used?XML can keep data separated from your HTML

XML can be used to store data inside HTML documents XML can be used as a format to exchange information XML can be used to store data in files or in databases

XML Syntax

All XML elements must have a closing tag.

<p>This is a paragraph</p> <p>This is another paragraph</p>

XML tags are case sensitive

<Message>This is incorrect</message> <message>This is correct</message>

All XML elements must be properly nested

<b><i>This text is bold and italic</i></b>

All XML documents must have a root tag <root> <child> <subchild> </subchild> </child> </root>

Attribute values must always be quoted

<?xml version="1.0"?><note date="12/11/99"><to>Tove</to><from>Jani</from>

Page 126: 241254 Web Technology Lab Manual

<heading>Reminder</heading><body>Don't forget me this weekend!</body></note>

XML Attributes

XML attributes are normally used to describe XML elements, or to provide additional information about elements. From HTML you can remember this construct: <IMG SRC="computer.gif">. In this HTML example SRC is an attribute to the IMG element. The SRC attribute provides additional information about the element.

Attributes are always contained within the start tag of an element. Here are some examples:

<file type="gif"><person id="3344">

XML Validation

"Well Formed" XML documents

A "Well Formed" XML document is a document that conforms to the XML syntax rules that we described in the previous chapter.

The following is a "Well Formed" XML document:

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

"Valid" XML documents

A "Valid" XML document is a "Well Formed" XML document which conforms to the rules of a Document Type Definition (DTD).

The following is the same document as above but with an added reference to a DTD:

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

Page 127: 241254 Web Technology Lab Manual

Introduction to DTD

The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document structure with a list of legal elements. A DTD can be declared inline in your XML document, or as an external reference.

Internal DTD

This is an XML document with a Document Type Definition:

<?xml version="1.0"?><!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)>]><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>

The DTD is interpreted like this: !ELEMENT note (in line 2) defines the element "note" as having four elements: "to,from,heading,body". !ELEMENT to (in line 3) defines the "to" element  to be of the type "CDATA". !ELEMENT from (in line 4) defines the "from" element to be of the type "CDATA" and so on.....

External DTD

This is the same XML document with an external DTD:

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

Page 128: 241254 Web Technology Lab Manual

This is a copy of the file "note.dtd" containing the Document Type Definition:

<?xml version="1.0"?><!ELEMENT note (to,from,heading,body)><!ELEMENT to (#PCDATA)><!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)><!ELEMENT body (#PCDATA)>

Why use a DTD?

XML provides an application independent way of sharing data. With a DTD, independent groups of people can agree to use a common DTD for interchanging data. Your application can use a standard DTD to verify that data that you receive from the outside world is valid. You can also use a DTD to verify your own data.

The building blocks of XML documents

XML documents (and HTML documents) are made up by the following building blocks:

Elements, Tags, Attributes, Entities, PCDATA, and CDATA

This is a brief explanation of each of the building blocks:

Elements

Elements are the main building blocks of both XML and HTML documents.

Examples of HTML elements are "body" and "table". Examples of XML elements could be "note" and "message". Elements can contain text, other elements, or be empty. Examples of empty HTML elements are "hr", "br" and "img".

Tags

Tags are used to markup elements.

A starting tag like <element_name> mark up the beginning of an element, and an ending tag like </element_name>  mark up the end of  an element.

Examples:A body element: <body>body text in between</body>. A message element: <message>some message in between</message>

Attributes

Attributes provide extra information about elements.

Attributes are placed inside the start tag of an element. Attributes come in name/value pairs. The following "img" element has an additional information about a source file:

Page 129: 241254 Web Technology Lab Manual

<img src="computer.gif" />

The name of the element is "img". The name of the attribute is "src". The value of the attribute is "computer.gif". Since the element itself is empty it is closed by a " /".

PCDATA

PCDATA means parsed character data. Think of character data as the text found between the start tag and the end tag of an XML element. PCDATA is text that will be parsed by a parser. Tags inside the text will be treated as markup and entities will be expanded. 

CDATA

CDATA also means character data. CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT be treated as markup and entities will not be expanded.

Entities

Entities as variables used to define common text. Entity references are references to entities. Most of you will known the HTML entity reference: "&nbsp;"  that is used to insert an extra space in an HTML document. Entities are expanded when a document is parsed by an XML parser.

The following entities are predefined in XML:

Entity References Character

&lt; <

&gt; >

&amp; &

&quot; "

&apos; '

DTD – Elements

Declaring an Element

In the DTD, XML elements are declared with an element declaration. An element declaration has the following syntax:

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

Empty elements

Empty elements are declared with the keyword EMPTY inside the parentheses:

<!ELEMENT element-name (EMPTY)>

example:

Page 130: 241254 Web Technology Lab Manual

<!ELEMENT img (EMPTY)>

Elements with data

Elements with data are declared with the data type inside parentheses:

<!ELEMENT element-name (#CDATA)> or<!ELEMENT element-name (#PCDATA)> or<!ELEMENT element-name (ANY)>example:<!ELEMENT note (#PCDATA)>

#CDATA means the element contains character data that is not supposed to be parsed by a parser.

#PCDATA means that the element contains data that IS going to be parsed by a parser.

The keyword ANY declares an element with any content.

If a #PCDATA section contains elements, these elements must also be declared.

DTD – Attributes

Declaring Attributes

In the DTD, XML element attributes are declared with an ATTLIST declaration. An attribute declaration has the following syntax:

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

As you can see from the syntax above, the ATTLIST declaration defines the element which can have the attribute, the name of the attribute, the type of the attribute, and the default attribute value.

The attribute-type can have the following values:

Value Explanation

CDATA The value is character data

(eval|eval|..) The value must be an enumerated value

ID The value is an unique id

IDREF The value is the id of another element

IDREFS The value is a list of other ids

NMTOKEN The value is a valid XML name

NMTOKENS The value is a list of valid XML names

ENTITY The value is an entity

ENTITIES The value is a list of entities

NOTATION The value is a name of a notation

xml: The value is predefined

Page 131: 241254 Web Technology Lab Manual

The attribute-default-value can have the following values:

Value Explanation

#DEFAULT value The attribute has a default value

#REQUIRED The attribute value must be included in the element

#IMPLIED The attribute does not have to be included

#FIXED value The attribute value is fixed

Attribute declaration example

DTD example:<!ELEMENT square EMPTY> <!ATTLIST square width CDATA "0">

XML example:<square width="100"></square>

In the above example the element square is defined to be an empty element with the attributes width of  type CDATA. The width attribute has a default value of 0. 

Introduction to XML Schema

XML Schema is an XML-based alternative to DTD.

An XML schema describes the structure of an XML document.

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

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

An XML Schema:

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

XML Schemas are the Successors of DTDs

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

Page 132: 241254 Web Technology Lab Manual

XML Schemas are extensible to future additions XML Schemas are richer and more powerful than DTDs XML Schemas are written in XML XML Schemas support data types XML Schemas support namespaces

XML Schemas Support Data Types

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

With support for data types:

It is easier to describe allowable document content It is easier to validate the correctness of data It is easier to work with data from a database It is easier to define data facets (restrictions on data) It is easier to define data patterns (data formats) It is easier to convert data between different data types

XML Schemas use XML Syntax

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

Some benefits of that XML Schemas are written in XML:

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

XML Schemas Secure Data Communication

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

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

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

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

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

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

Page 133: 241254 Web Technology Lab Manual

XML Schemas are Extensible

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

With an extensible Schema definition you can:

Reuse your Schema in other Schemas Create your own data types derived from the standard types Reference multiple schemas in the same document

An XML Schema<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"targetNamespace=http://www.w3schools.com xmlns="http://www.w3schools.com"elementFormDefault="qualified">

<xs:element name="note">   <xs:complexType>    <xs:sequence>       <xs:element name="to" type="xs:string"/>       <xs:element name="from" type="xs:string"/>      <xs:element name="heading" type="xs:string"/>      <xs:element name="body" type="xs:string"/>    </xs:sequence> /xs:complexType></xs:element>

</xs:schema>

Page 134: 241254 Web Technology Lab Manual

EX.No:8

Date:

CREATION OF XML DOCUMENT FOR A SPECIFIC DOMAIN.

AIM:

To creation of XML document for a specific domain

ALGORITHM:

Step1:start the program

Step2:using Onclick(),validate the student details as entered.

Step3:In XML file,we use styles for structure the program as

#PCDATA(datafield)

Step4:Using various HTML tags and attribute,we design the web page.

Step5:Using various XML attribute list and entity list to retrieve the

information of student.

Step6:Using processing instructions which we required to describe the

data.

Step7:Using “note.xml”as xmlid to connect with html file.Execute the

program.

Step8:Stop the program.

Page 135: 241254 Web Technology Lab Manual

Program

Student.html:

<HTML> <HEAD>

<SCRIPT>

function prev_onclick()

{

std.previousPage()

}

function next_onclick()

{

std.nextPage()

}

</SCRIPT>

</HEAD>

<BODY>

<xml id="note" src="note.xml"></xml>

<table id="std" dataSrc="#note" datapagesize="1" border="1">

<thead>

<tr><th>REGNO</th><th>NAME</th><th>COURSE</th><TH>SEM</th></tr>

</thead>

<tbody>

<tr><td><span datafld="REGNO"></span></td>

<td><span datafld="NAME"></span></td>

<td><span datafld="COURSE"></span></td>

<td><span datafld="SEM"></span></td>

</tr>

</tbody>

</table>

<INPUT TYPE="BUTTON" VALUE="NEXT" ONCLICK="next_onclick()">

<INPUT TYPE="BUTTON" VALUE="PREVIOUS" ONCLICK="prev_onclick()">

</BODY>

</HTML>

Page 136: 241254 Web Technology Lab Manual

note.xml:

<?xml version="1.0"?>

<note>

<STUDENT>

<REGNO>VMP49</REGNO>

<NAME>THANUJA.O</NAME>

<COURSE>M.E CSE</COURSE>

<SEM>II</SEM>

</STUDENT>

<STUDENT>

<REGNO>VMP52</REGNO>

<NAME>TAMILARASI</NAME>

<COURSE>M.E CSE</COURSE>

<SEM>II</SEM>

</STUDENT>

</note>

Page 137: 241254 Web Technology Lab Manual

Sample Output :

RESULT :

Thus the developing XML program has been executed successfully.

Page 138: 241254 Web Technology Lab Manual

EX. No:9

Date :

WRITING DTD OR XML SCHEMA FOR THE DOMAIN SPECIFIC XML DOCUMENT

AIM:To write a program for DTD and XML schema for the domain specific XML

document.

ALGORITHM:

Step1:start the program

Step2:open an XML file as Letter.xml, to create detail of person using

various xml attribute list

Step3:using user defined tags, we can create details of person using

name, pincode, address, ph.no, etc..

Step4:open DTD file as letter . dtd

Step5:using an external and internaldtd,we create elementlist as

#PCDATA for retrieve the datafield

Step6:using attribute declaration ,use to retrieve the datafield as more

than one time

Step7:Execute the program

Page 139: 241254 Web Technology Lab Manual

Program: Letter.xml:

<?xml version="1.0"?>

<letter>

<contact type="sender">

<name>aaaa</name>

<address>dfdsgdsgdsfvg</address>

<city>chennai</city>

<state>tamilnadu</state>

<zip>600089</zip>

<phone>044-23456789</phone>

<flag gender="F"/>

</contact>

<contact type="receiver">

<name>bbbb</name>

<address1>dfdsgdsgdsfvg</address1>

<address2>fvgefgffdg</address2>

<city>chennai</city>

<state>tamilnadu</state>

<zip>600089</zip>

<phone>044-23456789</phone>

<flag gender="F"/>

</contact>

<salutation>Dear Sir: </salutation>

<paragraph>It is our privillege .........</paragraph>

<closing>Sincerely</closing>

<signature>Ms.aaaaa</signature>

</letter>

Page 140: 241254 Web Technology Lab Manual

Letter.dtd:

<!element letter(contact+, salutation, paragraph+, closing, signature)>

<element contact(name, address1, address2, city, state, zip, phone, flag)>

<!attlist contacttype CDATA #implied>

<!element address1(#PCDATA)>

<!element address2(#PCDATA)>

<!element city(#PCDATA)>

<!element state(#PCDATA)>

<!element zip(#PCDATA)>

<!element phone(#PCDATA)>

<!element flag EMPTY>

<!attlist flag gender(M/F)"M">

<!element salutation(#pcdata)>

<!element closing (#pcdata)>

<!element paragraph (#pcdata)>

<!element signature (#pcdata)>

Page 141: 241254 Web Technology Lab Manual

output:

RESULT:

Thus the program for writing DTD or XML schema for the domain specific XML document has been successfully completed.

Page 142: 241254 Web Technology Lab Manual

Parsers? DOM vs SAX parser

Parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.

DOM1. Tree of nodes2. Memory: Occupies more memory, preffered for small XML documents3. Slower at runtime 4. Stored as objects 5. Programmatically easy 6. Ease of navigation SAX 1. Sequence of events 2. Doesn't use any memory preferred for large documents3. Faster at runtime4. Objects are to be created5. Need to write code for creating objects6. Backward navigation is not possible as it sequentially processes the document

Parsing XML with SAX Introduction

This web page publishes SAX Parser code that reads XML formatted data into Java objects. A class is included that will allocate and initialize the SAX Parser. If a boolean flag is true, the parser will be initialized as a validating parser. The XML schema that the XML documents are validated against is published here as well.

SAX: Ass Backward Parsing

With SAX and XML Schema validation as examples, I am left with the impression that the people who developed these technologies never took a compiler implementation class, or if they did, the class left no impression on them.

Parsing is usually done by two logical components: a parser and a scanner. The scanner reads the text and classifies it as "tokens". A token is a catagory that is recognized by the parser. For example, a scanner for the Java programming language might return the tokens that include: identifier, integer, for (a reserved word), mult (an operator). An important point, relative to SAX, is that the parser calls the scanner. As the parser processes the tokens returned by the scanner it performs operations, like building a syntax tree. An example of a parser that reads assignment statements and arithmetic expressions and builds XML can be found here. The is part of the DOM parsing software mentioned above.

In the case of SAX, the scanner (the SAXParser object) calls the parser. This makes parsing with SAX needlessly awkward and complicates the architecture of the software.

Page 143: 241254 Web Technology Lab Manual

For this reason, the DOMParser is frequently used for parsing complicated XML documents.

SAX is not without its virtues (maybe)

The SAXParser does have two notable advantages over the DOMParser: the SAXParser is faster and it uses less memory. While the SAXParser is difficult to use for processing complex XML documents, perhaps it is appropriate for processing simple XML documents? This web page grew out of an experiment to see if this is true.

A Prototype Application

The prototype code published on this web page is motivated by a real application. This is a software system I call a Trade Engine, which is diagrammed in Figure 1. The Trade Engine is designed to process order and control messages for trading applications. These might be computer driven trading programs for the stock, options or foreign exchange markets. The trading applications submit XML formatted orders and control messages to the Trade Engine. The Trade Engine parses and validates these messages and builds internal Java objects. The market orders are called "aim orders" because they specify a trading goal. Depending on the processing instructions, the Trade Engine may execute the order over a period of time (e.g., the trading day).

Figure 1

Parsing Trade Engine Messages using SAX

SAX uses "call backs". When the SAXParser object recognizes a component in an XML document (e.g., a start Element, an end Element, the characters between tags), it calls a method that may be supplied by the application to process the XML component. In Java this is done by subclassing a handler class, like the DefaultHandler. This can be seen in the method signature in the javax.xml.parsers.SAXParser object for the parse method used in this example:

parse(InputStream is, DefaultHandler dh)

In this example a MessageProcessor subclass is derived from the DefaultHandler class. The MessageProcessor class overrides the methods associated with the XML components that are of interest. For example, startElement is overridden, but the

Page 144: 241254 Web Technology Lab Manual

processingInstruction() method is not. The MessageProcessor class is diagrammed in Figure 2.

Figure 2

The result of the SAXParser calling the methods overridden by the MessageProcessor class is to build an object from the data. All Trade Engine objects share a common set of fields indicating the product that sent the message, the user and a local ID that is used by the product. The specific messages have unique data that is associated with that message type. This is experimental prototype code, so only two message types, Control and AimOrder are supported. This is shown in the Figure 3.

Figure 3

A Trade Engine message may enclose multiple sub-messages. For example, one Trade Engine message may include multiple aim orders. When the MessageProcessor class recognizes the start of a sub-message it allocates a sub-message processor. The MessageProcessor then calls the sub-message processor methods to process each of the XML components and build the object. The class diagram for the sub-message processors is shown in Figure 4. Again, this is just a prototype, so there are only two message processors.

Page 145: 241254 Web Technology Lab Manual

Figure 4

The MessageBaseMessage base class processes the common data fields in the MessageBase object, which is the base class for the Control and AimOrder objects.

Conclusion

The software published here builds message objects from XML formatted data. In theory using the SAXParser for this is faster than using the DOMParser to build a DOM object and then traversing the DOM tree to build a message object. But the call back architecture of SAX introduces complexity that does not exist for a parser which calls a scanner. The awkwardness of SAX and the overhead of DOMParsing are some of the motivations behind the XML Pull Parser, which is called by a parsing application. An example that applies XML Pull Parsing to the Trade Engine messages described on this web page can be found here.

One advantage that both the SAX and DOM parsers have is that they are validating. The structure of the XML document can be verified against an XML schema. However, the computational cost of this validation is unknown (at least to me). SAX validation may reduce the computational advantage of the SAX parser compared to the DOM parser.

XML Parsers: DOM and SAX Put to the Test

XML is becoming increasingly popular in the developer community as a tool for passing, manipulating, storing, and organizing information. If you are one of the many developers planning to use XML, you must carefully select and master the XML parser. The parser—one of XML's core technologies—is your interface to an XML document, exposing its contents through a well-specified API. Confirm that the parser you select has the functionality and performance that your application requires. A poor choice can result in excessive hardware requirements, poor system performance and developer productivity, and stability issues.

Page 146: 241254 Web Technology Lab Manual

I tested a of selection of Java-based XML parsers, and this article presents the results while discussing the performance issues you should consider when selecting a parser. Your software's performance hinges on your choosing the right one.

Performance IssuesBecause XML is a standardized format, it offers more developer and product support than proprietary formats, parsers, and configuration and storage schemes. Your XML project also will be easier to manage if you keep it simple. If possible, write interface code in only one or two languages (e.g., Java or C++), using as few APIs as possible (DOM, SAX, XML, and perhaps JAXP).

Minimizing technologies sounds good in theory, but it can't be done without effective tools. What makes a tool effective? Depending on the project, the following attributes can:

Stable specifications Commercial vendor support Adequate performance Adequate API features

SAX vs. DOMAt present, two major API specifications define how XML parsers work: SAX and DOM. The DOM specification defines a tree-based approach to navigating an XML document. In other words, a DOM parser processes XML data and creates an object-oriented hierarchical representation of the document that you can navigate at run-time.

The SAX specification defines an event-based approach whereby parsers scan through XML data, calling handler functions whenever certain parts of the document (e.g., text nodes or processing instructions) are found.

How do the tree-based and event-based APIs differ? The tree-based W3C DOM parser creates an internal tree based on the hierarchical structure of the XML data. You can navigate and manipulate this tree from your software, and it stays in memory until you release it. DOM uses functions that return parent and child nodes, giving you full access to the XML data and providing the ability to interrogate and manipulate these nodes. DOM manipulation is straightforward and the API does not take long to understand, particularly if you have some JavaScript DOM experience.

In SAX's event-based system, the parser doesn't create any internal representation of the document. Instead, the parser calls handler functions when certain events (defined by the SAX specification) take place. These events include the start and end of the document, finding a text node, finding child elements, and hitting a malformed element.

SAX development is more challenging, because the API requires development of callback functions that handle the events. The design itself also can sometimes be less intuitive and modular. Using a SAX parser may require you to store information in your own internal document representation if you need to rescan or analyze the information—SAX provides no container for the document like the DOM tree structure.

Is having two completely different ways to parse XML data a problem? Not really, both parsers have very different approaches for processing the information. The W3C DOM

Page 147: 241254 Web Technology Lab Manual

specification provides a very rich and intuitive structure for housing the XML data, but can be quite resource-intensive given that the entire XML document is typically stored in memory. You can manipulate the DOM at run-time and stream the updated data as XML, or transform it to your own format if you require.

The strength of the SAX specification is that it can scan and parse gigabytes worth of XML documents without hitting resource limits, because it does not try to create the DOM representation in memory. Instead, it raises events that you can handle as you see fit. Because of this design, the SAX implementation is generally faster and requires fewer resources. On the other hand, SAX code is frequently complex, and the lack of a document representation leaves you with the challenge of manipulating, serializing, and traversing the XML document.

Putting the Parser to the TestTo determine the right parser for you, prioritize the importance of functionality, speed, memory requirements, and class footprint size. A few types of tests can help you evaluate them, although the performance of some depends on the specific nature and design of your software. These tests include parsing large and small XML documents, traversing and navigating the processed DOM, constructing a DOM from scratch, and evaluating the resource requirements of the parser.

You can tell quite a bit about a parser by using one or two simple XML documents. If your software will have to deal with many small files, see if the parser has some initialization overhead that slows down repeated parsing. For very large files, confirm that the parser can interpret the file in sufficient time with reasonable resource requirements. For the latter case, very large XML documents may require using a SAX parser that does not store the document in memory. You might also consider reading in parts of the document (using an appropriate DTD that allows for a partial document) and manipulating the document fragments in memory, one at a time.

In addition, new DOM parsing solutions may handle massive XML documents more effectively. Remember that the DOM API specifies only how to interact with the document, not how it must be stored. Persistent DOM (PDOM) implementations with index-based searches and retrieval are in the works, but I have not yet tested any of these.

You should also evaluate how well the parser traverses an in-memory DOM after XML data has been parsed. If you require the ability to search or scan through a post-parsed DOM using the API, you can rule out SAX—unless you are willing to create your own document model from your callback functions. For W3C DOM-compliant parsers, test the speed of scanning through the constructed DOM to see how expensive traversal of the tree can be.

Some XML parsers come with a serialization feature and are able to convert a document tree to XML data. This capability is not in all parsers, but the performance of parsers that support this ability is often proportional to the time required to navigate a given document tree using the API. Again, because SAX does not support an internal representation of the document, you would have to provide your own document and serialization functionality.

Page 148: 241254 Web Technology Lab Manual

Parsing BenchmarksThe available XML parsers vary in performance. Performance is not a definitive benchmark, and it barely scratches the surface of all parser capabilities. I used the XmlTest application to test a selection of Java-based XML parsers:

Sun's Project X parser, included with the JAXP release Oracle's v2 XML parser the Xerces-J parser, shared by both IBM and Apache XP

All of the parsers have both SAX and DOM support except for the XP parser, which is SAX-based.

Page 149: 241254 Web Technology Lab Manual

Ex.No:

Date:

PARSING AN XML DOCUMENT USING DOM AND SAX PARSERS.

AIM:

To Parsing an XML document using DOM and SAX Parsers.

ALGORITHM :

Using Dom:

Step1: Get a document builder using document builder factory and parse the xml

file to create a DOM object

Step 2: Get a list of employee elements from the DOM

Step3: For each employee element get the id, name, age and type. Create an

employee value object and add it to the list.

Step4: At the end iterate through the list and print the employees to verify we

parsed it right.

Using Sax

Step1: Create a Sax parser and parse the xml

Step2: In the event handler create the employee object

Step3 : Print out the data

Page 150: 241254 Web Technology Lab Manual

Coding

employees.xml<?xml version="1.0" encoding="UTF-8"?><Personnel>  <Employee type="permanent">        <Name>Seagull</Name>        <Id>3674</Id>        <Age>34</Age>   </Employee>  <Employee type="contract">        <Name>Robin</Name>        <Id>3675</Id>        <Age>25</Age>    </Employee>  <Employee type="permanent">        <Name>Crow</Name>        <Id>3676</Id>        <Age>28</Age>    </Employee></Personnel>

Using DOM  DomParserExample.java

a) Getting a document builder private void parseXmlFile(){

//get the factoryDocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

try {

//Using factory get an instance of document builderDocumentBuilder db = dbf.newDocumentBuilder();

//parse using builder to get DOM representation of the XML filedom = db.parse("employees.xml");

}catch(ParserConfigurationException pce) {pce.printStackTrace();

}catch(SAXException se) {se.printStackTrace();

}catch(IOException ioe) {ioe.printStackTrace();

Page 151: 241254 Web Technology Lab Manual

}}

b) Get a list of employee elementsGet the rootElement from the DOM object.From the root element get all employee elements. Iterate through each employee element to load the data.

private void parseDocument(){//get the root elementElement docEle = dom.getDocumentElement();

//get a nodelist of elements

NodeList nl = docEle.getElementsByTagName("Employee");if(nl != null && nl.getLength() > 0) {

for(int i = 0 ; i < nl.getLength();i++) {

//get the employee elementElement el = (Element)nl.item(i);

//get the Employee objectEmployee e = getEmployee(el);

//add it to listmyEmpls.add(e);

}}

}c) Reading in data from each employee.

/** * I take an employee element and read the values in, create * an Employee object and return it */private Employee getEmployee(Element empEl) {

//for each <employee> element get text or int values of//name ,id, age and nameString name = getTextValue(empEl,"Name");int id = getIntValue(empEl,"Id");int age = getIntValue(empEl,"Age");

String type = empEl.getAttribute("type");

//Create a new Employee with the value read from the xml nodesEmployee e = new Employee(name,id,age,type);

Page 152: 241254 Web Technology Lab Manual

return e;}

/** * I take a xml element and the tag name, look for the tag and get * the text content * i.e for <employee><name>John</name></employee> xml snippet if * the Element points to employee node and tagName is 'name' I will return John */private String getTextValue(Element ele, String tagName) {

String textVal = null;NodeList nl = ele.getElementsByTagName(tagName);if(nl != null && nl.getLength() > 0) {

Element el = (Element)nl.item(0);textVal = el.getFirstChild().getNodeValue();

}

return textVal;}

/** * Calls getTextValue and returns a int value */private int getIntValue(Element ele, String tagName) {

//in production application you would catch the exceptionreturn Integer.parseInt(getTextValue(ele,tagName));

}d) Iterating and printing.

private void printData(){

System.out.println("No of Employees '" + myEmpls.size() + "'.");

Iterator it = myEmpls.iterator();while(it.hasNext()) {

System.out.println(it.next().toString());}

}Using Sax:SAXParserExample.java

a) Create a Sax Parser and parse the xml

private void parseDocument() {

Page 153: 241254 Web Technology Lab Manual

//get a factorySAXParserFactory spf = SAXParserFactory.newInstance();try {

//get a new instance of parserSAXParser sp = spf.newSAXParser();

//parse the file and also register this class for call backssp.parse("employees.xml", this);

}catch(SAXException se) {se.printStackTrace();

}catch(ParserConfigurationException pce) {pce.printStackTrace();

}catch (IOException ie) {ie.printStackTrace();

}}

b) In the event handlers create the Employee object and call the corresponding setter methods.

//Event Handlerspublic void startElement(String uri, String localName, String qName,

Attributes attributes) throws SAXException {//resettempVal = "";if(qName.equalsIgnoreCase("Employee")) {

//create a new instance of employeetempEmp = new Employee();tempEmp.setType(attributes.getValue("type"));

}}

public void characters(char[] ch, int start, int length) throws SAXException {tempVal = new String(ch,start,length);

}

public void endElement(String uri, String localName,String qName) throws SAXException {

if(qName.equalsIgnoreCase("Employee")) {//add it to the listmyEmpls.add(tempEmp);

Page 154: 241254 Web Technology Lab Manual

}else if (qName.equalsIgnoreCase("Name")) {tempEmp.setName(tempVal);

}else if (qName.equalsIgnoreCase("Id")) {tempEmp.setId(Integer.parseInt(tempVal));

}else if (qName.equalsIgnoreCase("Age")) {tempEmp.setAge(Integer.parseInt(tempVal));

}

}c) Iterating and printing.

private void printData(){

System.out.println("No of Employees '" + myEmpls.size() + "'.");

Iterator it = myEmpls.iterator();while(it.hasNext()) {

System.out.println(it.next().toString());}

}

OUTPUT:Employee Details - Name:Seagull, Type:permanent, Id:3674, Age:34.Employee Details - Name:Robin, Type:contract, Id:3675, Age:25.Employee Details - Name:Crow, Type:permanent, Id:3676, Age:28.

Page 155: 241254 Web Technology Lab Manual

Result :

Thus the Parsing an XML document using DOM and SAX Parsers is been done and executed successfully.

INTRODUCTION TO PHP

For many people, the main reson for learning a scripting language like PHP is

because of the interaction with databases it can offer. In this tutorial I will show you how

to use PHP and the MySQL database to store information on the web and include it into

your website. Before you read this tutorial you should have at least a basic knowledge of

how to use PHP. If you do not yet know PHP, I suggest that you read our PHP tutorial

before continuing.

Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer

supported version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4

is the current generation of PHP, which uses the

Page 156: 241254 Web Technology Lab Manual

Zend engine under the hood.

PHP 5 uses Zend engine 2 which, among other things, offers many

additionalOOP features

Why Would I Want A Database?

It is actually surprising how useful a database can be when used with a website. There are

a huge variety of things you can do when you interact the two, from displaying simple

lists to running a complete website from a database. Some examples of PHP and MySQL

being used together are:

Banner Rotation. On this site, where each banner is, a PHP script is called. This

opens a database and picks a random banner from it to show the visitor. It also

counts the number of times the banner has been viewed and could, with a few

changes, track clicks too. To add, change or edit the banners all I have to do is

change the database and the script will pick the correct banners for all the pages

on the site.

Forums. Hundreds of forums (message boards) on the internet are run using PHP

and MySQL. These are much more efficent than other systems that create a page

for each message and offer a wide variety of options. All the pages in the forum

can be updated by changing one script.

Databases. One quite obvious example is sites which get all there information

from a database. For example Script Avenue is run by a few scripts, which gain

all their information from a large database. All the different script categories can

be accessed in one script by just changing the URL to access a different part of

the database.

Websites. If you have a large website and you want to change the design it can

take a very long time to update and upload all the pages. With PHP and MySQL

your whole website could be just one or two PHP scripts. These would access a

MySQL database to get the information for the pages. To update the website's

design you would just have to change one page.

What Do I Need?

You only really need three things to run PHP scripts which access MySQL databases.

Page 157: 241254 Web Technology Lab Manual

Firstly, you will, of course, need a webserver. This can either be on a computer of your

own or on a web host. Any web server software should work with PHP and MySQL but

the best to use is Apache, which is free.

PHP also needs to be installed on the server. If it is not already installed you can install it

(or ask your web host to install it). It can be downloaded from PHP.net and is also free. If

you are not sure if you have PHP installed I will show you a way to check it later.

Finally, you will also require MySQL. This is the actual database software. You can also

use most other types of database (SQL, Oracle etc.) but as this is a PHP/MySQL tutorial I

will deal just now with the MySQL database (although the commands used here will also

work with SQL databases). As with the other software you need, MySQL is free and can

be downloaded from the MySQL homepage. If you are not sure if you have MySQL

installed, I will show you how to check later.

If you cannot install (or your web host won't allow) PHP and MySQL you can still use

another web host. Freedom2Surf are a free (banner supported) web host and support PHP

and have MySQL installed. HostRocket are an excellent web host and can offer you

300MB of space with PHP, MySQL and loads of other extras for under $10 a month.

Testing For PHP and MySQL

There is a simple test for both PHP and MySQL. Open a text editor and type in the

following:

<?

phpinfo();

?>

and save it as phpinfo.php Now upload this to your webspace and go to i

t in your browser. If you have PHP installed you will see a huge page with all the details

of your PHP installation on it. Next, scroll down through all this information. If you find

a section about MySQL then you will know that MySQL is installed.

Page 158: 241254 Web Technology Lab Manual

Managing Databases

Although all the database administrative options can be done through PHP scripts, I

strongly suggest installing a copy of PHPMyAdmin on your server. It is an excellent free

set of scripts that will provide you with an administrative interface for your MySQL

database(s). You can add, remove, edit, backup and view your databases using this and it

is especially useful when troubleshooting your databases.

PHP is one of the fastest growing web scripting languages on the Internet today,

and for good reason. PHP (which stands for Hypertext Preprocessor) was

designed explicitly for the web. Designed in 1994 to enable the creation of

dynamic web pages quickly and easily, PHP has exploded in growth and has been

adopted by major vendors such as Linux that have included the language with

their web servers.

The language is easy to learn and works with a variety of operating systems.

PHP’s strong performance, coupled with its modest learning curve, has made it

the language of choice for many businesses wanting a cost-effective rapid

application development solution for the web.

Reason for choosing PHP

    One of the main reasons that businesses choose PHP is its simplicity and ease of use.

PHP competes against a number of other web scripting solutions such as Active Server

Pages and PERL, but none of these languages are as easy to learn as PHP. Further, some

languages require a moderate amount of programming background before a developer

can get up to speed in development. With PHP, however, even non-programmers have

been able to develop web-based solutions within a matter of days after going through the

basic tutorials on PHP. PHP commands are simply embedded into the same web page

with HTML commands, and execute on the server to deliver the web pages to the user.

    Another big advantage of PHP is its interoperability with multiple operating systems.

A company can use PHP with either Linux, Windows or Macs for example. They can

also use PHP with the popular open source Apache server. Compare that with

Page 159: 241254 Web Technology Lab Manual

Microsoft’s Active Server Pages, by contrast, which is primarily designed for Microsoft-

enabled servers. Portability is becoming a chief concern for businesses that use one or

more operating systems in their businesses. Businesses save money by using PHP to

leverage their existing I.S. resources rather than investing large sums of money to

purchase proprietary products.

    PHP is an open source product with a worldwide community of developers. What this

means for businesses is that there is a large network of developers who can continually

refine PHP to make it a better product. It’s no surprise that since its inception in 1994,

developers have created a large library of useful add-ins to make PHP even more

powerful than ever. PHP includes support for native databases among numerous other

“plug and play” features that enable users to exploit the language to its fullest.

    The result of all of this for businesses is rapid application development. This is

especially important for the web, where businesses must develop web-based applications

that can respond to the real-time demands of e-Commerce. PHP enables companies to

deploy their web-based solutions quickly, and modify them just as easily when needed.

PHP is a stable, reliable language for administrators to use as well. PHP is easily

customized to work seamlessly with Open Source databases such as MySQL.

    Because of its lightweight design, PHP is fast and performs exceptionally well.

Numerous companies have realized that PHP is the best solution for their web server

needs. Companies such as Lycos in Europe offer services that are completely written in

PHP. The language is well able to handle the voluminous amounts of traffic delivered on

a daily basis. Many other major corporations worldwide have used PHP for their

enterprise needs as well. These companies include Cisco, Worldcom, Motorola, Air

Canada and Deutsche Bank, to name a few.

    A number of important statistics mark important milestones in PHP’s growth.

According to a Netcraft survey in May 2001, PHP’s popularity grew at a monthly rate of

8-11%. To put this in perspective, the growth of the entire Internet is 4%. At the time the

survey was taken, 6.5 million sites were using PHP. As of 2002, PHP leapt beyond

Microsoft’s Active Server Pages as the most popular web scripting language in use. PHP

is used on 24% of the sites on the Internet.

Page 160: 241254 Web Technology Lab Manual

Clearly the many benefits of PHP have made it the ideal solution for businesses to use in

deploying their web-based applications. Companies small and large know that for ease of

use, rapid development, superior performance, stability and reliability, and a large

worldwide community of users and developers, few languages can come close to

delivering what PHP can offer.

Advantages: PHP is accessible

** It's available for free

o It's available with documentation in many languages

o There are many support groups, forums, and teams supporting PHP

o There is a wealth of online information regarding PHP

It's quick to develop in PHP

** A basic PHP script can be created without a firm understanding of

programming principals, compilation, and other currently important programming

concepts

o PHP is loosely typed, which makes basic scripts much faster to develop with less attention to design

Programmers of Java, PERL, BASIC, and other popular languages can find many

parallels to ease transition to PHP

PHP is flexible. Use OOP or not. Use naming convention(s) or not

It runs on many different operating systems

It can be optimized, even "compiled" for performance closer to that of more

established compiled languages

Disadvantages: Out of the box, PHP tends to execute more slowly than assembly, C, and other

compiled languages

PHP is loosely typed. For developers of all skill levels, this allows room for

unexpected behavior due to programmer error that many other languages might

not permit. [Of course, few if any languages can protect from developer error!]

There are many ways to do one thing, and many cases where a function has

ambiguous handling due to legacy support or PHP development history.

Page 161: 241254 Web Technology Lab Manual

Ex.No:

Date:

CREATION OF WEB APPLICATION USING PHP

AIM:

To create a calculator web appliction using php.

ALGORITHM :

Step1 : Start the program

Step2 : Create a php web page calc.php

Step3: Using form and input type tag create various buttons, textbox, radio button

etc.

Step4: calcute the output for various option

Step5: using post method display the result in next page.

Step6: Stop the program.

Page 162: 241254 Web Technology Lab Manual

Coding:

Calc.php:

<?php ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Calculator</title> </head> <body> <?php // basic calculator program function showForm() { ?> All field are required, however, if you forget any, we will put a random number in for you. <br /> <table border="0"> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <tr> <td>Number:</td> <td><input type="text" maxlength="3" name="number" size="4" /></td>

Page 163: 241254 Web Technology Lab Manual

</tr> <span id="square"> <tr> <td>Another number:</td> <td><input type="text" maxlength="4" name="number2" size="4" /></td> </tr> </span> <tr> <td valign="top">Operator:</td> <td><input type="radio" name="opt" value="+" </>+<br /> <input type="radio" name="opt" value="-" />-<br /> <input type="radio" name="opt" value="*" />*<br /> <input type="radio" name="opt" value="/" />/<br /> <input type="radio" name="opt" value="^2" />x<sup>2</sup><br /> <input type="radio" name="opt" value="sqrt" />sqrt<br /> <input type="radio" name="opt" value="^" />^<br /> </td> </tr> <tr> <td>Rounding:</td> <td><input type="text" name="rounding" value="4" size="4" maxlength="4" /></td> <td><small>(Enter how many digits you would like to round to)</small> </td> </tr> <tr> <td><input type="submit" value="Calculate" name="submit" /></td> </tr> </form> </table> <?php }

if (empty($_POST['submit'])) { showForm(); } else { $errors = array(); $error = false; if (!is_numeric($_POST['number'])) { (int)$_POST['number'] = rand(1,200); } if (empty($_POST['number'])) { (int)$_POST['number'] = rand(1,200); } if (!is_numeric($_POST['number2'])) {

Page 164: 241254 Web Technology Lab Manual

(int)$_POST['number2'] = rand(1,200); } if (empty($_POST['number2'])) { (int)$_POST['number2'] = rand(1,200); } if (empty($_POST['rounding'])) { $round = 0; } if (!isset($_POST['opt'])) { $errors[] = "You must select an operation."; $error = true; } if (strpbrk($_POST['number'],"-") and strpbrk($_POST['number2'],"0.") and $_POST['opt'] == "^") { $errors[] = "You cannot raise a negative number to a decimal, this is impossible. <a href=\"http://hudzilla.org/phpwiki/index.php?title=Other_mathematical_conversion_functions\">Why?</a>"; $error = true; } if ($error != false) { echo "We found these errors:"; echo "<ul>"; foreach ($errors as $e) { echo "<li>$e</li>"; } echo "</ul>"; } else { switch ($_POST['opt']) { case "+": $result = (int)strip_tags($_POST['number']) + (int)strip_tags($_POST['number2']); echo "The answer to " . (int)strip_tags($_POST['number']) . " $_POST[opt] " . (int)strip_tags($_POST['number2']) . " is $result."; break; case "-"; $result = (int)strip_tags($_POST['number']) - (int)strip_tags($_POST['number2']); echo "The answer to " . (int)strip_tags($_POST['number']) . " $_POST[opt] " . (int)strip_tags($_POST['number2']) . " is $result."; break; case "*"; $result = (int)strip_tags($_POST['number']) * (int)strip_tags($_POST['number2']); echo "The answer to " . (int)strip_tags($_POST['number']) . " $_POST[opt] " . (int)$_POST['number2'] . " is $result."; break;

Page 165: 241254 Web Technology Lab Manual

case "/"; $result = (int)strip_tags($_POST['number']) / (int)strip_tags($_POST['number2']); $a = ceil($result); echo "<br />"; echo "<hr />"; echo "<h2>Rounding</h2>"; echo "$result rounded up is $a"; echo "<br />"; $b = floor($result); echo "$result rounded down is $b"; echo "<br />"; $h = round($result,(int)$_POST['rounding']); echo "$result rounded to $_POST[rounding] digits is " . $h; break; case "^2": $result = (int)strip_tags($_POST['number']) * (int)strip_tags($_POST['number2']); $a = (int)$_POST['number2'] * (int)$_POST['number2']; echo "The answer to " . (int)$_POST['number'] . "<sup>2</sup> is " . $result; echo "<br />"; echo "The answer to " . (int)$_POST['number2'] . "<sup>2</sup> is " . $a; break; case "sqrt": $result = (int)strip_tags(sqrt($_POST['number'])); $sqrt2 = (int)strip_tags(sqrt($_POST['number2'])); echo "The square root of " . (int)strip_tags($_POST['number']) . " is " . $result; echo "<br />"; echo "The square root of " . (int)strip_tags($_POST['number2']) . " is " . $sqrt2; echo "<br />"; echo "The square root of " . (int)strip_tags($_POST['number']) . " rounded to " . strip_tags($_POST[rounding]) . " digits is " . round($result,(int)$_POST['rounding']); echo "<br />"; echo "The square root of " . (int)strip_tags($_POST['number2']) . " rounded to " . strip_tags($_POST[rounding]) . " digits is " . round($sqrt2,(int)strip_tags($_POST['rounding'])); break; case "^": $result = (int)strip_tags(pow($_POST['number'],$_POST['number2'])); $pow2 = (int)strip_tags(pow($_POST['number2'],$_POST['number'])); echo (int)$_POST['number'] . "<sup>" . strip_tags($_POST[number2]) . "</sup> is " . $result; echo "<br />"; echo (int)$_POST['number2'] . "<sup>" . strip_tags($_POST[number]) . "</sup> is " . $pow2; break; } }

Page 166: 241254 Web Technology Lab Manual

} echo "<br />"; ?> <a href="calc.php">Go Back</a> </body> </html>

Page 167: 241254 Web Technology Lab Manual

OUTPUT:

Page 168: 241254 Web Technology Lab Manual
Page 169: 241254 Web Technology Lab Manual

Result: Thus the calculator web appliction using php is been developed succesfully.

Page 170: 241254 Web Technology Lab Manual

Ex.No:

Date:

CREATION OF WEB APPLICATION USING PHP

AIM:

To create a calculator web appliction using php.

ALGORITHM :

Step1: Start the program

Step2: Create a php web page contact.php

Step3: Using form and input type tag create various buttons, textbox, radio

button etc.

Step4: Get the necessary field from the user.

Step5: Using post method display the result in next page.

Step6: Stop the program.

Page 171: 241254 Web Technology Lab Manual

Coding:

Contact.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Web and Crafts</title><meta name="keywords" content="" /><meta name="description" content="" /><link href="style.css" rel="stylesheet" type="text/css" media="screen" /></head><body><!-- #header-wrapper -->

<?php

$name = $_POST['name']; $address = $_POST['address']; $city = $_POST['city'];$zip = $_POST['zip'];$phonenumber = $_POST['phonenumber']; $email = $_POST['email'];$message = $_POST['message']; $error=0; if (isset($_POST['submit'])) {

if (eregi('http:', $notes)) {die ("Do NOT try that! ! ");}if(!$email == "" && (!strstr($email,"@") || !strstr($email,"."))) {echo "<h2>Use Back - Enter valid e-mail</h2>\n"; $badinput = "<h2>Feedback was NOT submitted</h2>\n";echo $badinput;$error=1;}if(empty($name) || empty($phonenumber) || empty($email ) || empty($message)) {echo "<h2>Use Back - fill in all required fields </h2>\n"; $error=1; }

if($error!=1){$todayis = date("l, F j, Y, g:i a") ; $attn = $subject ;

$subject = "mail from $email";$message = stripcslashes($message); $mailmessage = " $todayis [EST]

\n Subject: $subject \n Message: $message \n From:

Page 172: 241254 Web Technology Lab Manual

$name ($email)\n City: $city\n Pin/Zip code: $zip\n PhoneNo: $phonenumber\n "; $from ="From: $email \r\n";

mail("[email protected]" ,$subject, $mailmessage,$from); echo "Thank You :"; echo "$name("; echo "$email )";

echo "for your interest in our services. We will contact you soon <br>";}else{echo "Use Back and Fill all required fields !!";} }else{?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" id="form1"> <table cellspacing="0" cellpadding="2" width="100%" border="0" class="text_main"> <tr> <td align="right" valign="center"><strong><font color="#ff0000">*</font>&nbsp;Name : </strong></td> <td align="left" valign="center"><input style="WIDTH: 207px; HEIGHT: 22px" size="26" name="name" /></td> </tr> <tr> <td align="right" valign="center"><strong>Address :</strong></td> <td align="left" valign="center"><textarea style="WIDTH: 205px; HEIGHT: 80px" name="address" rows="6" cols="22"></textarea></td> </tr> <tr> <td align="right" valign="center"><strong>City :</strong></td> <td align="left" valign="center"><input style="WIDTH: 205px; HEIGHT: 22px" size="26" name="city" /></td> </tr> <tr> <td align="right" valign="center"><strong><font color="#ff0000">*</font>&nbsp;Phone No :</strong></td> <td align="left" valign="center"><input style="WIDTH: 168px; HEIGHT: 22px" size="21" name="phonenumber" /></td> </tr> <tr> <td align="right" valign="center"><strong><font color="#ff0000">*</font>&nbsp;Email :</strong></td> <td align="left" valign="center"><input style="WIDTH: 207px; HEIGHT: 22px" size="26" name="email" /></td>

Page 173: 241254 Web Technology Lab Manual

</tr> <tr> <td align="right" valign="center"><strong><font color="#ff0000">*</font>&nbsp;Your Message :</strong></td> <td align="left" valign="center"><textarea style="WIDTH: 346px; HEIGHT: 158px" name="message" rows="8" cols="37"></textarea></td> </tr> <tr> <td valign="center" align="right"></td> <td valign="center" align="left"><input type="submit" value="Send" name="submit" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="reset" value="Clear" name="reset" /></td> </tr> <tr> <td valign="center" align="right"></td> <td valign="center" align="left" height="15" ></td> </tr> <tr> <td align="right" valign="center"></td> <td align="left" valign="center">Fields marked <font color="#ff0000">*</font> are mandatory</td> </tr> </table> </form> <?php}?> </body></html>

Page 174: 241254 Web Technology Lab Manual

Sample output:

RESULT:

Thus the Php application has been developed and executed successfully.