Вы находитесь на странице: 1из 762

IT1451 – WEB TECHNOLOGY

8TH SEMESTER – INFORMATION TECHNOLOGY

UNIT – 1 NOTES

P.Kumar, Rajalakshmi Engineering COllege 1


History of the Internet and World Wide
Web

Outline
History of the Internet
Personal Computing
History of the World Wide Web
World Wide Web Consortium (W3C)

P.Kumar, Rajalakshmi Engineering COllege 2


History of the Internet

• ARPANET
– Implemented in late 1960’s by ARPA (Advanced Research
Projects Agency of DOD)
– Networked computer systems of a dozen universities and
institutions with 56KB communications lines
– Grandparent of today’s Internet
– Intended to allow computers to be shared
– Became clear that key benefit was allowing fast
communication between researchers – electronic-mail
(email)

P.Kumar, Rajalakshmi Engineering COllege 3


History of the Internet

• ARPA’s goals
– Allow multiple users to send and receive info at same time
– Network operated packet switching technique
• Digital data sent in small packages called packets
• Packets contained data, address info, error-control info and
sequencing info
• Greatly reduced transmission costs of dedicated communications
lines
– Network designed to be operated without centralized control
• If portion of network fails, remaining portions still able to route
packets

P.Kumar, Rajalakshmi Engineering COllege 4


History of the Internet

• Transmission Control Protocol (TCP)


– Name of protocols for communicating over ARPAnet
– Ensured that messages were properly routed and that they arrived
intact
• Organizations implemented own networks
– Used both for intra-organization and communication

P.Kumar, Rajalakshmi Engineering COllege 5


History of the Internet

• Huge variety of networking hardware and software


appeared
– ARPA achieved inter-communication between all platforms with
development of the IP
• Internetworking Protocol
• Current architecture of Internet
– Combined set of protocols called TCP/IP
• The Internet
– Limited to universities and research institutions
– Military became big user
– Next, government decided to access Internet for commercial
purposes

P.Kumar, Rajalakshmi Engineering COllege 6


History of the Internet

• Internet traffic grew


– Businesses spent heavily to improve Internet
• Better service their clients
– Fierce competition among communications carriers and hardware
and software suppliers
– Result
• Bandwidth (info carrying capacity) of Internet increased
tremendously
• Costs plummeted

P.Kumar, Rajalakshmi Engineering COllege 7


History of the World Wide Web

• WWW
– Allows computer users to locate and view multimedia-based
documents
– Introduced in 1990 by Tim Berners-Lee
• Internet today
– Mixes computing and communications technologies
– Makes information constantly and instantly available to
anyone with a connection

P.Kumar, Rajalakshmi Engineering COllege 8


World Wide Web Consortium (W3C)

• W3C
– Founded in 1994 by Tim Berners-Lee
• Devoted to developing non-proprietary and interoperable
technologies for the World Wide Web and making the Web
universally accessible
– Standardization
• W3C Recommendations: technologies standardized by W3C
– include Extensible HyperText Markup Language (XHTML),
Cascading Style Sheets (CSS) and the Extensible Markup
Language (XML)
• Document must pass through Working Draft, Candidate
Recommendation and Proposed Recommendation phases before
considered for W3C Recommendation

P.Kumar, Rajalakshmi Engineering COllege 9


Protocols
 Protocols are agreed
formats for transmitting
data between devices
 The protocol determines:
 The error checking
required
 Data compression
method used
 The way the end of a
message is signaled T
 The way the device
indicates that it has
received the message
P.Kumar, Rajalakshmi Engineering COllege 10
Internet Protocols
 There are many protocols used by the
Internet and the WWW, including
 TCP/IP
 HTTP
 FTP
 Electronic mail protocols
 IMAP
 POP

P.Kumar, Rajalakshmi Engineering COllege 11


TCP/IP
 The Internet uses two main protocols (developed
by Vicent Cerf and Robert Kahn)
 Transmission control protocol (TCP)
 Controls disassembly of message into packets at the origin
 Reassembles at the destination
 Internet protocol (IP)
 Specifies the addressing details for each packet
 Each packet is labeled with its origin and destination

P.Kumar, Rajalakshmi Engineering COllege 12


Hypertext Transfer Protocol (HTTP)
 The hypertext transfer protocol (HTTP) was
developed by Tim Berners-Lee in 1991
 HTTP was designed to transfer pages between
machines
 The client (or Web browser) makes a request for
a given page and the Server is responsible for
finding it and returning it to the client

P.Kumar, Rajalakshmi Engineering COllege 13


Hypertext Transfer Protocol (HTTP)
 The browser connects and requests a page from the server
 The server reads the page from the file system, sends it to
the client and terminates the connection

Request sent to Web server

Client Web Server

Response sent with files (one for each


Web page, image, sound clip etc.)
P.Kumar, Rajalakshmi Engineering COllege 14
Electronic Mail Protocols
 Electronic mail uses the client/server model
 The organisation has an email server
devoted to handling email
 Stores and forwards email messages
 Individuals use email client software to
read and send email (e.g. Microsoft
Outlook, or Netscape Messenger)
P.Kumar, Rajalakshmi Engineering COllege 15
Electronic Mail Protocols Cont’d
 Simple Mail Transfer Protocol (SMTP)
 Specifies format of mail messages
 Post Office Protocol (POP)
 tells the email server to:
 Send mail to the user’s computer and delete it
from the server
 Send mail to the user’s computer and do not delete
it from the server
 Ask whether new mail has arrived

P.Kumar, Rajalakshmi Engineering COllege 16


Electronic Mail Protocols Cont’d
 Interactive Mail Access Protocol (IMAP)
 Newer than POP, provides similar functions
with additional features
 e.g. can send specific messages to the client rather
than all the messages
 A user can view email message headers and the
sender’s name before downloading the entire
message
 Allows users to delete and search mailboxes
held on the email server
P.Kumar, Rajalakshmi Engineering COllege 17
Electronic Mail Protocols Cont’d
 The disadvantage of POP
 You can only access messages from one PC
 The disadvantage of IMAP
 Since email is stored on the email server,
there is a need for more and more expensive
(high speed) storage space

P.Kumar, Rajalakshmi Engineering COllege 18


MIME
 MIME - Multi-purpose Internet Mail
Extensions
 The MIME protocol lets SMTP transmit
multimedia files including voice, audio,
and binary data across TCP/IP networks.

P.Kumar, Rajalakshmi Engineering COllege 19


Introduction to HyperText Markup
Language 4 (HTML 4)

Outline
Introduction
Markup Languages
Editing HTML
Common Tags
Headers
Text Styling
Linking
Images
Formatting Text With <FONT>
Special Characters, Horizontal Rules and
More Line Breaks

P.Kumar, Rajalakshmi Engineering COllege 20


Introduction
• HTML
– HyperText Markup Language
– HTML is a language for describing web pages.
– Not a procedural programming language like C,
Fortran, Cobol or Pascal
– Markup language
• Identify elements of a page so that a browser can render that
page on your computer screen
• Presentation of a document vs. structure
• Hypertext Transfer Protocol (HTTP) is the
communication protocol used by the Internet to
transfer hypertext documents.
P.Kumar, Rajalakshmi Engineering COllege 21
Basic Definitions
• Web Page: A web page is a document or resource of information that
is suitable for the World Wide Web and can be accessed through a web
browser.
• Website: A collection of pages on the World Wide Web that are
accessible from the same URL and typically residing on the same
server
• Browser: A web browser is a software application for retrieving,
presenting, and traversing information resources on the World Wide
Web
• URL: Uniform Resource Locator, the unique address which identifies
a resource on the Internet for routing purposes
• HTTP: A protocol to transfer hypertext requests and information
between servers and browsers
• Hypertext: Hypertext is text, displayed on a computer, with references
(hyperlinks) to other text that the reader can immediately follow,
usually by a mouse
• Web server: software that delivers Web pages and other documents to
browsers using the HTTP protocol
P.Kumar, Rajalakshmi Engineering COllege 22
Markup Languages
• Markup language
– Used to format text and information
• HTML
– Marked up with elements, delineated by tags
– Tags: keywords contained in pairs of angle brackets
• HTML tags
– Not case sensitive
– Good practice to keep all the letters in one case
• Forgetting to close tags is a syntax error

P.Kumar, Rajalakshmi Engineering COllege 23


Editing HTML
• HTML files or documents
– Written in source-code form using text editor
– Notepad: Start-Programs-Accessories

• HTML files
– .htm or .html extensions
– Name your files to describe their functionality
– File name of your home page should be index.html
• Errors in HTML
– Usually not fatal

P.Kumar, Rajalakshmi Engineering COllege 24


Common Tags
• Always include the <HTML>…</HTML> tags
• Comments placed inside <!--…--> tags
• HTML documents
– HEAD section
• Info about the document
• Info in header not generally rendered in display window
• TITLE element names your Web page
– BODY section
• Page content
• Includes text, images, links, forms, etc.
• Elements include backgrounds, link colors and font faces
• P element forms a paragraph, blank line before and after

P.Kumar, Rajalakshmi Engineering COllege 25


1 <HTML>
2 Outline
3 <!-- Fig. 3.1: main.html -->
4 <!-- Our first Web page -->
1. HEAD section
5
6 <HEAD>
1.1 TITLE element
7 <TITLE>Internet and WWW How to Program - Welcome</TITLE>
8 </HEAD> 2. BODY section
9 2.1 P element
10 <BODY>
11
12 <P>Welcome to Our Web Site!</P>
13
14 </BODY>
15 </HTML>

P.Kumar, Rajalakshmi Engineering COllege 26


Headers
• Headers
– Simple form of text formatting
– Vary text size based on the header’s “level”
– Actual size of text of header element is selected by
browser
– Can vary significantly between browsers
• CENTER element
– Centers material horizontally
– Most elements are left adjusted by default

P.Kumar, Rajalakshmi Engineering COllege 27


1 <HTML>
2
3 <!-- Fig. 3.2: header.html -->
Outline
4 <!-- HTML headers -->
5 1. Varying header
6 <HEAD>
sizes
7 <TITLE>Internet and WWW How to Program - Headers</TITLE>
8 </HEAD> 1.1 Level 1 is the largest,
9 level 6 is the smallest
10 <BODY>
11
12 <!-- Centers everything in the CENTER element -->
13 <CENTER>
14 <H1>Level 1 Header</H1> <!-- Level 1 header -->
15 <H2>Level 2 header</H2> <!-- Level 2 header -->
16 <H3>Level 3 header</H3> <!-- Level 3 header -->
17 <H4>Level 4 header</H4> <!-- Level 4 header -->
18 <H5>Level 5 header</H5> <!-- Level 5 header -->
19 <H6>Level 6 header</H6> <!-- Level 6 header -->
20 </CENTER>
21
22 </BODY>
23 </HTML>

P.Kumar, Rajalakshmi Engineering COllege 28


Header elements H1 through H6

P.Kumar, Rajalakshmi Engineering COllege 29


Text Styling
• Underline style
– <U>…</U>
• Align elements with ALIGN attribute
– right, left or center
• Close nested tags in the reverse order from which they
were opened
• Emphasis (italics) style
– <EM>…</EM>
• Strong (bold) style
– <STRONG>…</STRONG>
• <B> and <I> tags deprecated
– Overstep boundary between content and presentation

P.Kumar, Rajalakshmi Engineering COllege 30


1 <HTML>
2 Outline
3 <!-- Fig. 3.3: main.html -->
4 <!-- Stylizing your text -->
5 1. EM, STRONG, and U
6 <HEAD> tags
7 <TITLE>Internet and WWW How to Program - Welcome</TITLE> 1.1 Close nested tags in
8 </HEAD> reverse order from
9 which they were
10 <BODY> opened
11 <H1 ALIGN = "center"><U>Welcome to Our Web Site!</U></H1>
12
13 <P>We have designed this site to teach
2. Page rendered by
14 about the wonders of <EM>HTML</EM>. We have been using browser
15 <EM>HTML</EM> since <U>version<STRONG> 2.0</STRONG></U>,
16 and we enjoy the features that have been added recently. It
17 seems only a short time ago that we read our first <EM>HTML</EM>
18 book. Soon you will know about many of the great new features
19 of HTML 4.0.</P>
20
21 <H2 ALIGN = "center">Have Fun With the Site!</H2>
22
23 </BODY>
24 </HTML>

P.Kumar, Rajalakshmi Engineering COllege 31


Stylizing text on Web pages

P.Kumar, Rajalakshmi Engineering COllege 32


Linking
• Links inserted using the A (anchor) element
– Requires HREF attribute
• HREF specifies the URL you would like to link to
– <A HREF = “address”>…</A>
– Can link to email addresses, using
<A HREF = “mailto: emailaddress”>…</A>
– Note quotation mark placement

P.Kumar, Rajalakshmi Engineering COllege 33


1 <HTML>
2 Outline
3 <!-- Fig. 3.4: links.html -->
4 <!-- Introduction to hyperlinks -->
5 1. Anchor element
6 <HEAD> 1.1 HREF attribute
7 <TITLE>Internet and WWW How to Program - Links</TITLE>
8 </HEAD>
9
10 <BODY>
11
12 <CENTER>
13 <H2>Here are my favorite Internet Search Engines</H2>
14 <P><STRONG>Click on the Search Engine address to go to that
15 page.</STRONG></P>
16
17 <!-- Hyperlink form: <A HREF = "address"> -->
18 <P>Yahoo: <A HREF = "http://www.yahoo.com">
19 http://www.yahoo.com</A></P>
20
21 <P>AltaVista: <A HREF = "http://www.altavista.com">
22 http://www.altavista.com</A></P>
23
24 <P>Ask Jeeves: <A HREF = "http://www.askjeeves.com">
25 http://www.askjeeves.com</A></P>
26
27 <P>WebCrawler: <A HREF = "http://www.webcrawler.com">
28 http://www.webcrawler.com</A></P>
29 </CENTER>
30
31 </BODY>
P.Kumar, Rajalakshmi Engineering COllege 34
32 </HTML>
Linking to other Web pages

P.Kumar, Rajalakshmi Engineering COllege 35


1 <HTML>
2 Outline
3 <!-- Fig. 3.5: contact.html -->
4 <!-- Adding email hyperlinks -->
5 1. Anchor element
6 <HEAD> 1.1 mailto link
7 <TITLE>Internet and WWW How to Program - Contact Page</TITLE>
8 </HEAD>
9 2. Page rendered by
10 <BODY> browser
11
12 <!-- The correct form for hyperlinking to an email address -->
13 <!-- is <A HREF = "mailto:address"></A> -->
14 <P>My email address is <A HREF = "mailto:deitel@deitel.com">
15 deitel@deitel.com</A>. Click on the address and your browser
16 will open an email message and address it to me.
17 </P>
18
19 </BODY>
20 </HTML>

P.Kumar, Rajalakshmi Engineering COllege 36


Images (II)
• Images as anchors
• Background color
– Preset colors (white, black, blue, red, etc.)
– Hexadecimal code
• First two characters for amount of red
• Second two characters for amount of green
• Last two characters for amount of blue
• 00 is the weakest a color can get
• FF is the strongest a color can get
• Ex. black = #000000

P.Kumar, Rajalakshmi Engineering COllege 37


Images
• Image background
– <BODY BACKGROUND = “background”>
– Image does not need to be large as browser tiles image across and
down the screen
• Pixel
– Stands for “picture element”
– Each pixel represents one addressable dot of color on the screen
• Insert image into page
– Use <IMG> tag
• Attributes:
– SRC = “location”
– HEIGHT (in pixels)
– WIDTH (in pixels)
– BORDER (black by default)
– ALT (text description for browsers that have images turned off or
cannot view images)
P.Kumar, Rajalakshmi Engineering COllege 38
1 <HTML>
2 Outline
3 <!-- Fig. 3.6: picture.html -->
4 <!-- Adding images with HTML -->
5 1.1 Background image
6 <HEAD> 1.2 IMG element
7 <TITLE>Internet and WWW How to Program - Welcome</TITLE>
1.3 IMG attributes
8 </HEAD>
9
10 <BODY BACKGROUND = "background.gif"> 2. Page rendered by
11
browser
12 <CENTER>
13 <!-- Format for entering images: <IMG SRC = "name"> -->
14 <IMG SRC = "deitel.gif" BORDER = "1" HEIGHT = "144"
15 WIDTH = "200" ALT = "Harvey and Paul Deitel">
16 </CENTER>
17
18 </BODY>
19 </HTML>

P.Kumar, Rajalakshmi Engineering COllege 39


1 <HTML>
2 Outline
3 <!-- Fig. 3.7: navigationbar.html -->
4 <!-- Using images as link anchors -->
5 1. Images as anchors
6 <HEAD> 1.1 Format for value
7 <TITLE>Internet and WWW How to Program - Nav Bar</TITLE>
for SRC attribute
8 </HEAD>
9
10 <BODY BGCOLOR = "#CDCDCD"> 2. BR element
11 <CENTER>
12
13 <A HREF = "main.html">
14 <IMG SRC = "buttons/about.jpg" WIDTH = "65" HEIGHT = "50"
15 BORDER = "0" ALT = "Main Page"></A><BR>
16
17 <A HREF = "links.html">
18 <IMG SRC = "buttons/links.jpg" WIDTH = "65" HEIGHT = "50"
19 BORDER = "0" ALT = "Links Page"></A><BR>
20
21 <A HREF = "list.html">
22 <IMG SRC = "buttons/list.jpg" WIDTH = "65" HEIGHT = "50"
23 BORDER = "0" ALT = "List Example Page"></A><BR>
24
25 <A HREF = "contact.html">
26 <IMG SRC = "buttons/contact.jpg" WIDTH = "65" HEIGHT = "50"
27 BORDER = "0" ALT = "Contact Page"></A><BR>
28
29 <A HREF = "header.html">
30 <IMG SRC = "buttons/header.jpg" WIDTH = "65" HEIGHT = "50"
P.Kumar, Rajalakshmi Engineering COllege 40
31 BORDER = "0" ALT = "Header Page"></A><BR>
32 Outline
33 <A HREF = "table.html">
34 <IMG SRC = "buttons/table.jpg" WIDTH = "65" HEIGHT = "50"
3. Page rendered by
35 BORDER = "0" ALT = "Table Page"></A><BR>
browser
36
37 <A HREF = "form.html">
38 <IMG SRC = "buttons/form.jpg" WIDTH = "65" HEIGHT = "50"
39 BORDER = "0" ALT = "Feedback Form"></A><BR>
40 </CENTER>
41
42 </BODY>
43 </HTML>

P.Kumar, Rajalakshmi Engineering COllege 41


Using images as link anchors

P.Kumar, Rajalakshmi Engineering COllege 42


Formatting Text With <FONT>

• FONT element
– Add color and formatting to text
– FONT attributes:
• COLOR
– Preset or hex color code
– Value in quotation marks
– Note: you can set font color for whole document using
TEXT attribute in BODY element

P.Kumar, Rajalakshmi Engineering COllege 43


Formatting Text With <FONT> (II)
• SIZE
– To make text larger, set SIZE = “+x”
– To make text smaller, set SIZE = “-x”
– x is the number of font point sizes
• FACE
– Font of the text you are formatting
– Be careful to use common fonts like Times, Arial, Courier
and Helvetica
– Browser will display default if unable to display specified
font
• Example
<FONT COLOR = “red” SIZE = “+1” FACE =
“Arial”>…</FONT>

P.Kumar, Rajalakshmi Engineering COllege 44


1<HTML>
2 Outline
3<!-- Fig. 3.8: main.html -->
4<!-- Formatting text size and color -->
5 1. FONT tag
6<HEAD> 1.1 FONT attributes
7<TITLE>Internet and WWW How to Program - Welcome</TITLE>
8</HEAD>
9
10<BODY>
11
12<H1 ALIGN = "center"><U>Welcome to Our Web Site!</U></H1>
13
14<!-- Font tags change the formatting of text they enclose -->
15<P><FONT COLOR = "red" SIZE = "+1" FACE = "Arial">We have
16designed this site to teach about the wonders of
17<EM>HTML</EM>.</FONT>
18
19<FONT COLOR = "purple" SIZE = "+2" FACE = "Verdana">We have been
20using <EM>HTML</EM> since <U>version<STRONG> 2.0</STRONG></U>,
21and we enjoy the features that have been added recently.</FONT>
22
23<FONT COLOR = "blue" SIZE = "+1" FACE = "Helvetica">It
24seems only a short time ago that we read our first <EM>HTML</EM>
25book.</FONT>
26
27<FONT COLOR = "green" SIZE = "+2" FACE = "Times">Soon you will
28know about many of the great new feature of HTML 4.0.</FONT></P>
29
30<H2 ALIGN = "center">Have Fun With the Site!</H2></P>
31
P.Kumar, Rajalakshmi Engineering COllege 45
32</BODY>
33</HTML>
Using the FONT element to format text

P.Kumar, Rajalakshmi Engineering COllege 46


Special Characters, Horizontal Rules and
More Line Breaks
• Special characters
– Inserted in code form
– Format always &code;
• Ex. &amp;
– Insert an ampersand
– Codes often abbreviated forms of the character
– Codes can be in hex form
• Ex. &#38; to insert an ampersand
• Strikethrough with DEL element
• Superscript: SUP element
• Subscript: SUB element
P.Kumar, Rajalakshmi Engineering COllege 47
1 <HTML>
2 Outline
3 <!-- Fig. 3.9: contact.html -->
4 <!-- Inserting special characters -->
5 1. Special characters
6 <HEAD>
7 <TITLE>Internet and WWW How to Program - Contact Page</TITLE>
8 </HEAD>
2. Strikethrough
9
10 <BODY> 3. Superscript
11
12 <!-- Special characters are entered using the form &code; -->
13 <P>My email address is <A HREF = "mailto:deitel@deitel.com"> 4. Subscript
14 deitel@deitel.com</A>. Click on the address and your browser
15 will automatically open an email message and address it to my
16 address.</P>
17
18 <P>All information on this site is <STRONG>&copy;</STRONG>
19 Deitel <STRONG>&amp;</STRONG> Associates, 1999.</P>
20
21 <!-- Text can be struck out with a set of <DEL>...</DEL> -->
22 <!-- tags, it can be set in subscript with <SUB>...</SUB>, -->
23 <!-- and it can be set into superscript with <SUP...</SUP> -->
24 <DEL><P>You may copy up to 3.14 x 10<SUP>2</SUP> characters
25 worth of information from this site.</DEL><BR> Just make sure
26 you <SUB>do not copy more information</SUB> than is allowable.
27
28 <P>No permission is needed if you only need to use <STRONG>
29 &lt; &frac14;</STRONG> of the information presented here.</P>
30
P.Kumar, Rajalakshmi Engineering COllege 48
31 </BODY>
32 </HTML>
Inserting special characters into HTML

P.Kumar, Rajalakshmi Engineering COllege 49


Special Characters, Horizontal Rules and
More Line Breaks (II)
• Horizontal rule
– <HR> tag
– Inserts a line break directly below it
– HR attributes:
• WIDTH
– Adjusts the width of the rule
– Either a number (in pixels) or a percentage
• SIZE
– Determines the height of the horizontal rule
– In pixels
• ALIGN
– Either left, right or center
• NOSHADE
– Eliminates default shading effect and displays horizontal
rule as a solid-color bar
P.Kumar, Rajalakshmi Engineering COllege 50
1<HTML>
2 Outline
3<!-- Fig. 3.10: header.html -->
4<!-- Line breaks and horizontal rules -->
5 1. Horizontal rules
6<HEAD> 1.1 HR attributes
7<TITLE>Internet and WWW How to Program - Horizontal Rule</TITLE>
8</HEAD>
9
10<BODY>
11<!-- Horizontal rules as inserted using the format: -->
12<!-- <HR WIDTH = ".." SIZE = ".." ALIGN = ".."> -->
13<HR WIDTH = "25%" SIZE = 1>
14<HR WIDTH = "25%" SIZE = 2>
15<HR WIDTH = "25%" SIZE = 3>
16
17<P ALIGN = "left"><STRONG>Size:</STRONG>4
18<STRONG>Width:</STRONG>75%
19<HR WIDTH = "75%" SIZE = "4" ALIGN = "left">
20
21<P ALIGN = "right"><STRONG>Size:</STRONG>12
22<STRONG>Width:</STRONG>25%
23<HR WIDTH = "25%" SIZE = "12" ALIGN = "right">
24
25<P ALIGN = "center"><STRONG>Size:</STRONG>8
26<STRONG>Width:</STRONG>50%
27<STRONG><EM>No shade...</EM></STRONG>
28<HR NOSHADE WIDTH = "50%" SIZE = "8" ALIGN = "center">
29
P.Kumar, Rajalakshmi Engineering COllege 51
30</BODY>
31</HTML>
Using horizontal rules

P.Kumar, Rajalakshmi Engineering COllege 52


Intermediate HTML 4

Outline
Introduction
Unordered Lists
Nested and Ordered Lists
Basic HTML Tables
Intermediate HTML Tables and Formatting
Basic HTML Forms
More Complex HTML Forms
Internal Linking
Creating and Using Image Maps
<META> Tags
<FRAMESET> Tag
Nested <FRAMESET> Tags

P.Kumar, Rajalakshmi Engineering COllege 53


Introduction

• In this Chapter
– Lists
– Tables
– Internal linking
– Image maps
– Frames

P.Kumar, Rajalakshmi Engineering COllege 54


Unordered Lists
• Unordered list element
– Creates a list in which every line begins with a bullet
mark
– <UL>…</UL> tags
– Each item in unordered list inserted with the <LI> (list
item) tag
• Closing </LI> tag optional

P.Kumar, Rajalakshmi Engineering COllege 55


1<HTML>
3<!-- Fig. 4.1: links.html --> Outline
4<!-- Unordered Lists -->
5
6<HEAD> 1. Unordered list
7<TITLE>Internet and WWW How to Program - Links</TITLE> 1.1 List items
8</HEAD>
9
10<BODY>
11
12<CENTER>
13<H2>Here are my favorite Internet Search Engines</H2>
14<P><STRONG>Click on the Search Engine address to go to that
15page.</STRONG></P>
16
17<!-- <UL> creates a new unordered (bullet) list -->
18<!-- <LI> inserts a new entry into the list -->
19<UL>
20<LI>Yahoo: <A HREF = "http://www.yahoo.com">
21http://www.yahoo.com</A></LI>
22
23<LI>Alta Vista: <A HREF = "http://www.altavista.com">
24http://www.alta-vista.com</A></LI>
25
26<LI>Ask Jeeves: <A HREF = "http://www.askjeeves.com">
27http://www.askjeeves.com</A></LI>
28
29<LI>WebCrawler: <A HREF = "http://www.webcrawler.com">
30http://www.webcrawler.com</A></LI>
31</UL>
32</CENTER> P.Kumar, Rajalakshmi Engineering COllege 56
33</BODY>
34</HTML>
Unordered lists with HTML

P.Kumar, Rajalakshmi Engineering COllege 57


Nested and Ordered Lists
• Nested list
– Contained in another list element
– Nesting the new list inside the original
• Indents list one level and changes the bullet type to reflect the
nesting
• Browsers
– Insert a line of whitespace after every closed list
• Indent each level of a nested list
– Makes the code easier to edit and debug

P.Kumar, Rajalakshmi Engineering COllege 58


1 <HTML>
2 Outline
3 <!-- Fig. 4.2: list.html -->
4 <!-- Advanced Lists: nested and ordered -->
5 1. Nested lists
6 <HEAD> 1.1 Three levels of
7 <TITLE>Internet and WWW How to Program - List</TITLE>
nesting
8 </HEAD>
9 1.2 Close </UL> tags in
10 <BODY> appropriate places
11
12 <CENTER>
13 <H2><U>The Best Features of the Internet</U></H2>
14 </CENTER>
15
16 <UL>
17 <LI>You can meet new people from countries around
18 the world.</LI>
19 <LI>You have access to new media as it becomes public:</LI>
20
21 <!-- This starts a nested list, which uses a modified -->
22 <!-- bullet. The list ends when you close the <UL> tag -->
23 <UL>
24 <LI>New games</LI>
25 <LI>New applications </LI>
26
27 <!-- Another nested list, there is no nesting limit -->
28 <UL>
29 <LI>For business</LI>
30 <LI>For pleasure</LI>
P.Kumar, Rajalakshmi Engineering COllege 59
31 </UL> <!-- This ends the double nested list -->
32 <LI>Around the clock news</LI> Outline
33 <LI>Search engines</LI>
34 <LI>Shopping</LI>
35 <LI>Programming</LI> 2. Ordered list
36 <UL>
37 <LI>HTML</LI>
38 <LI>Java</LI>
39 <LI>Dynamic HTML</LI>
40 <LI>Scripts</LI>
41 <LI>New languages</LI>
42 </UL>
43 </UL> <!-- This ends the first level nested list -->
44 <LI>Links</LI>
45 <LI>Keeping in touch with old friends</LI>
46 <LI>It is the technology of the future!</LI>
47 </UL> <!-- This ends the primary unordered list -->
48
49 <BR><CENTER><H2>My 3 Favorite <EM>CEO's</EM></H2></CENTER>
50
51 <!-- Ordered lists are constructed in the same way as -->
52 <!-- unordered lists, except their starting tag is <OL> -->
53 <OL>
54 <LI>Bill Gates</LI>
55 <LI>Steve Jobs</LI>
56 <LI>Michael Dell</LI>
57 </OL>
58
59 </BODY>
60 </HTML>
P.Kumar, Rajalakshmi Engineering COllege 60
Nested and ordered lists in HTML

P.Kumar, Rajalakshmi Engineering COllege 61


Nested and Ordered Lists (II)
• Ordered list element
– <OL>…</OL> tags
– By default, ordered lists use decimal sequence numbers
• (1, 2, 3, …)
– To change sequence type, use TYPE attribute in <OL> opening tag
• TYPE = “1” (default)
– Decimal sequence (1, 2, 3, …)
• TYPE = “I”
– Uppercase Roman numerals (I, II, III, …)
• TYPE = “i”
– Lowercase Roman numerals (i, ii, iii, …)
• TYPE = “A”
– Uppercase alphabetical (A, B, C, …)
• TYPE = “a”
– Lowercase alphabetical (a, b, c, …)
P.Kumar, Rajalakshmi Engineering COllege 62
1<HTML>
2 Outline
3<!-- Fig. 4.3: list.html -->
4<!-- Different Types of Ordered Lists -->
5 1. OL element
6<HEAD> 1.1 TYPE attribute
7<TITLE>Internet and WWW How to Program - List</TITLE>
8</HEAD>
9
10<BODY>
11
12<CENTER>
13<H2>Web Site Outline</H2>
14</CENTER>
15
16<!-- Change the character style by specifying it in -->
17<!-- <OL TYPE = "style"> OR <LI TYPE = "style"> as -->
18<!-- decimal=1, uppercase Roman=I, lowercase Roman=i -->
19<!-- uppercase Latin=A, lowercase Latin=a -->
20<OL>
21<LI>Home page</LI>
22<LI>Links page</LI>
23 <OL TYPE = "I">
24 <LI>Links to search engines</LI>
25 <LI>Links to information sites</LI>
26 <OL TYPE = "A">
27 <LI>News sites</LI>
28 <OL>
29 <LI TYPE = "i">TV based</LI>
30 <OL TYPE = "a">
P.Kumar, Rajalakshmi Engineering COllege 63
31 <LI>CNN</LI>
32 <LI>Headline News</LI> Outline
33 </OL>
34 <LI TYPE = "i">Text based</LI>
35 <OL TYPE = "a">
36 <LI>New York Times</LI>
37 <LI>Washington Post</LI>
38 </OL>
39 </OL>
40 <LI>Stock sites</LI>
41 </OL>
42 <LI>Links to "fun" sites</LI>
43 </OL>
44 <LI>Feedback page</LI>
45 <LI>Contact page</LI>
46 <LI>HTML Example Pages</LI>
47 </OL>
48
49 </BODY>
50 </HTML>

P.Kumar, Rajalakshmi Engineering COllege 64


Different types of ordered lists

P.Kumar, Rajalakshmi Engineering COllege 65


Basic HTML Tables
• Tables
– Organize data into rows and columns
– All tags and text that apply to the table go inside
<TABLE>…</TABLE> tags
– TABLE element
• Attributes
– BORDER lets you set the width of the table’s border in
pixels
– ALIGN: left, right or center
– WIDTH: pixels (absolute) or a percentage
• CAPTION element is inserted directly above the table in the
browser window
– Helps text-based browsers interpret table data

P.Kumar, Rajalakshmi Engineering COllege 66


Basic HTML tables (II)
– TABLE element (cont.)
• THEAD element
– Header info
– For example, titles of table and column headers
• TR element
– Table row element used for formatting the cells of
individual rows
• TBODY element
– Used for formatting and grouping purposes
• Smallest area of the table we are able to format is data cells
– Two types of data cells
» In the header: <TH>…</TH> suitable for titles and
column headings
» In the table body: <TD>…</TD>
– Aligned left by default

P.Kumar, Rajalakshmi Engineering COllege 67


1 <HTML>
2 Outline
3 <!-- Fig. 4.4: table.html -->
4 <!-- Basic table design -->
5 1. TABLE element
6 <HEAD> 1.1 BORDER attribute
7 <TITLE>Internet and WWW How to Program - Tables</TITLE>
1.2 CAPTION element
8 </HEAD>
9
1.3 THEAD element
10 <BODY> 1.4 TH element
11
12 <CENTER><H2>Table Example Page</H2></CENTER>
13
14 <!-- The <TABLE> tag opens a new table and lets you put in -->
15 <!-- design options and instructions -->
16 <TABLE BORDER = "1" ALIGN = "center" WIDTH = "40%">
17
18 <!-- Use the <CAPTION> tag to summarize the table's contents -->
19 <!-- (this helps the visually impaired) -->
20 <CAPTION>Here is a small sample table.</CAPTION>
21
22 <!-- The <THEAD> is the first (non-scrolling) horizontal -->
23 <!-- section.Use it to format the table header area. -->
24 <!-- <TH> inserts a header cell and displays bold text -->
25 <THEAD>
26 <TR><TH>This is the head.</TH></TR>
27 </THEAD>
28
29 <!-- All of your important content goes in the <TBODY>. -->
30 <!-- Use this tag to format the entire section -->
31 <!-- <TD> inserts a data cell, withP.Kumar,
regular text
Rajalakshmi Engineering COllege--> 68
32 <TBODY>
33 <TR><TD ALIGN = "center">This is the body.</TD></TR> Outline
34 </TBODY>
35 1.5 TBODY element
36 </TABLE> 1.6 TD element
37
38 </BODY>
2. Page rendered by
39 </HTML>
browser

P.Kumar, Rajalakshmi Engineering COllege 69


Intermediate HTML Tables and Formatting
• COLGROUP element
– Used to group and format columns
• Each COL element
– In the <COLGROUP>…</COLGROUP> tags
– Can format any number of columns (specified by the
SPAN attribute)
• Background color or image
– Add to any row or cell
– Use BGCOLOR and BACKGROUND attributes

P.Kumar, Rajalakshmi Engineering COllege 70


Intermediate HTML Tables and Formatting
(II)
• Possible to make some data cells larger than others
– ROWSPAN attribute inside any data cell
• Value extends the data cell to span the specified number of
cells
– COLSPAN attribute
• Value extends the data cell to span the specified number of
cells
– Modified cells will cover the areas of other cells
• Reduces number of cells in that row or column
• VALIGN attribute
– top, middle, bottom and baseline
– Default is middle

P.Kumar, Rajalakshmi Engineering COllege 71


1<HTML>
2 Outline
3<!-- Fig. 4.5: table.html -->
4<!-- Intermediate table design -->
5
6<HEAD>
7<TITLE>Internet and WWW How to Program - Tables</TITLE>
8</HEAD>
9<BODY>
10
11<H2 ALIGN = "center">Table Example Page</H2>
12
13<TABLE BORDER = "1" ALIGN = "center" WIDTH = "40%">
14 <CAPTION>Here is a small sample table.</CAPTION>
15
16 <THEAD>
17 <TR>
18 <TH>This is the Head.</TH>
19 </TR>
20 </THEAD>
21
22 <TBODY>
23 <TR>
24 <TD ALIGN = "center">This is the Body.</TD>
25 </TR>
26 </TBODY>
27
28</TABLE>
29
30<BR><BR> P.Kumar, Rajalakshmi Engineering COllege 72
30<BR><BR>
31 Outline
32<TABLE BORDER = "1" ALIGN = "center">
33
34 <CAPTION>Here is a more complex sample table.</CAPTION> 1.1 COLGROUP element
35
1.2 COL element
36 <!-- <COLGROUP> and <COL> are used to format entire -->
37 <!-- columns at once. SPAN determines how many columns --> 1.3 ROWSPAN and
38 <!-- the COL tag effects. --> COLSPAN attributes
39 <COLGROUP>
1.4 BGCOLOR attribute
40 <COL ALIGN = "right">
41 <COL SPAN = "4" ALIGN = "center"> 1.5 WIDTH attribute
42 </COLGROUP> 1.6 VALIGN attribute
43
44 <THEAD>
45
46 <!-- ROWSPANs and COLSPANs combine the indicated number -->
47 <!-- of cells vertically or horizontally -->
48 <TR BGCOLOR = "#8888FF">
49 <TH ROWSPAN = "2">
50 <IMG SRC = "deitel.gif" WIDTH = "200" HEIGHT = "144"
51 ALT = "Harvey and Paul Deitel">
52 </TH>
53 <TH COLSPAN = "4" VALIGN = "top">
54 <H1>Camelid comparison</H1><BR>
55 <P>Approximate as of 8/99</P>
56 </TH>
57 </TR>
58
59 <TR BGCOLOR = "khaki" VALIGN = "bottom">
60 <TH># of Humps</TH> P.Kumar, Rajalakshmi Engineering COllege 73
61 <TH>Indigenous region</TH>
62 <TH>Spits?</TH> Outline
63 <TH>Produces Wool?</TH>
64 </TR>
65
66 </THEAD>
67
68 <TBODY>
69
70 <TR>
71 <TH>Camels (bactrian)</TH>
72 <TD>2</TD>
73 <TD>Africa/Asia</TD>
74 <TD ROWSPAN = "2">Llama</TD>
75 <TD ROWSPAN = "2">Llama</TD>
76 </TR>
77
78 <TR>
79 <TH>Llamas</TH>
80 <TD>1</TD>
81 <TD>Andes Mountains</TD>
82 </TR>
83
84 </TBODY>
85 </TABLE>
86
87 </BODY>
88 </HMTL> P.Kumar, Rajalakshmi Engineering COllege 74
A complex table with formatting and color

P.Kumar, Rajalakshmi Engineering COllege 75


Basic HTML Forms
• Forms
– Collect information from people viewing your site
• FORM element
– METHOD attribute indicates the way the Web server will
organize and send you form output
• Web server: machine that processes browser requests
• METHOD = “post” in a form that causes changes to server
data
• METHOD = “get” in a form that does not cause any changes
in server data
– Form data sent to server as an environment variable
• Processed by scripts
– ACTION attribute
• Path to a script (a CGI script written in Perl, C or other
languages)
P.Kumar, Rajalakshmi Engineering COllege 76
Basic HTML Forms (II)
• INPUT element
– Attributes:
• TYPE (required)
– Hidden inputs always have TYPE = “hidden”
– Defines the usage of the INPUT element
» TYPE = “text” inserts a one-line text box
• NAME provides a unique identification for INPUT element
• VALUE indicates the value that the INPUT element sends to
the server upon submission
• SIZE
– For TYPE = “text”, specifies the width of the text
input, measured in characters
• MAXLENGTH
– For TYPE = “text”, specifies the maximum number of
characters that the text input will accept

P.Kumar, Rajalakshmi Engineering COllege 77


Basic HTML Forms (III)
• INPUT element (cont.)
– Include textual identifier adjacent to INPUT element
– 2 types of INPUT elements that should be inserted into
every form:
• TYPE = “submit” inserts a button that submits data to the
server
– VALUE attribute changes the text displayed on the button
(default is “Submit”)
• TYPE = “reset” inserts a button that clears all entries the
user entered into the form
– VALUE attribute changes the text displayed on the button
(default is “Reset”)

P.Kumar, Rajalakshmi Engineering COllege 78


1<HTML>
2 Outline
3<!-- Fig. 4.6: form.html -->
4<!-- Introducing Form Design -->
5 1. FORM element
6<HEAD> 1.1 Specify METHOD
7<TITLE>Internet and WWW How to Program - Forms</TITLE> attribute
8</HEAD>
1.2 Hidden input
9
elements
10<BODY>
11<H2>Feedback Form</H2>
12
13<P>Please fill out this form to help us improve our site.</P>
14
15<!-- This tag starts the form, gives the method of sending -->
16<!-- information and the location of form scripts. -->
17<!-- Hidden inputs give the server non-visual information -->
18<FORM METHOD = "POST" ACTION = "/cgi-bin/formmail">
19
20<INPUT TYPE = "hidden" NAME = "recipient"
21 VALUE = "deitel@deitel.com">
22<INPUT TYPE = "hidden" NAME = "subject"
23 VALUE = "Feedback Form">
24<INPUT TYPE = "hidden" NAME = "redirect"
25 VALUE = "main.html">
26
27<!-- <INPUT type = "text"> inserts a text box -->

P.Kumar, Rajalakshmi Engineering COllege 79


28<P><STRONG>Name:</STRONG>
29<INPUT NAME = "name" TYPE = "text" SIZE = "25"></P> Outline
30
31<!-- Input types "submit" and "reset" insert buttons -->
1.3 Text box INPUT
32<!-- for submitting or clearing the form's contents -->
element
33<INPUT TYPE = "submit" VALUE = "Submit Your Entries">
34<INPUT TYPE = "reset" VALUE = "Clear Your Entries">
1.4 “submit” and
35</FORM>
“reset” INPUT
36
TYPEs
37</BODY>
38</HTML> 2. Page rendered by
browser

P.Kumar, Rajalakshmi Engineering COllege 80


More Complex HTML Forms
• TEXTAREA element
– Inserts a scrollable text box into FORM
– ROWS and COLS attributes specify the number of
character rows and columns
• INPUT element
– TYPE = “password”
– Inserts a text box where data displayed as asterisks
• Actual data submitted to server

P.Kumar, Rajalakshmi Engineering COllege 81


More Complex HTML Forms (II)
• INPUT element (cont.)
– TYPE = “checkbox” creates a checkbox
• Used individually or in groups
• Each checkbox in a group should have same NAME
• Make sure that the checkboxes within a group have different
VALUE attribute values
– Otherwise, browser will cannot distinguish between them
• CHECKED attribute checks boxes initially
– TYPE = “radio”
• Radio buttons similar in function and usage to checkboxes
• Only one radio button in a group can be selected
• CHECKED attribute indicates which radio button is selected
initially

P.Kumar, Rajalakshmi Engineering COllege 82


More Complex Forms (III)
• SELECT element
– Places a selectable list of items inside FORM
• Include NAME attribute
– Add an item to list
• Insert an OPTION element in the <SELECT>…</SELECT>
tags
• Closing OPTION tag optional
– SELECTED attribute applies a default selection to list
– Change the number of list options visible
• Including the SIZE = “x” attribute inside the <SELECT>
tag
• x number of options visible

P.Kumar, Rajalakshmi Engineering COllege 83


1<HTML>
2 Outline
3<!-- Fig. 4.7: form.html -->
4<!-- Form Design Example 2 -->
5 1.1 TEXTAREA element
6<HEAD>
7<TITLE>Internet and WWW How to Program - Forms</TITLE>
8</HEAD>
9
10<BODY>
11<H2>Feedback Form</H2>
12
13<P>Please fill out this form to help us improve our site.</P>
14
15<FORM METHOD = "POST" ACTION = "/cgi-bin/formmail">
16
17<INPUT TYPE = "hidden" NAME = "recipient"
18 VALUE = "deitel@deitel.com">
19<INPUT TYPE = "hidden" NAME = "subject"
20 VALUE = "Feedback Form">
21<INPUT TYPE = "hidden" NAME = "redirect"
22 VALUE = "main.html">
23
24<P><STRONG>Name: </STRONG>
25<INPUT NAME = "name" TYPE = "text" SIZE = "25"></P>
26
27<!-- <TEXTAREA> creates a textbox of the size given -->
28<P><STRONG>Comments:</STRONG>
29<TEXTAREA NAME = "comments" ROWS = "4" COLS = "36"></TEXTAREA>
30</P>
P.Kumar, Rajalakshmi Engineering COllege 84
31
32<!-- <INPUT TYPE = "password"> inserts a textbox whose --> Outline
33<!-- readout will be in *** instead of regular characters -->
34<P><STRONG>Email Address:</STRONG>
35<INPUT NAME = "email" TYPE = "password" SIZE = "25"></P> 1.2 “password” TYPE
36 1.3 “checkbox” TYPE
37<!-- <INPUT TYPE = "checkbox"> creates a checkbox -->
1.4 Checkboxes in
38<P><STRONG>Things you liked:</STRONG><BR>
same group must
39
40Site design
have same NAME,
41<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Design"> but different VALUE
42Links attributes
43<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Links">
44Ease of use
45<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Ease">
46Images
47<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Images">
48Source code
49<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Code">
50</P>
51
52<INPUT TYPE = "submit" VALUE = "Submit Your Entries">
53<INPUT TYPE = "reset" VALUE = "Clear Your Entries">
54</FORM>
55
56</BODY>
57</HTML>

P.Kumar, Rajalakshmi Engineering COllege 85


Form including textareas, password boxes
and checkboxes

P.Kumar, Rajalakshmi Engineering COllege 86


1<HTML>
2
3<!-- Fig. 4.8: form.html -->
Outline
4<!-- Form Design Example 3 -->
5
6<HEAD>
7<TITLE>Internet and WWW How to Program - Forms</TITLE>
8</HEAD>
9
10<BODY>
11<H2>Feedback Form</H2>
12
13<P>Please fill out this form to help us improve our site.</P>
14
15<FORM METHOD = "POST" ACTION = "/cgi-bin/formmail">
16
17<INPUT TYPE = "hidden" NAME = "recipient"
18 VALUE = "deitel@deitel.com">
19<INPUT TYPE = "hidden" NAME = "subject"
20 VALUE = "Feedback Form">
21<INPUT TYPE = "hidden" NAME = "redirect"
22 VALUE = "main.html">
23
24<P><STRONG>Name: </STRONG>
25<INPUT NAME = "name" TYPE = "text" SIZE = "25"></P>
26
27<P><STRONG>Comments:</STRONG>
28<TEXTAREA NAME = "comments" ROWS = "4" COLS = "36"></TEXTAREA>
P.Kumar, Rajalakshmi Engineering COllege 87
29</P>
30
31<P><STRONG>Email Address:</STRONG>
32<INPUT NAME = "email" TYPE = "password" SIZE = "25"></P> Outline
33
34<P><STRONG>Things you liked:</STRONG><BR>
35
1.1 TYPE = “radio”
36Site design creates a radio
37<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Design"> button
38Links 1.2 Only one radio
39<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Links"> button in a group
40Ease of use can be selected
41<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Ease">
1.3 CHECKED attribute
42Images
specifies which
43<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Images">
44Source code
radio button is
45<INPUT NAME = "things" TYPE = "checkbox" VALUE = "Code">
selected by default
46</P>
47
48<!-- <INPUT TYPE="radio"> creates a radio button. The -->
49<!-- difference between radio buttons and checkboxes is -->
50<!-- that only one radio button in a group can be selected -->
51<P><STRONG>How did you get to our site?:</STRONG><BR>
52
53Search engine
54<INPUT NAME = "how get to site" TYPE = "radio"
55 VALUE = "search engine" CHECKED>
56Links from another site
57<INPUT NAME = "how get to site" TYPE = "radio"
58 VALUE = "link">
P.Kumar, Rajalakshmi Engineering COllege 88
59Deitel.com Web site
60<INPUT NAME = "how get to site" TYPE = "radio"
61 VALUE = "deitel.com">
Outline
62Reference in a book
63<INPUT NAME = "how get to site" TYPE = "radio" 1.4 SELECT element
64 VALUE = "book">
65Other 1.5 Create menu items
66<INPUT NAME = "how get to site" TYPE = "radio" with OPTION
67 VALUE = "other"> elements
68</P>
69 1.6 SELECTED attribute
70<!-- The <select> tag presents a drop down menu with --> specifies which
71<!-- choices indicated by the <option> tags --> option is displayed
72<P><STRONG>Rate our site (1-10):</STRONG>
73<SELECT NAME = "rating">
by default
74<OPTION SELECTED>Amazing:-)
75<OPTION>10
76<OPTION>9
77<OPTION>8
78<OPTION>7
79<OPTION>6
80<OPTION>5
81<OPTION>4
82<OPTION>3
83<OPTION>2
84<OPTION>1
85<OPTION>The Pits:-(
86</SELECT></P>
87
88<INPUT TYPE = "submit" VALUE = "Submit Your Entries">
89<INPUT TYPE = "reset" VALUE = "Clear Your Entries">
90</FORM>
92</BODY> P.Kumar, Rajalakshmi Engineering COllege 89
93</HTML>
HTML form including radio buttons and
pulldown lists

P.Kumar, Rajalakshmi Engineering COllege 90


Internal Linking
• Internal linking
– Assign location name to individual point in an HTML
file
– Location name can then be added to the page’s URL
• Link to specific point on the page
– Location marked by including a NAME attribute in an A
(anchor) element
• Ex. <A NAME = “features”></A> in list.html
– URL of location
• Format: page.html#name
• Ex. list.html#features

P.Kumar, Rajalakshmi Engineering COllege 91


1 <HTML>
2 Outline
3 <!-- Fig. 4.9: list.html -->
4 <!-- Internal Linking -->
5 1.1 Create an internal
6 <HEAD> link using the NAME
7 <TITLE>Internet and WWW How to Program - List</TITLE> attribute in an A
8 </HEAD> element
9
10 <BODY>
11
12 <CENTER>
13 <!-- <A NAME = ".."></A> makes an internal hyperlink -->
14 <A NAME = "features"></A>
15 <H2><U>The Best Features of the Internet</U></H2>
16
17 <!-- An internal link's address is "xx.html#linkname" -->
18 <H3><A HREF = "#ceos">Go to <EM>Favorite CEO's</EM></A></H3>
19 </CENTER>
20
21 <UL>
22 <LI>You can meet new people from countries around the world.
23 <LI>You have access to new media as it becomes public:
24 <UL>
25 <LI>New games
26 <LI>New applications
27 <UL>
28 <LI>For Business
29 <LI>For Pleasure
30 </UL> P.Kumar, Rajalakshmi Engineering COllege 92
31 <LI>Around the Clock news
32 <LI>Search Engines Outline
33 <LI>Shopping
34 <LI>Programming
35 <UL> 1.2 Access internal link
36 <LI>HTML using HREF =
37 <LI>Java “#features”
38 <LI>Dynamic HTML
39 <LI>Scripts
40 <LI>New languages
41 </UL>
42 </UL>
43 <LI>Links
44 <LI>Keeping In touch with old friends
45 <LI>It is the technology of the future!
46 </UL><BR><BR>
47
48 <A NAME = "ceos"></A>
49 <CENTER><H2>My 3 Favorite <EM>CEO's</EM></H2>
50 <H3><A HREF = "#features">Go to <EM>Favorite Features</EM></A>
51 </H3></CENTER>
52
53 <OL>
54 <LI>Bill Gates
55 <LI>Steve Jobs
56 <LI>Michael Dell
57 </OL>
58
59 </BODY>
60
61 </HTML> P.Kumar, Rajalakshmi Engineering COllege 93
Using internal hyperlinks to make your page
more navigable

P.Kumar, Rajalakshmi Engineering COllege 94


Creating and Using Image Maps
• Image maps
– Designate certain sections of an image as hotspots
– Use hotspots as anchors for linking
– All elements of image map inside <MAP>…</MAP>
tags
– <MAP> tag requires NAME attribute
• Ex. <MAP NAME = “picture”>
• Hotspots designated with AREA element
– AREA attributes:
• HREF sets the target for the link on that spot
• SHAPE and COORDS set the characteristics of the AREA
• ALT provides alternate textual description
P.Kumar, Rajalakshmi Engineering COllege 95
Creating and Using Image Maps (II)
• AREA element (continued)
– SHAPE = “rect”
• Causes rectangular hotspot to be drawn around the coordinates
given in the COORDS attribute
• COORDS - pairs of numbers corresponding to the x and y axes
– x axis extends horizontally from upper-left corner
– y axis extends vertically from upper-left corner
• Ex. <AREA HREF = “form.html” SHAPE = “rect”
COORDS = “3, 122, 73, 143” ALT = “Go to
the form”>
– Rectangular hotspot with upper-left corner of rectangle at
(3, 122) and lower-right corner at (73, 143)

P.Kumar, Rajalakshmi Engineering COllege 96


Creating and Using Image Maps (III)
• AREA element (continued)
– SHAPE = “poly”
• Causes a hotspot to be created around specified coordinates
• Ex. <AREA HREF = “mailto:deitel@deitel.com”
SHAPE = “poly” COORDS = “28, 22, 24, 68,
46, 114, 84, 111, 99, 56, 86, 13”
ALT = “Email the Deitels”>
– SHAPE = “circle”
• Creates a circular hotspot
• Coordinates of center of circle and radius of circle, in pixels
• Ex. <AREA HREF = “mailto:deitel@deitel.com”
SHAPE = “circle” COORDS = “146, 66, 42”
ALT = “Email the Deitels”>

P.Kumar, Rajalakshmi Engineering COllege 97


Creating and Using Image Maps (IV)

• To use the image map with an IMG element


– Insert the USEMAP = “#name” attribute into the
IMG element
– name - value of the NAME attribute in the MAP element
– Ex. <IMG SRC = "deitel.gif" WIDTH = "200"
HEIGHT="144" BORDER="1" ALT = "Harvey and
Paul Deitel" USEMAP = "#picture">

P.Kumar, Rajalakshmi Engineering COllege 98


1<HTML>
2 Outline
3<!-- Fig. 4.10: picture.html -->
4<!-- Creating and Using Image Maps -->
5 1. MAP element
6<HEAD> 1.1 NAME attribute
7<TITLE>Internet and WWW How to Program - List</TITLE>
1.2 SHAPE = “rect”
8</HEAD>
9 1.3 “rect”COORDS
10<BODY BACKGROUND = "bckgrnd.gif"> 1.4 SHAPE = “poly”
11
12<CENTER>
1.5 “poly” COORDS
13<!-- <MAP> opens and names an image map formatting area -->
14<!-- and to be referenced later -->
15<MAP NAME = "picture">
16
17<!-- The "SHAPE = rect indicates a rectangular area, with -->
18<!-- coordinates of the upper-left and lower-right corners -->
19<AREA HREF = "form.html" SHAPE = "rect"
20 COORDS = "3, 122, 73, 143" ALT = "Go to the form">
21<AREA HREF = "contact.html" SHAPE = "rect"
22 COORDS = "109, 123, 199, 142" ALT = "Go to the contact page">
23<AREA HREF = "main.html" SHAPE = "rect"
24 COORDS = "1, 2, 72, 17" ALT = "Go to the homepage">
25<AREA HREF = "links.html" SHAPE = "rect"
26 COORDS = "155, 0, 199, 18" ALT = "Go to the links page">
27
28<!-- The "SHAPE = polygon" indicates an area of cusotmizable -->
29<!-- shape, with the coordinates of every vertex listed -->
30<AREA HREF = "mailto:deitel@deitel.com"
P.Kumar,SHAPE = Engineering
Rajalakshmi "poly"COllege 99
31 COORDS = "28, 22, 24, 68, 46, 114, 84, 111, 99, 56, 86, 13"
32 ALT = "Email the Deitels"> Outline
33
34<!-- The "SHAPE = circle" indicates a circular area with --> 1.6 SHAPE =
35<!-- center and radius listed --> “circle”
36<AREA HREF = "mailto:deitel@deitel.com" SHAPE = "circle"
1.7 Use image map
37 COORDS = "146, 66, 42" ALT = "Email the Deitels"> with IMG element
38</MAP> via USEMAP attribute
39
40<!-- <IMG SRC=... USEMAP = "#name"> says that the indicated -->
41<!-- image map will be used with this image -->
42<IMG SRC = "deitel.gif" WIDTH = "200" HEIGHT = "144" BORDER = "1"

43 ALT = "Harvey and Paul Deitel" USEMAP = "#picture">


44</CENTER>
45
46</BODY>
47</HTML>

P.Kumar, Rajalakshmi Engineering COllege 100


A picture with links anchored to an image
map

P.Kumar, Rajalakshmi Engineering COllege 101


<META> Tags
• Search engines
– Catalog sites by following links from page to page
– Save identification and classification info

• <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0


Transitional//EN">
– Tells browser that HTML conforms to a
Transitional subset of HTML version 4.0

• META tag
– Main HTML element that interacts with search engines

P.Kumar, Rajalakshmi Engineering COllege 102


<META> Tags (II)
• META tags
– Contain two attributes that should always be used:
– NAME identifies type of META tag
– CONTENT provides info the search engine will catalog
about your site
• CONTENT of a META tag with NAME = “keywords”
– Provides search engines with a list of words that describe
key aspects of your site
• CONTENT of a META tag with NAME = “description”
– Should be 3 to 4 lines
– Used by search engines to catalog and display your site
• META elements
– Not visible to users of the site
– Should be placed inside header section
P.Kumar, Rajalakshmi Engineering COllege 103
1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<HTML> Outline
3
4<!-- Fig. 4.11: main.html -->
5<!-- <META> and <!DOCTYPE> tags --> 1. META tags
6 1.1 NAME =
7<HEAD> “keywords”
8<!-- <META> tags give search engines information they need -->
9<!-- to catalog your site -->
1.2 NAME =
10<META NAME = "keywords" CONTENT = "Webpage, design, HTML, “description”
11 tutorial, personal, help, index, form, contact, feedback,
12 list, links, frame, deitel">
13
14<META NAME = "description" CONTENT = "This Web site will help
15 you learn the basics of HTML and Webpage design through the
16 use of interactive examples and instruction.">
17
18<TITLE>Internet and WWW How to Program - Welcome</TITLE>
19</HEAD>
20
21<BODY>
22
23<H1 ALIGN = "center"><U>Welcome to Our Web Site!</U></H1>
24
25<P><FONT COLOR = "red" SIZE = "+1" FACE = "Arial">We have
26designed this site to teach about the wonders of
27<EM>HTML</EM>.</FONT>
28
29<FONT COLOR = "purple" SIZE = "+2" FACE = "Verdana">We have been
30using <EM>HTML</EM> since <U>version<STRONG> 2.0</STRONG></U>,
P.Kumar, Rajalakshmi Engineering COllege 104
31and we enjoy the features that have been added recently.</FONT>
32 Outline
33<FONT COLOR = "blue" SIZE = "+1" FACE = "Helvetica">It
34seems only a short time ago that we read our first <EM>HTML</EM>
35book.</FONT>
36
37<FONT COLOR = "green" SIZE = "+2" FACE = "Times">Soon you will
38know about many of the great new feature of HTML 4.0.</FONT></P>
39
40<H2 ALIGN = "center">Have Fun With the Site!</H2></P>
41
42</BODY>
43</HTML>

P.Kumar, Rajalakshmi Engineering COllege 105


<FRAMESET> Tag
• Frames
– Display more than one HTML file at a time
– If used properly, frames make your site more readable and usable
• <!DOCTYPE> tag
– Uses Frameset instead of Transitional
– Tell the browser that you are using frames
• <FRAMESET> tags
– Tell the browser the page contains frames
– Details for frames contained within
<FRAMESET>…</FRAMESET> tags
– COLS or ROWS attribute gives the width or height of each frame
• In pixels or a percentage

P.Kumar, Rajalakshmi Engineering COllege 106


<FRAMESET> Tag (II)
• FRAME elements
– Specify what files will make up frameset
– FRAME attributes:
• NAME - identifies specific frame, enabling hyperlinks to load in their
intended frame
– TARGET attribute of A element
– Ex. <A HREF = “links.html” TARGET = “main”>
– TARGET = “_blank” loads page in a new blank browser
window
– TARGET = “_self” loads page in the same window as
anchor element
– TARGET = “_parent” loads page in the parent FRAMESET
– TARGET = _top” loads page in the full browser window
– SRC
• Gives the URL of the page that will be displayed in the specified
frame
P.Kumar, Rajalakshmi Engineering COllege 107
<FRAMESET> Tag (III)
• Not all browsers support frames
– Use the NOFRAMES element inside the FRAMESET
– Direct users to a non-framed version
– Provide links for downloading a frames-enabled
browser
• Use of frames
– Do not use frames if you can accomplish same with
tables or other, simpler HTML formatting

P.Kumar, Rajalakshmi Engineering COllege 108


1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
2<HTML> Outline
3
4<!-- Fig. 4.12: index.html -->
5<!-- HTML Frames I --> 1.1 <!DOCTYPE>
6 declares Frameset
7<HEAD> 1.2 FRAMESET tag gives
8<META NAME = "keywords" CONTENT = "Webpage, design, HTML,
the dimensions of
9 tutorial, personal, help, index, form, contact, feedback,
10 list, links, frame, deitel">
your frame using
11 COLS or ROWS
12<META NAME = "description" CONTENT = "This Web site will help 1.3 COLS = “110,*”
13 you learn the basics of HTML and Webpage design through the indicates that the
14 use of interactive examples and instruction."> first frame extends
15
110 pixels from left
16<TITLE>Internet and WWW How to Program - Main</TITLE>
17</HEAD>
side and the
18 second frame fills
19<!-- The <FRAMESET> tag gives the dimensions of your frame --> the remainder of
20<FRAMESET COLS = "110,*"> the screen
21 1.4 FRAME elements
22 <!-- The individual FRAME elements specify which pages -->
23 <!-- appear in the given frames --> 1.5 NOFRAMES element
24 <FRAME NAME = "nav" SRC = "nav.html">
25 <FRAME NAME = "main" SRC = "main.html">
26
27 <NOFRAMES>
28 <P>This page uses frames, but your browser does not support
29 them.</P>
30 <P>Get Internet Explorer 5 at theP.Kumar, Rajalakshmi Engineering COllege 109
31 <A HREF = "http://www.microsoft.com/">
32 Microsoft Web Site</A></P> Outline
33 </NOFRAMES>
34
35 </FRAMESET>
2. Page rendered by
36 </HTML> browser

P.Kumar, Rajalakshmi Engineering COllege 110


Nested <FRAMESET> Tags
• FRAME element
– SCROLLING attribute
• Set to “no” to prevent scroll bars
– NORESIZE attribute prevents user from resizing the
frame
• Nesting frames
– Include the correct number of FRAME elements inside
FRAMESET
– Using nested FRAMESET elements
• Indent every level of FRAME tag
• Makes page clearer and easier to debug

P.Kumar, Rajalakshmi Engineering COllege 111


1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">
2<HTML> Outline
3
4<!-- Fig. 4.13: index.html -->
5<!-- HTML Frames II --> 1. Nested FRAMESET
6 elements
7<HEAD> 1.1 Indent each level of
8 FRAMESET and
9<META NAME = "keywords" CONTENT = "Webpage, design, HTML,
FRAME elements
10 tutorial, personal, help, index, form, contact, feedback,
11 list, links, frame, deitel"> 1.2 Provide
12 NOFRAMES
13<META NAME = "description" CONTENT = "This Web site will help element
14 you learn the basics of HTML and Webpage design through the
15 use of interactive examples and instruction.">
16
17<FRAMESET COLS = "110,*">
18 <FRAME NAME = "nav" SCROLLING = "no" SRC = "nav.html">
19
20 <!-- Nested Framesets are used to change the formatting -->
21 <!-- and spacing of the frameset as a whole -->
22 <FRAMESET ROWS = "175,*">
23 <FRAME NAME = "picture" SRC = "picture.html" NORESIZE>
24 <FRAME NAME = "main" SRC = "main.html">
25 </FRAMESET>
26
27 <NOFRAMES>
28 <P>This page uses frames, but your browser doesn't
29 support them.</P>
P.Kumar, Rajalakshmi Engineering COllege 112
30 <P>Get Internet Explorer 5 at the
31 <A HREF = "http://www.microsoft.com/">Microsoft Outline
32 Web-Site</A></P>
33
34 </NOFRAMES> 2. Page rendered by
35 browser
36 </FRAMESET>
37 </HTML>

P.Kumar, Rajalakshmi Engineering COllege 113


JavaScript: Introduction to Scripting

Outline
Introduction
Simple Program: Printing a Line of Text in a Web Page
Obtaining User Input with prompt Dialogs
Dynamic Welcome Page
Adding Integers
Memory Concepts
Arithmetic
Decision Making: Equality and Relational Operators
Web Resources

P.Kumar, Rajalakshmi Engineering COllege 114


Objectives

• In this lesson, you will learn:


– To be able to write simple JavaScript programs.
– To be able to use input and output statements.
– To understand basic memory concepts.
– To be able to use arithmetic operators.
– To understand the precedence of arithmetic operators.
– To be able to write decision-making statements.
– To be able to use relational and equality operators.

P.Kumar, Rajalakshmi Engineering COllege 115


Introduction

• JavaScript scripting language


– Enhances functionality and appearance
– Client-side scripting
• Makes pages more dynamic and interactive
– Foundation for complex server-side scripting
– Program development
– Program control

P.Kumar, Rajalakshmi Engineering COllege 116


JavaScript Origin

• Divided into 3 parts


1. Core – heart of the language, includes operators,
expressions, stmts, subprograms
2. Client-side – Collection of objects that support
browser and interactions with users( embedded
with HTML)
3. Server-side – useful on web server(less frequently
used)

P.Kumar, Rajalakshmi Engineering COllege 117


Java Vs Javascript

• Java supports Oops concept whereas the


JavaScript does not support
• Java is a strongly typed language, JavaScript does
not provide ( dynamically typed)
• Objects in Java are static and are dynamic in
JavaScript
• Main similarity is their syntax

P.Kumar, Rajalakshmi Engineering COllege 118


Simple Program: Printing a Line of Text in a
Web Page
• Inline scripting
– Written in the <body> of a document
– <script> tag
• Indicate that the text is part of a script
• type attribute
– Specifies the type of file and the scripting language use
• writeln method
– Write a line in the document
• Escape character ( \ )
– Indicates “special” character is used in the string
• alert method
– Dialog box

P.Kumar, Rajalakshmi Engineering COllege 119


Outline

welcome.html
(1 of 1)

P.Kumar, Rajalakshmi Engineering COllege 120


Outline

welcome2.html
(1 of 1)

P.Kumar, Rajalakshmi Engineering COllege 121


Outline

welcome3.html
1 of 1

P.Kumar, Rajalakshmi Engineering COllege 122


Outline

welcome4.html
1 of 1

P.Kumar, Rajalakshmi Engineering COllege 123


P.Kumar, Rajalakshmi Engineering COllege 124
Simple Program: Printing a Line of Text in a
Web Page
Escape sequence Description
\n Newline. Position the screen cursor at the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the
current line; do not advance to the next line. Any characters output
after the carriage return overwrite the characters previously output on
that line.
\\ Backslash. Used to represent a backslash character in a string.
\" Double quote. Used to represent a double quote character in a string
contained in double quotes. For example,
window.alert( "\"in quotes\"" );
displays "in quotes" in an alert dialog.

\' Single quote. Used to represent a single quote character in a string. For
example,
window.alert( '\'in quotes\'' );
displays 'in quotes' in an alert dialog.

Fig. 7.5 Some common escape sequences.

P.Kumar, Rajalakshmi Engineering COllege 125


Dynamic Welcome Page

• A script can adapt the content based on input from


the user or other variables

P.Kumar, Rajalakshmi Engineering COllege 126


Outline

welcome5.html
(1 of 2)

P.Kumar, Rajalakshmi Engineering COllege 127


23
24 </head>
Outline
25
26 <body>
27 <p>Click Refresh (or Reload) to run this script again.</p> welcome5.html
28 </body> (2 of 2)
29 </html>

P.Kumar, Rajalakshmi Engineering COllege 128


Dynamic Welcome Page
When the user clicks OK, the
value typed by the user is returned
to the program as a string.
This is the prompt
to the user.

This is the text field in which


This is the default value that the user types the value.
appears when the dialog
opens.

Fig. 7.7 Prompt dialog displayed by the window object’s prompt method.

P.Kumar, Rajalakshmi Engineering COllege 129


Adding Integers

• Prompt user for two integers and calculate the sum


• NaN (not a number)
• parseInt
– Converts its string argument to an integer

P.Kumar, Rajalakshmi Engineering COllege 130


Outline

Addition.html
(1 of 2)

P.Kumar, Rajalakshmi Engineering COllege 131


24 // read in second number from user as a string
25 secondNumber =
Outline
26 window.prompt( "Enter second integer", "0" );
27
28 // convert numbers from strings to integers Addition.html
29 number1 = parseInt( firstNumber ); (2 of 2)
30 number2 = parseInt( secondNumber );
31
32 // add the numbers
33 sum = number1 + number2;
34
35 // display the results
36 document.writeln( "<h1>The sum is " + sum + "</h1>" );
37 // -->
38 </script>
39
40 </head>
41 <body>
42 <p>Click Refresh (or Reload) to run the script again</p>
43 </body>
44 </html>

P.Kumar, Rajalakshmi Engineering COllege 132


P.Kumar, Rajalakshmi Engineering COllege 133
Memory Concepts

• Variable names correspond to locations in the


computer’s memory
• Every variable has a name, a type, and a value
• Read value from a memory location
– nondestructive

P.Kumar, Rajalakshmi Engineering COllege 134


Memory Concepts

number1 45

Fig. 7.9 Memory location showing the name and value of variable number1.

P.Kumar, Rajalakshmi Engineering COllege 135


Memory Concepts

number1 45

number2 72

Fig. 7.10 Memory locations after values for variables number1 and number2 have been input.

P.Kumar, Rajalakshmi Engineering COllege 136


Memory Concepts

number1 45

number2 72

sum 117

Fig. 7.11 Memory locations after calculating the sum of number1 and number2.

P.Kumar, Rajalakshmi Engineering COllege 137


Arithmetic

• Many scripts perform arithmetic calculations


– Expressions in JavaScript must be written in straight-line
form

P.Kumar, Rajalakshmi Engineering COllege 138


Arithmetic
JavaScript Arithmetic Algebraic JavaScript
operation operator expression expression
Addition + f+7 f + 7

Subtraction - p–c p - c
Multiplication * bm b * m
/ x-- x / y
Division x / y or y
or xy

Remainder % r mod s r % s
Fig. 7.12 Arithmetic operators.

Operator(s) Operation(s) Order of evaluation (precedence)


*, / or % Multiplication Evaluated second. If there are several such
Division operations, they are evaluated from left to right.
Modulus
+ or - Addition Evaluated last. If there are several such operations,
Subtraction they are evaluated from left to right.
Fig. 7.13 Precedence of arithmetic operators.

P.Kumar, Rajalakshmi Engineering COllege 139


Arithmetic
Step 1. y = 2 * 5 * 5 + 3 * 5 + 7;

2 * 5 is 10 (Leftmost multiplication)

Step 2. y = 10 * 5 + 3 * 5 + 7;

10 * 5 is 50 (Leftmost multiplication)

Step 3. y = 50 + 3 * 5 + 7;

3 * 5 is 15 (Multiplication before addition)

Step 4. y = 50 + 15 + 7;

50 + 15 is 65 (Leftmost addition)

Step 5. y = 65 + 7;

65 + 7 is 72 (Last addition)

Step 6. y = 72; (Last operation—place 72 into y )

Fig. 7.14 Order in which a second-degree polynomial is evaluated.


P.Kumar, Rajalakshmi Engineering COllege 140
Decision Making: Equality and Relational
Operators
• Decision based on the truth or falsity of a
condition
– Equality operators
– Relational operators

P.Kumar, Rajalakshmi Engineering COllege 141


Decision Making: Equality and Relational
Operators
Standard algebraic JavaScript equality Sample Meaning of
equality operator or or relational JavaScript JavaScript
relational operator operator condition condition
Equality operators
= == x == y x is equal to y
? != x != y x is not equal to y
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
 >= x >= y x is greater than or
equal to y
 <= x <= y x is less than or
equal to y
Fig. 7.15 Equality and relational operators.

P.Kumar, Rajalakshmi Engineering COllege 142


Outline

welcome6.html
(1 of 3)

P.Kumar, Rajalakshmi Engineering COllege 143


25 // determine whether the time is PM
26 if ( hour >= 12 )
Outline
27 {
28 // convert to a 12 hour clock
29 hour = hour - 12; welcome6.html
30 (2 of 3)
31 // determine whether it is before 6 PM
32 if ( hour < 6 )
33 document.write( "<h1>Good Afternoon, " );
34
35 // determine whether it is after 6 PM
36 if ( hour >= 6 )
37 document.write( "<h1>Good Evening, " );
38 }
39
40 document.writeln( name +
41 ", welcome to JavaScript programming!</h1>" );
42 // -->
43 </script>
44
45 </head>
46

P.Kumar, Rajalakshmi Engineering COllege 144


47 <body>
48 <p>Click Refresh (or Reload) to run this script again.</p>
Outline
49 </body>
50 </html>
welcome6.html
(3 of 3)

P.Kumar, Rajalakshmi Engineering COllege 145


Decision Making: Equality and Relational
Operators

Operators Associativity Type


* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
= right to left assignment
Fig. 7.17 Precedence and associativity of the
operators discussed so far.

P.Kumar, Rajalakshmi Engineering COllege 146


JavaScript: Control Statements I
Outline
Introduction
Algorithms
Control Structures
if Selection Statement
if…else Selection Statement
while Repetition Statement
Formulating Algorithms: Case Study 1 (Counter-Controlled
Repetition)
Formulating Algorithms with Top-Down, Stepwise
Refinement: Case Study 2 (Sentinel-Controlled Repetition)
Formulating Algorithms with Top-Down, Stepwise
Refinement: Case Study 3 (Nested Control Structures)
Assignment Operators
Increment and Decrement Operators

P.Kumar, Rajalakshmi Engineering COllege 147


Objectives

• In this lesson, you will learn:


– To understand basic problem-solving techniques.
– To be able to develop algorithms through the process of top-
down, stepwise refinement.
– To be able to use the if and if…else selection statements
to choose among alternative actions.
– To be able to use the while repetition statement to execute
statements in a script repeatedly.
– To understand counter-controlled repetition and sentinel-
controlled repetition.
– To be able to use the increment, decrement and assignment
operators.

P.Kumar, Rajalakshmi Engineering COllege 148


Introduction

• Writing a script
– Thorough understanding of problem
– Carefully planned approach
– Understand the types of building blocks that are available
– Employ proven program-construction principles

P.Kumar, Rajalakshmi Engineering COllege 149


Algorithms

• Actions to be executed
• Order in which the actions are to be executed

P.Kumar, Rajalakshmi Engineering COllege 150


Control Structures

• Sequential execution
– Statements execute in the order they are written
• Transfer of control
– Next statement to execute may not be the next one in sequence
• Three control structures
– Sequence structure
– Selection structure
• if
• if…else
• switch
– Repetition structure
• while
• do…while
• for
• for…in
P.Kumar, Rajalakshmi Engineering COllege 151
Control Structures

• Flowchart
– Graphical representation of algorithm or portion of
algorithm
– Flowlines
• Indicate the order the actions of the algorithm execute
– Rectangle symbol
• Indicate any type of action
– Oval symbol
• A complete algorithm
– Small circle symbol
• A portion of algorithm
– Diamond symbol
• Indicates a decision is to be made
P.Kumar, Rajalakshmi Engineering COllege 152
Control Structures

add grade to total total = total + grade;

add 1 to counter counter = counter + 1;

Fig. 8.1 Flowcharting JavaScript’s sequence structure.

P.Kumar, Rajalakshmi Engineering COllege 153


Control Structures

JavaScript
Keywords
break case catch continue default
delete do else finally for
function if in instanceof new
return switch this throw try
typeof var void while with
Keywords that
are reserved but
not currently
used by
JavaScript
abstract boolean byte char class
const debugger double enum export
extends final float goto implements
import int interface long native
package private protected public short
static super synchronized throws transient
volatile
Fig. 8.2 JavaScript keywords.
P.Kumar, Rajalakshmi Engineering COllege 154
if Selection Statement

• Single-entry/single-exit structure
• Indicate action only when the condition evaluates
to true

P.Kumar, Rajalakshmi Engineering COllege 155


if Selection Statement

true
grade >= 60 print “Passed”

false

Fig. 8.3 Flowcharting the single-selection if statement.

P.Kumar, Rajalakshmi Engineering COllege 156


if…else Selection Statement

• Indicate different actions to be perform when


condition is true or false
• Conditional operator (?:)
– JavaScript’s only ternary operator
• Three operands
• Forms a conditional expression
• Dangling-else problem

P.Kumar, Rajalakshmi Engineering COllege 157


if…else Selection Statement

false grade >= 60 true

print “Failed” print “Passed”

Flowcharting the double-selection if…else statement.

P.Kumar, Rajalakshmi Engineering COllege 158


while Repetition Statement

• Repetition structure (loop)


– Repeat action while some condition remains true

P.Kumar, Rajalakshmi Engineering COllege 159


while Repetition Statement

true
product <= 1000 product = 2 * product

false

Flowcharting the while repetition statement.

P.Kumar, Rajalakshmi Engineering COllege 160


Formulating Algorithms:
Case Study 1 (Counter-Controlled
Repetition)
• Counter-controlled repetition
– Counter
• Control the number of times a set of statements executes
– Definite repetition

P.Kumar, Rajalakshmi Engineering COllege 161


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 8.7: average.html --> average.html
6 <!-- Class Average Program --> (1 of 3)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Class Average Program</title>
11
12 <script type = "text/javascript">
13 <!--
14 var total, // sum of grades
15 gradeCounter, // number of grades entered
16 gradeValue, // grade value
17 average, // average of all grades
18 grade; // grade typed by user
19
20 // Initialization Phase
21 total = 0; // clear total
22 gradeCounter = 1; // prepare to loop
23

P.Kumar, Rajalakshmi Engineering COllege 162


24 // Processing Phase
while ( gradeCounter <= 10 ) { // loop 10 times
25
Outline
26
27 // prompt for input and read grade from user
28 grade = window.prompt( "Enter integer grade:", "0" ); average.html
29 (2 of 3)
30 // convert grade from a string to an integer
31 gradeValue = parseInt( grade );
32
33 // add gradeValue to total
34 total = total + gradeValue;
35
36 // add 1 to gradeCounter
37 gradeCounter = gradeCounter + 1;
38 }
39
40 // Termination Phase
41 average = total / 10; // calculate the average
42
43 // display average of exam grades
44 document.writeln(
45 "<h1>Class average is " + average + "</h1>" );
46 // -->
47 </script>

P.Kumar, Rajalakshmi Engineering COllege 163


48
</head>
49
Outline
50 <body>
51 <p>Click Refresh (or Reload) to run the script again<p>
52 </body> average.html
53 </html> (3 of 3)

P.Kumar, Rajalakshmi Engineering COllege 164


Formulating Algorithms with Top-Down,
Stepwise Refinement: Case Study 2
(Sentinel-Controlled Repetition)
• Indefinite repetition
– Sentinel value

P.Kumar, Rajalakshmi Engineering COllege 165


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 8.9: average2.html --> average2.html
6 <!-- Sentinel-controlled Repetition --> (1 of 3)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Class Average Program:
11 Sentinel-controlled Repetition</title>
12
13 <script type = "text/javascript">
14 <!--
15 var gradeCounter, // number of grades entered
16 gradeValue, // grade value
17 total, // sum of grades
18 average, // average of all grades
19 grade; // grade typed by user
20
21 // Initialization phase
22 total = 0; // clear total
23 gradeCounter = 0; // prepare to loop
24

P.Kumar, Rajalakshmi Engineering COllege 166


25 // Processing phase
// prompt for input and read grade from user
26
Outline
27 grade = window.prompt(
28 "Enter Integer Grade, -1 to Quit:", "0" );
29 average2.html
30 // convert grade from a string to an integer (2 of 3)
31 gradeValue = parseInt( grade );
32
33 while ( gradeValue != -1 ) {
34 // add gradeValue to total
35 total = total + gradeValue;
36
37 // add 1 to gradeCounter
38 gradeCounter = gradeCounter + 1;
39
40 // prompt for input and read grade from user
41 grade = window.prompt(
42 "Enter Integer Grade, -1 to Quit:", "0" );
43
44 // convert grade from a string to an integer
45 gradeValue = parseInt( grade );
46 }
47

P.Kumar, Rajalakshmi Engineering COllege 167


48 // Termination phase
49 if ( gradeCounter != 0 ) {
Outline
50 average = total / gradeCounter;
51
52 // display average of exam grades average2.html
53 document.writeln( (3 of 3)
54 "<h1>Class average is " + average + "</h1>" );
55 }
56 else
57 document.writeln( "<p>No grades were entered</p>" );
58 // -->
59 </script>
60 </head>
61
62 <body>
63 <p>Click Refresh (or Reload) to run the script again</p>
64 </body>
65 </html>

P.Kumar, Rajalakshmi Engineering COllege 168


P.Kumar, Rajalakshmi Engineering COllege 169
Formulating Algorithms with Top-Down,
Stepwise Refinement: Case Study 3 (Nested
Control Structures)
• Consider problem
• Make observations
• Top-down, stepwise refinement

P.Kumar, Rajalakshmi Engineering COllege 170


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 8.11: analysis.html --> analysis.html
6 <!-- Analyzing Exam Results --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Analysis of Examination Results</title>
11
12 <script type = "text/javascript">
13 <!--
14 // initializing variables in declarations
15 var passes = 0, // number of passes
16 failures = 0, // number of failures
17 student = 1, // student counter
18 result; // one exam result
19
20 // process 10 students; counter-controlled loop
21 while ( student <= 10 ) {
22 result = window.prompt(
23 "Enter result (1=pass,2=fail)", "0" );
24

P.Kumar, Rajalakshmi Engineering COllege 171


25 if ( result == "1" )
passes = passes + 1;
26
Outline
27 else
28 failures = failures + 1;
29 analysis.html
30 student = student + 1; (2 of 2)
31 }
32
33 // termination phase
34 document.writeln( "<h1>Examination Results</h1>" );
35 document.writeln(
36 "Passed: " + passes + "<br />Failed: " + failures );
37
38 if ( passes > 8 )
39 document.writeln( "<br />Raise Tuition" );
40 // -->
41 </script>
42
43 </head>
44 <body>
45 <p>Click Refresh (or Reload) to run the script again</p>
46 </body>
47 </html>

P.Kumar, Rajalakshmi Engineering COllege 172


P.Kumar, Rajalakshmi Engineering COllege 173
P.Kumar, Rajalakshmi Engineering COllege 174
Assignment Operators

• Compound assignment operators


– Abbreviate assignment expressions

P.Kumar, Rajalakshmi Engineering COllege 175


Assignment Operators

Assignment Initial Sample Explanation Assigns


operator value of expression
variable
+= c = 3 c += 7c = c + 10 to c
7
-= d = 5 d -= 4 d = d - 1 to d
4
*= e = 4 e *= 5 e = e * 20 to e
5
/= f = 6 f /= 3 f = f / 2 to f
3
%= g = 12 g %= 9 g = g % 3 to g
9
Fig. 8.12 Arithmetic assignment operators.

P.Kumar, Rajalakshmi Engineering COllege 176


Increment and Decrement Operators

• Preincrement or predecrement operator


– Increment of decrement operator placed before a variable
• Postincrement or postdecrement operator
– Increment of decrement operator placed after a variable

P.Kumar, Rajalakshmi Engineering COllege 177


Increment and Decrement Operators
Operator Called Sample Explanation
expression
++ preincrement ++a Increment a by 1, then use the
new value of a in the
expression in which a resides.
++ postincrement a++ Use the current value of a in
the expression in which a
resides, then increment a by 1.
-- predecrement --b Decrement b by 1, then use the
new value of b in the
expression in which b resides.
-- postdecrement b-- Use the current value of b in
the expression in which b
resides, then decrement b by 1.
Fig. 8.13 increment and decrement operators.

P.Kumar, Rajalakshmi Engineering COllege 178


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 8.14: increment.html --> increment.html
6 <!-- Preincrementing and Postincrementing --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Preincrementing and Postincrementing</title>
11
12 <script type = "text/javascript">
13 <!--
14 var c;
15
16 c = 5;
17 document.writeln( "<h3>Postincrementing</h3>" );
18 document.writeln( c ); // print 5
19 // print 5 then increment
20 document.writeln( "<br />" + c++ );
21 document.writeln( "<br />" + c ); // print 6
22
23 c = 5;
24 document.writeln( "<h3>Preincrementing</h3>" );
25 document.writeln( c ); // print 5

P.Kumar, Rajalakshmi Engineering COllege 179


26 // increment then print 6
document.writeln( "<br />" + ++c );
27
Outline
28 document.writeln( "<br />" + c ); // print 6
29 // -->
30 </script> increment.html
31 (2 of 2)
32 </head><body></body>
33 </html>

P.Kumar, Rajalakshmi Engineering COllege 180


Increment and Decrement Operators

Operator Associativity Type


++ -- right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 8.15 Precedence and associativity of the operators
discussed so far.

P.Kumar, Rajalakshmi Engineering COllege 181


JavaScript: Control Statements II

Outline
Essentials of Counter-Controlled Repetition
for Repetition Statement
Examples Using the for Statement
switch Multiple-Selection Statement
do…while Repetition Statement
break and continue Statements
Labeled break and continue Statements
Logical Operators
Summary of Structured Programming

P.Kumar, Rajalakshmi Engineering COllege 182


Objectives

• In this lesson, you will learn:


– To be able to use the for and do…while repetition
statements to execute statements in a program repeatedly.
– To understand multiple selection using the switch selection
statement.
– To be able to use the break and continue program-control
statements.
– To be able to use the logical operators.

P.Kumar, Rajalakshmi Engineering COllege 183


Essentials of Counter-Controlled
Repetition
• Counter-controlled repetition
– Name of a control
– Initial value
– Increment or decrement
– Final value

P.Kumar, Rajalakshmi Engineering COllege 184


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.1: WhileCounter.html --> WhileCounter.html
6 <!-- Counter-Controlled Repetition --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Counter-Controlled Repetition</title>
11
12 <script type = "text/javascript">
13 <!--
14 var counter = 1; // initialization
15
16 while ( counter <= 7 ) { // repetition condition
17 document.writeln( "<p style = \"font-size: " +
18 counter + "ex\">XHTML font size " + counter +
19 "ex</p>" );
20 ++counter; // increment
21 }
22 // -->
23 </script>
24

P.Kumar, Rajalakshmi Engineering COllege 185


25 </head><body></body>
26 </html>
Outline

WhileCounter.html
(2 of 2)

P.Kumar, Rajalakshmi Engineering COllege 186


for Repetition Statement

• for repetition statement


– Handles all the details of counter-controlled repetition
– for structure header
• The first line

P.Kumar, Rajalakshmi Engineering COllege 187


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.2: ForCounter.html --> ForCounter.html
6 <!-- Counter-Controlled Repetition with for statement --> (1 of 1)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Counter-Controlled Repetition</title>
11
12 <script type = "text/javascript">
13 <!--
14 // Initialization, repetition condition and
15 // incrementing are all included in the for
16 // statement header.
17 for ( var counter = 1; counter <= 7; ++counter )
18 document.writeln( "<p style = \"font-size: " +
19 counter + "ex\">XHTML font size " + counter +
20 "ex</p>" );
21 // -->
22 </script>
23
24 </head><body></body>
25 </html>

P.Kumar, Rajalakshmi Engineering COllege 188


P.Kumar, Rajalakshmi Engineering COllege 189
for Repetition Statement

for keyword Control variable name Final value of control variable


for which the condition is true

for ( var counter = 1; counter <= 7; ++counter )

Initial value of control variable Increment of control variable


Loop-continuation condition

for statement header components.

P.Kumar, Rajalakshmi Engineering COllege 190


for Repetition Statement

Establish
initial value
of control
variable.
var counter = 1

document.writeln(
true "<p style=\"font-size: "
counter <= 7 ++counter
+ counter +
"ex\">XHTML font size " + Increment
counter + "ex</p>" ); the control
false variable.
Determine Body of loop
(this may be many
if final value
of control statements)
variable
has been
reached.

for repetition structure flowchart.

P.Kumar, Rajalakshmi Engineering COllege 191


Examples Using the for Statement

• Summation with for


• Compound interest calculation with for loop
– Math object
• Method pow
• Method round

P.Kumar, Rajalakshmi Engineering COllege 192


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.5: Sum.html --> Sum.html
6 <!-- Using the for repetition statement --> (1 of 1)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Sum the Even Integers from 2 to 100</title>
11
12 <script type = "text/javascript">
13 <!--
14 var sum = 0;
15
16 for ( var number = 2; number <= 100; number += 2 )
17 sum += number;
18
19 document.writeln( "The sum of the even integers " +
20 "from 2 to 100 is " + sum );
21 // -->
22 </script>
23
24 </head><body></body>
25 </html>

P.Kumar, Rajalakshmi Engineering COllege 193


P.Kumar, Rajalakshmi Engineering COllege 194
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.6: Interest.html --> Interest.html
6 <!-- Using the for repetition statement --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Calculating Compound Interest</title>
11
12 <script type = "text/javascript">
13 <!--
14 var amount, principal = 1000.0, rate = .05;
15
16 document.writeln(
17 "<table border = \"1\" width = \"100%\">" );
18 document.writeln(
19 "<caption>Calculating Compound Interest</caption>" );
20 document.writeln(
21 "<thead><tr><th align = \"left\">Year</th>" );
22 document.writeln(
23 "<th align = \"left\">Amount on deposit</th>" );
24 document.writeln( "</tr></thead>" );
25

P.Kumar, Rajalakshmi Engineering COllege 195


26 for ( var year = 1; year <= 10; ++year ) {
27 amount = principal * Math.pow( 1.0 + rate, year );
Outline
28 document.writeln( "<tbody><tr><td>" + year +
29 "</td><td>" + Math.round( amount * 100 ) / 100 +
30 "</td></tr>" ); Interest.html
31 } (2 of 2)
32
33 document.writeln( "</tbody></table>" );
34 // -->
35 </script>
36
37 </head><body></body>
38 </html>

P.Kumar, Rajalakshmi Engineering COllege 196


switch Multiple-Selection Statement

• Controlling expression
• Case labels
• Default case

P.Kumar, Rajalakshmi Engineering COllege 197


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.7: SwitchTest.html --> SwitchTest.html
6 <!-- Using the switch statement --> (1 of 3)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Switching between XHTML List Formats</title>
11
12 <script type = "text/javascript">
13 <!--
14 var choice, // user’s choice
15 startTag, // starting list item tag
16 endTag, // ending list item tag
17 validInput = true, // indicates if input is valid
18 listType; // list type as a string
19
20 choice = window.prompt( "Select a list style:\n" +
21 "1 (bullet), 2 (numbered), 3 (lettered)", "1" );
22

P.Kumar, Rajalakshmi Engineering COllege 198


23 switch ( choice ) {
case "1":
24
Outline
25 startTag = "<ul>";
26 endTag = "</ul>";
27 listType = "<h1>Bullet List</h1>"; SwitchTest.html
28 break; (2 of 3)
29 case "2":
30 startTag = "<ol>";
31 endTag = "</ol>";
32 listType = "<h1>Ordered List: Numbered</h1>";
33 break;
34 case "3":
35 startTag = "<ol type = \"A\">";
36 endTag = "</ol>";
37 listType = "<h1>Ordered List: Lettered</h1>";
38 break;
39 default:
40 validInput = false;
41 }
42
43 if ( validInput == true ) {
44 document.writeln( listType + startTag );
45
46 for ( var i = 1; i <= 3; ++i )
47 document.writeln( "<li>List item " + i + "</li>" );

P.Kumar, Rajalakshmi Engineering COllege 199


48
49 document.writeln( endTag );
Outline
50 }
51 else
52 document.writeln( "Invalid choice: " + choice ); SwitchTest.html
53 // --> (3 of 3)
54 </script>
55
56 </head>
57 <body>
58 <p>Click Refresh (or Reload) to run the script again</p>
59 </body>
60 </html>

P.Kumar, Rajalakshmi Engineering COllege 200


P.Kumar, Rajalakshmi Engineering COllege 201
P.Kumar, Rajalakshmi Engineering COllege 202
switch Multiple-Selection Statement

true
case a case a action(s) break

false

true
case b case b action(s) break

false

.
.
.

true
case z case z action(s) break

false

default action(s)

P.Kumar, Rajalakshmi Engineering COllege 203


do…while Repetition Statement

• Similar to the while statement


• Tests the loop continuation condition after the
loop body executes
• Loop body always executes at least once

P.Kumar, Rajalakshmi Engineering COllege 204


1 <?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.9: DoWhileTest.html --> DoWhileTest.html
6 <!-- Using the do...while statement --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the do...while Repetition Statement</title>
11
12 <script type = "text/javascript">
13 <!--
14 var counter = 1;
15
16 do {
17 document.writeln( "<h" + counter + ">This is " +
18 "an h" + counter + " level head" + "</h" +
19 counter + ">" );
20
21 ++counter;
22 } while ( counter <= 6 );
23 // -->
24 </script>

P.Kumar, Rajalakshmi Engineering COllege 205


25
26 </head><body></body>
Outline
27 </html>

DoWhileTest.html
(2 of 2)

P.Kumar, Rajalakshmi Engineering COllege 206


do…while Repetition Structure

action(s)

true
condition

false

do…while repetition statement flowchart.

P.Kumar, Rajalakshmi Engineering COllege 207


break and continue Statements

• break
– Immediate exit from the structure
– Used to escape early from a loop
– Skip the remainder of a switch statement
• continue
– Skips the remaining statements in the body of the structure
– Proceeds with the next iteration of the loop

P.Kumar, Rajalakshmi Engineering COllege 208


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.11: BreakTest.html --> BreakTest.html
6 <!-- Using the break statement --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Using the break Statement in a for Structure
12 </title>
13
14 <script type = "text/javascript">
15 <!--
16 for ( var count = 1; count <= 10; ++count ) {
17 if ( count == 5 )
18 break; // break loop only if count == 5
19
20 document.writeln( "Count is: " + count + "<br />" );
21 }
22

P.Kumar, Rajalakshmi Engineering COllege 209


23 document.writeln(
24 "Broke out of loop at count = " + count );
Outline
25 // -->
26 </script>
27 BreakTest.html
28 </head><body></body> (2 of 2)
29 </html>

P.Kumar, Rajalakshmi Engineering COllege 210


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.12: ContinueTest.html --> ContinueTest.html
6 <!-- Using the break statement --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>
11 Using the continue Statement in a for Structure
12 </title>
13
14 <script type = "text/javascript">
15 <!--
16 for ( var count = 1; count <= 10; ++count ) {
17 if ( count == 5 )
18 continue; // skip remaining code in loop
19 // only if count == 5
20
21 document.writeln( "Count is: " + count + "<br />" );
22 }
23

P.Kumar, Rajalakshmi Engineering COllege 211


24 document.writeln( "Used continue to skip printing 5" );
25 // -->
Outline
26 </script>
27
28 </head><body></body> ContinueTest.html
29 </html> (2 of 2)

P.Kumar, Rajalakshmi Engineering COllege 212


Labeled break and continue Statements

• Labeled break statement


– Break out of a nested set of structures
– Immediate exit from that structure and enclosing repetition
structures
– Execution resumes with first statement after enclosing
labeled statement
• Labeled continue statement
– Skips the remaining statements in structure’s body and
enclosing repetition structures
– Proceeds with next iteration of enclosing labeled repetition
structure
– Loop-continuation test evaluates immediately after the
continue statement executes
P.Kumar, Rajalakshmi Engineering COllege 213
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.13: BreakLabelTest.html --> BreakLabelTest.html
6 <!-- Using the break statement with a Label --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the break Statement with a Label</title>
11
12 <script type = "text/javascript">
13 <!--
14 stop: { // labeled block
15 for ( var row = 1; row <= 10; ++row ) {
16 for ( var column = 1; column <= 5 ; ++column ) {
17
18 if ( row == 5 )
19 break stop; // jump to end of stop block
20
21 document.write( "* " );
22 }
23
24 document.writeln( "<br />" );
25 }

P.Kumar, Rajalakshmi Engineering COllege 214


26
// the following line is skipped
27
Outline
28 document.writeln( "This line should not print" );
29 }
30 BreakLabelTest.html
31 document.writeln( "End of script" ); (2 of 2)
32 // -->
33 </script>
34
35 </head><body></body>
36 </html>

P.Kumar, Rajalakshmi Engineering COllege 215


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.14: ContinueLabelTest.html --> ContinueLabelTest.html
6 <!-- Using the continue statement --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the continue Statement with a Label</title>
11
12 <script type = "text/javascript">
13 <!--
14 nextRow: // target label of continue statement
15 for ( var row = 1; row <= 5; ++row ) {
16 document.writeln( "<br />" );
17
18 for ( var column = 1; column <= 10; ++column ) {
19
20 if ( column > row )
21 continue nextRow; // next iteration of
22 // labeled loop
23
24 document.write( "* " );
25 }

P.Kumar, Rajalakshmi Engineering COllege 216


26 }
27 // -->
Outline
28 </script>
29
30 </head><body></body> ContinueLabelTest.html
31 </html> (2 of 2)

P.Kumar, Rajalakshmi Engineering COllege 217


Logical Operators

• More logical operators


– Logical AND ( && )
– Logical OR ( || )
– Logical NOT ( ! )

P.Kumar, Rajalakshmi Engineering COllege 218


Logical Operators

expression1 expression2 expression1 &&


expression2
false false false
false true false
true false false
true true true
Fig. 9.15 Truth table for the && (logical AND)
operator.

P.Kumar, Rajalakshmi Engineering COllege 219


Logical Operators

expression1 expression2 expression1 ||


expression2
false false false
false true true
true false true
true true true
Fig. 9.16 Truth table for the || (logical OR) operator.

expression !expression
false true
true false
Fig. 9.17 Truth table for operator ! (logical negation).

P.Kumar, Rajalakshmi Engineering COllege 220


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.18: LogicalOperators.html --> LogicalOperators.html
6 <!-- Demonstrating Logical Operators --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Demonstrating the Logical Operators</title>
11
12 <script type = "text/javascript">
13 <!--
14 document.writeln(
15 "<table border = \"1\" width = \"100%\">" );
16
17 document.writeln(
18 "<caption>Demonstrating Logical " +
19 "Operators</caption" );
20
21 document.writeln(
22 "<tr><td width = \"25%\">Logical AND (&&)</td>" +
23 "<td>false && false: " + ( false && false ) +
24 "<br />false && true: " + ( false && true ) +
25 "<br />true && false: " + ( true && false ) +

P.Kumar, Rajalakshmi Engineering COllege 221


26 "<br />true && true: " + ( true && true ) +
"</td>" );
27
Outline
28
29 document.writeln(
30 "<tr><td width = \"25%\">Logical OR (||)</td>" + LogicalOperators.html
31 "<td>false || false: " + ( false || false ) + (2 of 2)
32 "<br />false || true: " + ( false || true ) +
33 "<br />true || false: " + ( true || false ) +
34 "<br />true || true: " + ( true || true ) +
35 "</td>" );
36
37 document.writeln(
38 "<tr><td width = \"25%\">Logical NOT (!)</td>" +
39 "<td>!false: " + ( !false ) +
40 "<br />!true: " + ( !true ) + "</td>" );
41
42 document.writeln( "</table>" );
43 // -->
44 </script>
45
46 </head><body></body>
47 </html>

P.Kumar, Rajalakshmi Engineering COllege 222


P.Kumar, Rajalakshmi Engineering COllege 223
Logical Operators

Operator Associativity Type


++ -- ! right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 9.19 Precedence and associativity of the operators discussed
so far.

P.Kumar, Rajalakshmi Engineering COllege 224


Summary of Structured Programming

• Flowcharts
– Reveal the structured nature of programs
• Single-entry/single-exit control structures
– Only one way to enter and one way to exit each control
structure
• Control structure stacking
– The exit point of one control structure is connected to the
entry point of the next control structure

P.Kumar, Rajalakshmi Engineering COllege 225


Summary of Structured Programming

do…while statement

T
while statement
Rep etition

F
for statement

T
T

F
Single-entry/single-exit sequence, selection and repetition structures. (1 of 3)

P.Kumar, Rajalakshmi Engineering COllege 226


Summary of Structured Programming

if…else statement
(d ouble se lec tion)
T

break
break

break
F
Se lectio n

(m ultiple selection)
switch statement
(single se lec tio n)
if statement

T
F

F
.
.
.
T

Single-entry/single-exit sequence, selection and repetition structures. (2 of 3)


P.Kumar, Rajalakshmi Engineering COllege 227
Summary of Structured Programming
Se que nc e

.
.
.
Single-entry/single-exit sequence, selection and repetition structures. (3 of 3)

P.Kumar, Rajalakshmi Engineering COllege 228


Summary of Structured Programming

Rules for Forming Structured Programs


1) Begin with the “simplest flowchart” (Fig. 9.22).
2) Any rectangle (action) can be replaced by two rectangles (actions) in sequence.
3) Any rectangle (action) can be replaced by any control structure (sequence, if, if…else,
switch, while, do…while or for).
4) Rules 2 and 3 may be applied as often as you like and in any order.
Fig. 9.21 Rules for forming structured programs.

P.Kumar, Rajalakshmi Engineering COllege 229


Summary of Structured Programming

Simplest flowchart.

P.Kumar, Rajalakshmi Engineering COllege 230


Summary of Structured Programming

Rule 2 Rule 2 Rule 2

.
.
.

Repeatedly applying rule 2 to the simplest flowchart.

P.Kumar, Rajalakshmi Engineering COllege 231


Summary of Structured Programming

Rule 3

Rule 3

Applying rule 3 to the simplest flowchart.


P.Kumar, Rajalakshmi Engineering COllege 232
Summary of Structured Programming
Stacked building blocks Nested building blocks

Overlapping building blocks


(Illegal in structured programs)

Stacked, nested and overlapped building blocks.

P.Kumar, Rajalakshmi Engineering COllege 233


Summary of Structured Programming

Unstructured flowchart.

P.Kumar, Rajalakshmi Engineering COllege 234


JavaScript: Functions
Outline

Function Definitions
Scope Rules
JavaScript Global Functions
Recursion
Recursion vs. Iteration

P.Kumar, Rajalakshmi Engineering COllege 235


Objectives

• In this, you will learn:


– To understand how to construct programs modularly from
small pieces called functions.
– To be able to create new functions.
– To understand the mechanisms used to pass information
between functions.
– To understand how the visibility of identifiers is limited to
specific regions of programs.

P.Kumar, Rajalakshmi Engineering COllege 236


Functions

• A piece of code that performs a specific task


• Built in Function
– alert() – Open a box containing the message
– prompt() – display a prompt window with field for the user
to enter a text string
– toLowerCase()

P.Kumar, Rajalakshmi Engineering COllege 237


Function Definitions

• Format of a function definition

function function-name( parameter-list )


{
declarations and statements
}

– Function name any valid identifier


– Parameter list names of variables that will receive arguments
• Must have same number as function call
• May be empty
– Declarations and statements
• Function body (“block” of code)

P.Kumar, Rajalakshmi Engineering COllege 238


Outline

<html>
<head>
<script>
function about(name, age)
{
document.write("<h1> All about You</h1>");
document.write("<p>Your Name is" + name);
document.write("<p>You are" + age);
}
about("abc",95);
</script>
</head>
</html>

P.Kumar, Rajalakshmi Engineering COllege . 239


Function Definitions

• Finding the maximum of 3 numbers


– Prompt for 3 inputs
– Convert to numbers
– Pass to maximum
– Math.max

P.Kumar, Rajalakshmi Engineering COllege 240


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.3: maximum.html --> Maximum.html
6 <!-- Maximum function --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Finding the Maximum of Three Values</title>
11 Prompt for the user to input three integers.
12 <script type = "text/javascript">
13 <!--
14 var input1 =
15 window.prompt( "Enter first number", "0" );
16 var input2 =
17 window.prompt( "Enter second number", "0" );
18 var input3 =
19 window.prompt( "Enter third number", "0" );
20
21 var value1 = parseFloat( input1 );
22 var value2 = parseFloat( input2 );
23 var value3 = parseFloat( input3 );

P.Kumar, Rajalakshmi Engineering COllege . 241


24
25 var maxValue = maximum( value1, value2, value3 );
Outline
26
27 document.writeln( "First number: " + value1 +
Call function maximum and pass it the value of
28 "<br />Second number: " + value2 +
variables value1, value2 and value3.Maximum.html
29 "<br />Third number: " + value3 + (2 of 2)
30 "<br />Maximum is: " + maxValue );
Method max returns the larger of the two
31
integers passed to it.
32 // maximum method definition (called from line 25)
33 function maximum( x, y, z )
34 {
35 y, z ) ); x,
return Math.max( x, Math.max( Variables y and z get the value of variables
36 } value1, value2 and value3, respectively.
37 // -->
38 </script>
39
40 </head>
41 <body>
42 <p>Click Refresh (or Reload) to run the script again</p>
43 </body>
44 </html>

P.Kumar, Rajalakshmi Engineering COllege . 242


Function Definitions
Programmer-defined maximum function (1 of 2).

P.Kumar, Rajalakshmi Engineering COllege 243


Function Definitions
Programmer-defined maximum function (2 of 2).

P.Kumar, Rajalakshmi Engineering COllege 244


Scope Rules

• Scope
– How a Variable can be accessed
– Local & Global
– Inside function is local or function scope
• Identifiers exist only between opening and closing braces
• Local variables hide global variables

P.Kumar, Rajalakshmi Engineering COllege 245


Example
<html>
<head>
</head>
<body>
<script>
var a=32;
var b=a;
var c=setlocal(17);
document.write("a is "+a);
document.write("b is "+b);
document.write("c is "+c);

function setlocal(d)
{
a=d;
alert("bis inside" + b);
return(a);
}
</script>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 246


JavaScript Global Functions
Global function Description
parseFloat This function takes a string argument and attempts
to convert the beginning of the string into a floating-
point value. If the conversion is unsuccessful, the
function returns NaN; otherwise, it returns the
converted value (e.g., parseFloat( "abc123.45" )
returns NaN, and parseFloat( "123.45abc" )
returns the value 123.45).
parseInt This function takes a string argument and attempts
to convert the beginning of the string into an integer
value. If the conversion is unsuccessful, the function
returns NaN; otherwise, it returns the converted
value (e.g., parseInt( "abc123" ) returns NaN, and
parseInt( "123abc" ) returns the integer value
123). This function takes an optional second
argument, from 2 to 36, specifying the radix (or
base) of the number. Base 2 indicates that the first
argument string is in binary format, base 8 indicates
that the first argument string is in octal format and
base 16 indicates that the first argument string is in
hexadecimal format. See see Appendex E, Number
Systems, for more information on binary, octal and
hexadecimal numbers.
unescape This function takes a string as its argument and
returns a string in which all characters previously
encoded with escape are decoded.
Fig. 10.9 JavaScript global functions.
P.Kumar, Rajalakshmi Engineering COllege 247
Recursion

• Recursive functions
– Call themselves
• Recursion step or recursive call
• Part of return statement
– Must have base case
• Simplest case of problem
• Returns value rather than calling itself
– Each recursive call simplifies input
• When simplified to base case, functions return

P.Kumar, Rajalakshmi Engineering COllege 248


Recursion

Final value = 120


5! 5!
5! = 5 * 24 = 120 is returned
5 * 4! 5 * 4!
4! = 4 * 6 = 24 is returned
4 * 3! 4 * 3!
3! = 3 * 2 = 6 is returned
3 * 2! 3 * 2!
2! = 2 * 1 = 2 is returned
2 * 1! 2 * 1!
1 returned
1 1

(a) Procession of recursive calls. (b) Values returned from each recursive call.

Recursive evaluation of 5!.

P.Kumar, Rajalakshmi Engineering COllege 249


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 10.11: FactorialTest.html --> FactorialTest.html
6 <!-- Recursive factorial example --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Recursive Factorial Function</title>
11
12 <script language = "javascript">
Calling function factorial and passing
13 document.writeln( "<h1>Factorials of 1 to 10</h1>" );
it the value of i.
14 document.writeln(
15 "<table border = '1' width = '100%'>" );
16
17 for ( var i = 0; i <= 10; i++ )
18 document.writeln( "<tr><td>" + i + "!</td><td>" +
19 factorial( i ) + "</td></tr>" );
20
21 document.writeln( "</table>" );
22

P.Kumar, Rajalakshmi Engineering COllege . 250


23 // Recursive definition of function factorial
24 function factorial( number ) Variable number gets the value of variable i.Outline
25 {
26 if ( number <= 1 ) Call
// base case to function factorial and passing it 1
27 return 1; less than the current value of number . FactorialTest.html
28 else (2 of 2)
29 return number * factorial( number - 1 );
30 }
31 </script>
32 </head><body></body>
33 </html>

P.Kumar, Rajalakshmi Engineering COllege . 251


Recursion
Factorial calculation with a recursive function.

P.Kumar, Rajalakshmi Engineering COllege 252


Example

<HTML>
<!-- volume.html -->
<HEAD>
<TITLE>Calculating Sphere Volumes</TITLE>
<SCRIPT >
function displayVolume()
{ var radius = parseFloat( myForm.radiusField.value );
window.status = "Volume is " + sphereVolume( radius ); }
function sphereVolume( r )
{ return ( 4.0 / 3.0 ) * Math.PI * Math.pow( r, 3 ); }
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME =" myForm"> Enter radius of sphere<BR>
<INPUT NAME =" radiusField" TYPE =" text">
<INPUT NAME =" calculate" TYPE =" button" VALUE =" Calculate"
ONCLICK =" displayVolume()"> </FORM> </BODY> </HTML>
P.Kumar, Rajalakshmi Engineering COllege 253
Recursion vs. Iteration

• Iteration
– Explicitly uses repetition structures to achieve result
– Terminates when loop-continuation condition fails
– Often faster than recursion
• Recursion
– Repeats through function calls
– Terminates when base case reached
– Slower due to function call overhead
• Each call generates new copy of local variables
– Easy to read and debug when modeling problem with
naturally recursive solution

P.Kumar, Rajalakshmi Engineering COllege 254


JavaScript: Arrays
Outline

Arrays
Declaring and Allocating Arrays
Examples Using Arrays
References and Reference Parameters
Sorting Arrays
Searching Arrays: Linear Search and Binary Search
Multidimensional Arrays

P.Kumar, Rajalakshmi Engineering COllege 255


Objectives

• In this, you will learn:


– To introduce the array data structure.
– To understand the use of arrays to store, sort and search lists
and tables of values.
– To understand how to declare an array, initialize an array
and refer to individual elements of an array.
– To be able to pass arrays to functions.
– To be able to search and sort an array.
– To be able to declare and manipulate multi-dimensional
arrays.

P.Kumar, Rajalakshmi Engineering COllege 256


Arrays

• Ordered set of data elements which can be accessed thru a


single variable
– Each element referenced by a number
• Start at “zeroth element”
• Subscript or index
– Accessing a specific element
• Name of array
• Brackets
• Number of element
– Arrays hold mixed data types
• Var data = [“mon”,34, 76.34,”wed”];

P.Kumar, Rajalakshmi Engineering COllege 257


Arrays
c[ 0 ] -45
Name of array
c[ 1 ] 6

c[ 2 ] 0

c[ 3 ] 72

c[ 4 ] 1543

c[ 5 ] -89

c[ 6 ] 0

c[ 7 ] 62

c[ 8 ] -3

c[ 9 ] 1
Position number (index
or subscript) of the c[ 10 ] 6453
element within array c
c[ 11 ] 78

A 12-element array.

P.Kumar, Rajalakshmi Engineering COllege 258


Arrays

Operators Associativity Type


() [] . left to right highest
++ -- ! right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 11.2 Precedence and associativity of the operators discussed so far.

P.Kumar, Rajalakshmi Engineering COllege 259


Declaring and Allocating Arrays

• Arrays in memory
– Objects
– Operator new
• Allocates memory for objects
• Dynamic memory allocation operator

var c;
c = new Array( 12 );

P.Kumar, Rajalakshmi Engineering COllege 260


Examples Using Arrays

• Possible to declare and initialize in one step


– Specify list of values
• Initializer list
var n = [ 10, 20, 30, 40, 50 ];
var n = new Array( 10, 20, 30, 40, 50 );
– Also possible to only initialize some values
• Leave uninitialized elements blank
• Uninitialized elements default to “undefined”
var n = [ 10, 20, , 40, 50 ];

P.Kumar, Rajalakshmi Engineering COllege 261


Accessing Arrays

<html>
<head>
</head>
<body>
<script>
var data = [“mon, “tue”, 34, 76.34];
var len = data.length;
for(var i=0;i<len;i++)
document.write(data[i] +”,”);
</script>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 262


References and Reference Parameters

• Two ways to pass parameters


– Pass-by-value
• Pass copy of original value
• Default for numbers and booleans
• Original variable is unchanged
– Pass-by-reference
• How objects are passed, like arrays
• Pass location in memory of value
• Allows direct access to original value
• Improves performance

P.Kumar, Rajalakshmi Engineering COllege 263


Sorting Arrays

• Sorting
– Important computing task

P.Kumar, Rajalakshmi Engineering COllege 264


SORTING

<HTML>
<HEAD>
<TITLE>Sorting an Array with Bubble Sort</TITLE>
<SCRIPT>
function start()
{ var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];
document.writeln( "<H1>Sorting an Array</H1>" );
outputArray( "Data items in original order: ", a );
bubbleSort( a ); // sort the array
outputArray( "Data items in ascending order: ", a );
}

P.Kumar, Rajalakshmi Engineering COllege 265


SORTING

function outputArray( header, theArray )


{ document.writeln( "<P>" + header + theArray.join( " " ) + "</P>" );
} // sort the elements of an array with bubble sort
function bubbleSort( theArray )
{
for ( var pass = 1; pass < theArray.length; ++pass ) for ( var i = 0; i <
theArray.length - 1; ++i )
if ( theArray[ i ] > theArray[ i + 1 ] )
swap( theArray, i, i + 1 ); // swap elements
}

P.Kumar, Rajalakshmi Engineering COllege 266


SORTING

• // swap two elements of an array


• function swap( theArray, first, second )
• { var hold; // temporary holding area for swap
hold = theArray[ first ];
• theArray[ first ] = theArray[ second ];
• theArray[ second ] = hold; }
• </SCRIPT>
• </HEAD>
• <BODY ONLOAD =" start()"></BODY>
</HTML>
P.Kumar, Rajalakshmi Engineering COllege 267
Searching Arrays: Linear Search and Binary
Search
• Searching
– Look for matching key value
• Linear search
– Iterate through each element until match found
– Inefficient
• Worst case scenario, must test entire array
• Binary search
– Requires sorted data
– Cuts search range in half each iteration
– Efficient
• Only look at small fraction of elements

P.Kumar, Rajalakshmi Engineering COllege 268


Linear Search

<HTML>
<HEAD> <TITLE>Linear Search of an Array</TITLE>
<SCRIPT LANGUAGE =" JavaScript">
var a = new Array( 100 ); // create an Array // fill Array with
even integer values from 0 to 198
for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i;
// function called when "Search" button is pressed function
buttonPressed()
{
var searchKey = searchForm.inputVal.value;

P.Kumar, Rajalakshmi Engineering COllege 269


Linear Search

var element = linearSearch( a, parseInt( searchKey ) );


if ( element != -1 )
searchForm.result.value = "Found value in element " +
element;
else
searchForm.result.value = "Value not found"; }
// Search "theArray" for the specified "key" value function
linearSearch( theArray, key )
{ for ( var n = 0; n < theArray.length; ++n )
if ( theArray[ n ] == key ) return n;
return -1; }
</SCRIPT> </HEAD>
P.Kumar, Rajalakshmi Engineering COllege 270
SEARCHING

<BODY>
<FORM NAME =" searchForm">
<P>Enter integer search key<BR>
<INPUT NAME =" inputVal" TYPE =" text">
<INPUT NAME =" search" TYPE =" button" VALUE ="
Search" ONCLICK =" buttonPressed()"><BR></P>
<P>Result<BR> <INPUT NAME =" result" TYPE ="
text" SIZE =" 30"></P>
</FORM> </BODY> </HTML>

P.Kumar, Rajalakshmi Engineering COllege 271


SEARCHING

P.Kumar, Rajalakshmi Engineering COllege 272


zMultidimensional Arrays

• Two-dimensional arrays analogous to tables


– Rows and columns
• Specify row first, then column
– Two subscripts

P.Kumar, Rajalakshmi Engineering COllege 273


Multidimensional Arrays

Column 0 Column 1 Column 2 Column 3

Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]

Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]

Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]

Column subscript (or index)

Row subscript (or index)

Array name

Two-dimensional array with three rows and four columns.

P.Kumar, Rajalakshmi Engineering COllege 274


Multidimensional Arrays

• Declaring and initializing multidimensional arrays


– Group by row in square brackets
– Treated as arrays of arrays
– Creating array b with one row of two elements and a second
row of three elements:
var b = [ [ 1, 2 ], [ 3, 4, 5 ] ];

P.Kumar, Rajalakshmi Engineering COllege 275


Multidimensional Arrays

• Also possible to use new operator


– Create array b with two rows, first with five columns and
second with three:
var b;

b = new Array( 2 );
b[ 0 ] = new Array( 5 );
b[ 1 ] = new Array( 3 );

P.Kumar, Rajalakshmi Engineering COllege 276


JavaScript: Objects
Outline
Introduction
Thinking About Objects
Math Object
String Object
Fundamentals of Characters and Strings
Methods of the String Object
Character-Processing Methods
Searching Methods
HTML Markup Methods
Date Object
document Object
window Object

P.Kumar, Rajalakshmi Engineering COllege 277


Introduction
• Use JavaScript to manipulate every element of
HTML document from a script
• Reference for several of JavaScript’s built-in
objects
• Demonstrates the capabilities

P.Kumar, Rajalakshmi Engineering COllege 278


Thinking About Objects
• Objects
– Attributes
– Behaviors
– Encapsulate date and methods
– Property of information hiding
– Details hidden within the objects themselves

P.Kumar, Rajalakshmi Engineering COllege 279


Math Object
• Allow the programmer to perform many common
mathematical calculations
Method Description Example
abs( x ) absolute value of x abs( 7.2 ) is 7.2
abs( 0.0 ) is 0.0
abs( -5.6 ) is 5.6
ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0
integer not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential method ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
floor( x ) rounds x to the largest floor( 9.2 ) is 9.0
integer not greater than x floor( -9.8 ) is -10.0
log( x ) natural logarithm of x log( 2.718282 ) is 1.0
(base e) log( 7.389056 ) is 2.0
max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3

P.Kumar, Rajalakshmi Engineering COllege 280


Math Object

min( x, y ) smaller value of x min( 2.3, 12.7 ) is 2.3


and y min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to power y pow( 2.0, 7.0 ) is 128.0
(xy) pow( 9.0, .5 ) is 3.0
round( x ) rounds x to the round( 9.75 ) is 10
closest integer round( 9.25 ) is 9
sin( x ) trigonometric sine of sin( 0.0 ) is 0.0
x (x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent tan( 0.0 ) is 0.0
of x
(x in radians)
Fig. 12.1 Math object methods.

P.Kumar, Rajalakshmi Engineering COllege 281


String Object
• JavaScript’s string and character-processing
capabilities
• Appropriate for processing names, addresses,
credit card information, etc.

P.Kumar, Rajalakshmi Engineering COllege 282


Fundamentals of Characters and Strings
• Characters
– Fundamental building blocks of JavaScript programs
• String
– Series of characters treated as a single unit

P.Kumar, Rajalakshmi Engineering COllege 283


Methods of the String Object
Method Description
charAt( index ) Returns a string containing the character at the specified index. If there is no
character at the index, charAt returns an empty string. The first character is
located at index 0.
charCodeAt( index ) Returns the Unicode value of the character at the specified index. If there is
no character at the index, charCodeAt returns NaN (Not a Number).
concat( string ) Concatenates its argument to the end of the string that invokes the method.
The string invoking this method is not modified; instead a new String is
returned. This method is the same as adding two strings with the string
concatenation operator + (e.g., s1.concat( s2 ) is the same as s1 +
s2).
fromCharCode( Converts a list of Unicode values into a string containing the corresponding
value1, value2, ) characters.
indexOf( Searches for the first occurrence of substring starting from position index in
substring, index ) the string that invokes the method. The method returns the starting index of
substring in the source string or –1 if substring is not found. If the index
argument is not provided, the method begins searching from index 0 in the
source string.
lastIndexOf( Searches for the last occurrence of substring starting from position index and
substring, index ) searching toward the beginning of the string that invokes the method. The
method returns the starting index of substring in the source string or –1 if
substring is not found. If the index argument is not provided, the method
begins searching from the end of the source string.
String object methods.
P.Kumar, Rajalakshmi Engineering COllege 284
Methods of the String Object

slice( start, end ) Returns a string containing the portion of the string from index start
through index end. If the end index is not specified, the method returns a
string from the start index to the end of the source string. A negative end
index specifies an offset from the end of the string starting from a
position one past the end of the last character (so –1 indicates the last
character position in the string).
split( string ) Splits the source string into an array of strings (tokens) where its string
argument specifies the delimiter (i.e., the characters that indicate the end
of each token in the source string).
substr( Returns a string containing length characters starting from index start in
start, length ) the source string. If length is not specified, a string containing characters
from start to the end of the source string is returned.
substring( Returns a string containing the characters from index start up to but not
start, end ) including index end in the source string.
toLowerCase() Returns a string in which all uppercase letters are converted to lowercase
letters. Non-letter characters are not changed.
toUpperCase() Returns a string in which all lowercase letters are converted to uppercase
letters. Non-letter characters are not changed.
toString() Returns the same string as the source string.
valueOf() Returns the same string as the source string.

String object methods.

P.Kumar, Rajalakshmi Engineering COllege 285


• Split(string) – splits the string with delimiter
var a = “wel come”
var b = a.split(“ “)
Solution: wel & come
• Substring(start, end)
Example: var a = “welcome”
Var b = a.substring(0,2); wel
Var c = a.substring(3,6); come

P.Kumar, Rajalakshmi Engineering COllege 286


Character Processing Methods
• charAt
– Returns the character at specific position
• charCodeAt
– Returns Unicode value of the character at specific position
• fromCharCode
– Returns string created from series of Unicode values
• toLowerCase
– Returns lowercase version of string
• toUpperCase
– Returns uppercase version of string

P.Kumar, Rajalakshmi Engineering COllege 287


1 <?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 12.4: CharacterProcessing.html --> CharacterProcessing.
html
6 <!-- Character Processing Methods -->
1 of 2
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Character Processing Methods</title>
11
12 <script type = "text/javascript">
13 <!--
14 var s = "ZEBRA";
15 var s2 = "AbCdEfG";
16
17 document.writeln( "<p>Character at index 0 in '" +
18 s + "' is " + s.charAt( 0 ) );
19 document.writeln( "<br />Character code at index 0 in '"
20 + s + "' is " + s.charCodeAt( 0 ) + "</p>" );
21
22 document.writeln( "<p>'" +
23 String.fromCharCode( 87, 79, 82, 68 ) +
24 "' contains character codes 87, 79, 82 and 68</p>" )
25

P.Kumar, Rajalakshmi Engineering COllege 288


26 document.writeln( "<p>'" + s2 + "' in lowercase is '" +
s2.toLowerCase() + "'" );
27
Outline
28 document.writeln( "<br />'" + s2 + "' in uppercase is '"
29 + s2.toUpperCase() + "'</p>" );
30 // --> CharacterProcessing.
html
31 </script>
2 of 2
32
33 </head><body></body>
34 </html>

P.Kumar, Rajalakshmi Engineering COllege 289


HTML Markup Methods
• Anchor
– <a name = “top”> Anchor </a>
• Blink
– <blink> blinking text </blink>
• Fixed
– <tt> monospaced text </tt>
• Strike
– <strike> strike out text </strike>
• Subscript
– <sub> subscript </sub>
• Superscript
– <sup> superscript </sup>
P.Kumar, Rajalakshmi Engineering COllege 290
1 <?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 12.7: MarkupMethods.html --> MarkupMethods.html
1 of 2
6 <!-- XHTML markup methods of the String object -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>XHTML Markup Methods of the String Object</title>
11
12 <script type = "text/javascript">
13 <!--
14 var anchorText = "This is an anchor",
15 blinkText = "This is blinking text",
16 fixedText = "This is monospaced text",
17 linkText = "Click here to go to anchorText",
18 strikeText = "This is strike out text",
19 subText = "subscript",
20 supText = "superscript";
21
22 document.writeln( anchorText.anchor( "top" ) );
23 document.writeln( "<br />" + blinkText.blink() );
24 document.writeln( "<br />" + fixedText.fixed() );
25 document.writeln( "<br />" + strikeText.strike() );

P.Kumar, Rajalakshmi Engineering COllege 291


26 document.writeln(
"<br />This is text with a " + subText.sub() );
27
Outline
28 document.writeln(
29 "<br />This is text with a " + supText.sup() );
30 document.writeln( MarkupMethods.html
2 of 2
31 "<br />" + linkText.link( "#top" ) );
32 // -->
33 </script>
34
35 </head><body></body>
36 </html>

P.Kumar, Rajalakshmi Engineering COllege 292


Date Object
• Provides methods for date and time manipulations
Method Desc ription
getDate() Returns a number from 1 to 31 representing the day of the month in local time or UTC, respectively.
getUTCDate()
getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC,
getUTCDay() respectively.

getFullYear() Returns the year as a four-digit number in local time or UTC, respectively.
getUTCFullYear()
getHours() Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.
getUTCHours()
getMilliseconds() Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively.
getUTCMilliSeconds() The time is stored in hours, minutes, seconds and milliseconds.

getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.
getUTCMinutes()
getMonth() Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC,
getUTCMonth() respectively.
getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.
getUTCSeconds()
getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object.

getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTC—previously
known as Greenwich Mean Time (GMT).

setDate( val ) Sets the day of the month (1 to 31) in local time or UTC, respectively.
setUTCDate( val )
Fig. 12.8 Methods of the Date object.

P.Kumar, Rajalakshmi Engineering COllege 293


Date Object
Method De sc rip tio n
setFullYear( y, m, d ) Sets the year in local time or UTC, respectively. The second and third
arguments representing the month and the date are optional. If an optional
setUTCFullYear( y, m, d ) argument is not specified, the current value in the Date object is used.

setHours( h, m, s, ms ) Sets the hour in local time or UTC, respectively. The second, third and fourth
arguments representing the minutes, seconds and milliseconds are optional. If
setUTCHours( h, m, s, ms ) an optional argument is not specified, the current value in the Date object is
used.

setMilliSeconds( ms ) Sets the number of milliseconds in local time or UTC, respectively.


setUTCMilliseconds( ms )
setMinutes( m, s, ms ) Sets the minute in local time or UTC, respectively. The second and third
arguments representing the seconds and milliseconds are optional. If an
setUTCMinutes( m, s, ms ) optional argument is not specified, the current value in the Date object is
used.

setMonth( m, d ) Sets the month in local time or UTC, respectively. The second argument
representing the date is optional. If the optional argument is not specified, the
setUTCMonth( m, d ) current date value in the Date object is used.

setSeconds( s, ms ) Sets the second in local time or UTC, respectively. The second argument
representing the milliseconds is optional. If this argument is not specified, the
setUTCSeconds( s, ms ) current millisecond value in the Date object is used.

Fig. 12.8 Methods of the Date object.


P.Kumar, Rajalakshmi Engineering COllege 294
Date Object

Method De sc rip tion


setTime( ms ) Sets the time based on its argument—the number of elapsed milliseconds
since January 1, 1970.
toLocaleString() Returns a string representation of the date and time in a form specific to the
computer’s locale. For example, September 13, 2001 at 3:42:22 PM is
represented as 09/13/01 15:47:22 in the United States and 13/09/01
15:47:22 in Europe.

toUTCString() Returns a string representation of the date and time in the form: 19 Sep
2001 15:47:22 UTC
toString() Returns a string representation of the date and time in a form specific to the
locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United
States).
valueOf() The time in number of milliseconds since midnight, January 1, 1970.

Fig. 12.8 Methods of the Date object.

P.Kumar, Rajalakshmi Engineering COllege 295


1 <?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 12.9: DateTime.html --> DateTime.html
1 of 3
6 <!-- Date and Time Methods -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Date and Time Methods</title>
11
12 <script type = "text/javascript">
13 <!--
14 var current = new Date();
15
16 document.writeln(
17 "<h1>String representations and valueOf</h1>" );
18 document.writeln( "toString: " + current.toString() +
19 "<br />toLocaleString: " + current.toLocaleString() +
20 "<br />toUTCString: " + current.toUTCString() +
21 "<br />valueOf: " + current.valueOf() );
22
23 document.writeln(
24 "<h1>Get methods for local time zone</h1>" );

P.Kumar, Rajalakshmi Engineering COllege 296


25 document.writeln( "getDate: " + current.getDate() +
"<br />getDay: " + current.getDay() +
26
Outline
27 "<br />getMonth: " + current.getMonth() +
28 "<br />getFullYear: " + current.getFullYear() +
29 "<br />getTime: " + current.getTime() + DateTime.html
2 of 3
30 "<br />getHours: " + current.getHours() +
31 "<br />getMinutes: " + current.getMinutes() +
32 "<br />getSeconds: " + current.getSeconds() +
33 "<br />getMilliseconds: " +
34 current.getMilliseconds() +
35 "<br />getTimezoneOffset: " +
36 current.getTimezoneOffset() );
37
38 document.writeln(
39 "<h1>Specifying arguments for a new Date</h1>" );
40 var anotherDate = new Date( 2001, 2, 18, 1, 5, 0, 0 );
41 document.writeln( "Date: " + anotherDate );
42
43 document.writeln(
44 "<h1>Set methods for local time zone</h1>" );
45 anotherDate.setDate( 31 );
46 anotherDate.setMonth( 11 );
47 anotherDate.setFullYear( 2001 );
48 anotherDate.setHours( 23 );
49 anotherDate.setMinutes( 59 );

P.Kumar, Rajalakshmi Engineering COllege 297


50 anotherDate.setSeconds( 59 );
document.writeln( "Modified date: " + anotherDate );
51
Outline
52 // -->
53 </script>
54 DateTime.html
3 of 3
55 </head><body></body>
56 </html>

P.Kumar, Rajalakshmi Engineering COllege 298


document Object
• Manipulate document that is currently visible in
the browser window
Method or Property Description
write( string ) Writes the string to the XHTML document as
XHTML code.
writeln( string ) Writes the string to the XHTML document as
XHTML code and adds a newline character at
the end.
document.cookie This property is a string containing the values
of all the cookies stored on the user’s computer
for the current document. See Section 12.9,
Using Cookies.
document.lastModified This property is the date and time that this
document was last modified.
Fig. 12.12 Important document object methods and properties.

P.Kumar, Rajalakshmi Engineering COllege 299


window Object
• Provides methods for manipulating browser window
Method or Property Description
open( url, name, options ) Creates a new window with the URL of the window set to
url, the name set to name, and the visible features set by
the string passed in as option.
prompt( prompt, default ) Displays a dialog box asking the user for input. The text
of the dialog is prompt, and the default value is set to
default.
close() Closes the current window and deletes its object from
memory.
window.focus() This method gives focus to the window (i.e., puts the
window in the foreground, on top of any other open
browser windows).
window.document This property contains the document object representing
the document currently inside the window.
window.closed This property contains a boolean value that is set to true if
the window is closed, and false if it is not.
window.opener This property contains the window object of the window
that opened the current window, if such a window exists.
Fig. 12.14 Important window object methods and properties.

P.Kumar, Rajalakshmi Engineering COllege 300


IT1451 – WEB TECHNOLOGY

8TH SEMESTER – INFORMATION TECHNOLOGY

UNIT – 2 NOTES

P.Kumar, Rajalakshmi Engineering COllege 301


Dynamic HTML: Object Model and
Collections
Outline
Introduction
Object Referencing
Collections all and children
Dynamic Styles
Dynamic Positioning
Using the frames Collection
navigator Object
Summary of the DHTML Object Model

P.Kumar, Rajalakshmi Engineering COllege 302


Introduction

• Dynamic HTML Object Model


– Allows Web authors to control the presentation of their pages
– Gives them access to all the elements on their pages
• Web page
– Elements, forms, frames, tables
– Represented in an object hierarchy
• Scripting
– Retrieve and modify properties and attributes

P.Kumar, Rajalakshmi Engineering COllege 303


Object Referencing

• The simplest way to reference an element is by using the


element’s id attribute.
• The element is represented as an object
– HTML attributes become properties that can be manipulated by
scripting

P.Kumar, Rajalakshmi Engineering COllege 304


Object Referencing

<html>
<head>
<title>Object Model</title>
<script>
function start()
{
alert(ptext.innerText);
ptext.innerText = "Thanks for coming";
} </script>
</head>
<body onload="start()">
<p id="ptext"> Welcome to our web page</p>
</body> </html> P.Kumar, Rajalakshmi Engineering COllege 305
P.Kumar, Rajalakshmi Engineering COllege 306
Collections all and children

• Collections
– Arrays of related objects on a page
– all
• all the HTML elements in a document
– children
• Specific element contains that element’s child elements

P.Kumar, Rajalakshmi Engineering COllege 307


Dynamic Styles

• Element’s style can be changed dynamically


• Dynamic HTML Object Model also allows you to change
the class attribute

P.Kumar, Rajalakshmi Engineering COllege 308


dynamicstyle.html

<HTML>
<HEAD> <TITLE>Object Model</TITLE> <SCRIPT >
function start()
{ var a = prompt( "Enter a color name for the " +
"background of this page", "" );
document.body.style.backgroundColor = a;
}
</SCRIPT> </HEAD>
<BODY ONLOAD =" start()"> <P>Welcome to our
Web site!</P> </BODY>
</HTML>
P.Kumar, Rajalakshmi Engineering COllege 309
P.Kumar, Rajalakshmi Engineering COllege 310
dynamicstyle2

<HEAD> <TITLE>Object Model</TITLE>


<STYLE>
.bigText { font-size: 3em; font-weight: bold }
.smallText { font-size: .75em }
</STYLE>
<SCRIPT LANGUAGE =" JavaScript">
function start()
{ var a = prompt( "Enter a className for the text " +
"(bigText or smallText)", "" );
pText.className = a; }
</SCRIPT> </HEAD>

P.Kumar, Rajalakshmi Engineering COllege 311


dynamicstyle2

<BODY ONLOAD =" start()">


<P ID =" pText">Welcome to our Web site!</P> </BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 312


P.Kumar, Rajalakshmi Engineering COllege 313
Dynamic Positioning

• HTML elements can be positioned with scripting


– Declare an element’s CSS position property to be either absolute
or relative
– Move the element by manipulating any of the top, left, right or
bottom CSS properties

P.Kumar, Rajalakshmi Engineering COllege 314


1 <?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 13.6: dynamicposition.html --> dynamicposition
6 <!-- Dynamic Positioning --> .html
7 (1 of 3)
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Dynamic Positioning</title>
11
12 <script type = "text/javascript">
13 <!--
14 var speed = 5;
15 var count = 10;
16 var direction = 1;
17 var firstLine = "Text growing";
18 var fontStyle = [ "serif", "sans-serif", "monospace" ];
19 var fontStylecount = 0;
20
21 function start()
22 {
23 window.setInterval( "run()", 100 );
24 }
25

P.Kumar, Rajalakshmi Engineering COllege 315


26 function run()
27 {
Outline
28 count += speed;
29
30 if ( ( count % 200 ) == 0 ) { dynamicposition
31 speed *= -1; .html
32 direction = !direction; (2 of 3)
33
34 pText.style.color =
35 ( speed < 0 ) ? "red" : "blue" ;
36 firstLine =
37 ( speed < 0 ) ? "Text shrinking" : "Text growing";
38 pText.style.fontFamily =
39 fontStyle[ ++fontStylecount % 3 ];
40 }
41
42 pText.style.fontSize = count / 3;
43 pText.style.left = count;
44 pText.innerHTML = firstLine + "<br /> Font size: " +
45 count + "px";
46 }
47 // -->
48 </script>
49 </head>
50

P.Kumar, Rajalakshmi Engineering COllege 316


51 <body onload = "start()">
52 <p id = "pText" style = "position: absolute; left: 0;
Outline
53 font-family: serif; color: blue">
54 Welcome!</p>
55 </body> dynamicposition
56 </html> .html
(3 of 3)

P.Kumar, Rajalakshmi Engineering COllege 317


P.Kumar, Rajalakshmi Engineering COllege 318
Using the frames Collection

• Referencing elements and objects in different frames by


using the frames collection
<HTML>
<!-- index.html --> <!-- Using the frames collection -->
<HEAD> <TITLE>Frames collection</TITLE> </HEAD>
<FRAMESET ROWS =" 100, *">
<FRAME SRC =" top.html" NAME =" upper">
<FRAME SRC =" " NAME =" lower">
</FRAMESET> </HTML>

P.Kumar, Rajalakshmi Engineering COllege 319


<HTML> <!-- top.html --> <!-- Cross-frame scripting -->
<HEAD> <TITLE>The frames collection</TITLE>
<SCRIPT > function start()
{ var text = prompt( "What is your name?", "" );
parent.frames( "lower" ).document.write( "<H1>Hello, " +
text + "</H1>" ); }
</SCRIPT> </HEAD>
<BODY ONLOAD =" start()"> <H1>Cross-frame
scripting!</H1> </BODY> </HTML>

P.Kumar, Rajalakshmi Engineering COllege 320


P.Kumar, Rajalakshmi Engineering COllege 321
navigator Object

• Netscape, Mozilla, Microsoft’s Internet Explorer


– Others as well
• Contains information about the Web browser
• Allows Web authors to determine what browser the user is
using

P.Kumar, Rajalakshmi Engineering COllege 322


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig 13.9: navigator.html --> navigator.html
6 <!-- Using the navigator object --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>The navigator Object</title>
11
12 <script type = "text/javascript">
13 <!--
14 function start()
15 {
16 if (navigator.appName=="Microsoft Internet Explorer")
17 {
18 if ( navigator.appVersion.substring( 1, 0 ) >= "4" )
19 document.location = "newIEversion.html";
20 else
21 document.location = "oldIEversion.html";
22 }
23 else
24 document.location = "NSversion.html";
25 }

P.Kumar, Rajalakshmi Engineering COllege 323


26 // -->
27 </script>
Outline
28 </head>
29
30 <body onload = "start()"> navigator.html
31 <p>Redirecting your browser to the appropriate page, (2 of 2)
32 please wait...</p>
33 </body>
34 </html>

P.Kumar, Rajalakshmi Engineering COllege 324


Summary of the DHTML Object Model
window

document all

frames document anchors

history document applets

navigator body
plugins
location embeds

event filters

screen forms

images

Key links

object plugins

collection scripts

styleSheets

Fig. 13.10 DHTML Object Model.


P.Kumar, Rajalakshmi Engineering COllege 325
Summary of the DHTML Object Model
Object or collection Description
Objects
window Represents the browser window and provides access to the document object contained
in the window. If the window contains frames a separate window object is created
automatically for each frame, to provide access to the document rendered in the frame.
Frames are considered to be subwindows in the browser.
document Represents the XHTML document rendered in a window. The document object
provides access to every element in the XHTML document and allows dynamic
modification of the XHTML document.
body Provides access to the body element of an XHTML document.
history Keeps track of the sites visited by the browser user. The object provides a script
programmer with the ability to move forward and backward through the visited sites, but
for security reasons does not allow the actual site URLs to be manipulated.
navigator Contains information about the Web browser, such as the name of the browser, the
version of the browser, the operating system on which the browser is running and other
information that can help a script writer customize the user’s browsing experience.
location Contains the URL of the rendered document. When this object is set to a new URL, the
browser immediately switches (navigates) to the new location.
event Can be used in an event handler to obtain information about the event that occurred (e.g.,
the mouse x-y coordinates during a mouse event).
screen Contains information about the computer screen for the computer on which the browser
is running. Information such as the width and height of the screen in pixels can be used to
determine the size at which elements should be rendered in a Web page.
Fig. 13.11 Objects in the Internet Explorer 6 Object Model.

P.Kumar, Rajalakshmi Engineering COllege 326


Summary of the DHTML Object Model
Object or collection Description
Collections
all Many objects have an all collection that provides access to every element contained in
the object. For example, the body object’s all collection provides access to every
element in the body element of an XHTML document.
anchors Collection contains all the anchor elements (a) that have a name or id attribute. The
elements appear in the collection in the order they were defined in the XHTML
document.
applets Contains all the applet elements in the XHTML document. Currently, the most
common applet elements are Java applets.
embeds Contains all the embed elements in the XHTML document.
forms Contains all the form elements in the XHTML document. The elements appear in the
collection in the order they were defined in the XHTML document.
frames Contains window objects that represent each frame in the browser window. Each frame
is treated as its own subwindow.
images Contains all the img elements in the XHTML document. The elements appear in the
collection in the order they were defined in the XHTML document.
links Contains all the anchor elements (a) with an href property. This collection also
contains all the area elements that represent links in an image map.
Fig. 13.11 Objects in the Internet Explorer 6 Object Model.

P.Kumar, Rajalakshmi Engineering COllege 327


Summary of the DHTML Object Model
Object or collection Description
plugins Like the embeds collection, this collection contains all the embed elements in the
XHTML document.
scripts Contains all the script elements in the XHTML document.

styleSheets Contains styleSheet objects that represent each style element in the XHTML
document and each style sheet included in the XHTML document via link.
Fig. 13.11 Objects in the Internet Explorer 6 Object Model.

P.Kumar, Rajalakshmi Engineering COllege 328


Dynamic HTML: Event Model
Outline
Introduction
Event onclick
Event onload
Error Handling with onerror
Tracking the Mouse with Event onmousemove
Rollovers with onmouseover and onmouseout
Form Processing with onfocus and onblur
More Form Processing with onsubmit and onreset
Event Bubbling
More DHTML Events

P.Kumar, Rajalakshmi Engineering COllege 329


Introduction
• Event model
– Scripts can respond to user
– Content becomes more dynamic
– Interfaces become more intuitive

P.Kumar, Rajalakshmi Engineering COllege 330


Event onclick
• onClick
– Invoked when user clicks the mouse on a specific item

P.Kumar, Rajalakshmi Engineering COllege 331


Event onclick
<HTML>
<HEAD>
<TITLE>DHTML Event Model - ONCLICK</TITLE>
<!-- The FOR attribute declares the script for a certain -->
<!-- element, and the EVENT for a certain event. -->

<SCRIPT LANGUAGE ="JavaScript" FOR ="para" EVENT ="onclick">

alert( "Hi there" );


</SCRIPT>
</HEAD>
<BODY>
<!-- The ID attribute gives a unique identifier -->
<P ID ="para">Click on this text!</P>
<!-- You can specify event handlers inline -->
<INPUT TYPE =" button" VALUE =" Click Me!" ONCLICK =" alert( 'Hi
again' )";>
</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 332


Outline

P.Kumar, Rajalakshmi Engineering COllege 333


Event onload

• onload event
– Fires when an element finishes loading
– Used in the body element
– Initiates a script after the page loads into the client
<html>
<head>
<script >
function mymessage()
{
alert("This message was triggered from the onload event");
}
</script>
</head>
<body onload="mymessage()">
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 334
Error Handling with onerror

• onerror event
– Execute specialized error-handling code

P.Kumar, Rajalakshmi Engineering COllege 335


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- Fig 14.3: onerror.html --> onerror.html
6 <!-- Demonstrating the onerror event --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>DHTML Event Model - onerror</title>
11 <script type = "text/javascript">
12 <!--
13 // Specify that if an onerror event is triggered
14 // in the window function handleError should execute
15 window.onerror = handleError;
16
17 function doThis() {
18 alrrt( "hi" ); // alert misspelled, creates an error
19 }
20
21 // The ONERROR event passes three values to the
22 // function: the name of the error, the url of
23 // the file, and the line number.
24 function handleError( errType, errURL, errLineNum )
25 {

P.Kumar, Rajalakshmi Engineering COllege 336


26 // Writes to the status bar at the
27 // bottom of the window.
Outline
28 window.status = "Error: " + errType + " on line " +
29 errLineNum;
30 onerror.html
31 // Returning a value of true cancels the (2 of 2)
32 // browser’s reaction.
33 return true;
34 }
35 // -->
36 </script>
37 </head>
38
39 <body>
40
41 <input id = "mybutton" type = "button" value = "Click Me!"
42 onclick = "doThis()" />
43
44 </body>
45 </html>

P.Kumar, Rajalakshmi Engineering COllege 337


Tracking the Mouse with Event
onmousemove
• onmousemove
– Fires repeatedly when the user moves the mouse over the
Web page
– Gives position of the mouse

P.Kumar, Rajalakshmi Engineering COllege 338


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5 <!-- Fig. 14.4: onmousemove.html --> onmousemove.html
6 <!-- Demonstrating the onmousemove event --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>DHTML Event Model - onmousemove event</title>
11 <script type = "text/javascript">
12 <!--
13 function updateMouseCoordinates()
14 {
15 coordinates.innerText = event.srcElement.tagName +
16 " (" + event.offsetX + ", " + event.offsetY + ")";
17 }
18 // -->
19 </script>
20 </head>
21
22 <body style = "back-groundcolor: wheat"
23 onmousemove = "updateMouseCoordinates()">
24

P.Kumar, Rajalakshmi Engineering COllege 339


25 <span id = "coordinates">(0, 0)</span><br />
26 <img src = "deitel.gif" style = "position: absolute;
Outline
27 top: 100; left: 100" alt = "Deitel" />
28
29 </body> onmousemove.html
30 </html> (2 of 2)

P.Kumar, Rajalakshmi Engineering COllege 340


Rollovers with onmouseover and
onmouseout
• Events fired by mouse movements
– onmouseover
• Mouse cursor moves over element
– Onmouseout
• Mouse cursor leaves element
– Onmousedown
• Fires when a mouse button is pressed down
– Onmouseup
• Fires when a mouse button is released

P.Kumar, Rajalakshmi Engineering COllege 341


Rollovers with onmouseover and
onmouseout
<html>
<body>
<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">
Mouse over this text</h1>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 342


Onmousedown, Onmouseup
<head>
<script >
function lighton()
{
document.getElementById('myimage').src="bulbon.gif";
}
function lightoff()
{
document.getElementById('myimage').src="bulboff.gif";
}
</script>
</head>

<body>
<img id="myimage" onmousedown="lighton()" onmouseup="lightoff()"
src="bulboff.gif" width="100" height="180">
<p>Click to turn on the light</p>
</body>
</html> P.Kumar, Rajalakshmi Engineering COllege 343
onmousemove

<html>
<head>
<script >
var i=1;
function moveright()
{
document.getElementById('header').style.position="relative";
document.getElementById('header').style.left=i;
i++;
}
</script>
</head>
<body onmousemove="moveright()">
<h1 id="header"> Move the mouse over this page </h1>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 344
Form Processing with onfocus and
onblur
• onfocus event fires when element gains focus
• onblur event fires when element loses focus

P.Kumar, Rajalakshmi Engineering COllege 345


Form Processing with onfocus

<html>
<head>
<script >
function message()
{
alert("This alert box was triggered by the onfocus event handler");
}
</script>
</head>
<body>
<form>
Enter your name: <input type="text" onfocus="message()" size="20">
</form>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 346
Form Processing with onblur
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was triggered by the onblur event handler");
}
</script>
</head>
<body>
<p>The onblur event occurs when an element loses focus. Try to click or write in
the input field below, then click elsewhere in the document so the input field
loses focus.</p>
<form>
Enter your name: <input type="text" onblur="message()" size="20">
</form>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 347


More Form Processing with onsubmit and
onreset
• onsubmit and onreset are useful events for processing forms
<html>
<head>
<script type="text/javascript">
function confirmInput()
{
fname=document.forms[0].fname.value;
alert("Hello " + fname + "! You will now be redirected to www.rajalakshmi.org ");
}
</script>
</head>
<body>
<form onsubmit="confirmInput()" action="http://www.rajalakshmi.org/">
Enter your name: <input id="fname" type="text" size="20">
<input type="submit">
</form>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 348


Form Processing with onreset

<html>
<head>
<script>
function message()
{
alert("This alert box was triggered by the onreset event handler");
}
</script>
</head>
<body>
<form onreset="message()">
Enter your name: <input type="text" size="20">
<input type="reset">
</select>
</form>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 349
Event Bubbling

• Crucial part of the event model


• Process whereby events fired in child elements
“bubble” up to their parent elements

P.Kumar, Rajalakshmi Engineering COllege 350


1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
Outline
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig 14.9: bubbling.html --> bubbling.html
6 <!-- Disabling event bubbling --> (1 of 2)
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>DHTML Event Model - Event Bubbling</title>
11
12 <script type = "text/javascript">
13 <!--
14 function documentClick()
15 {
16 alert( "You clicked in the document" );
17 }
18
19 function paragraphClick( value )
20 {
21 alert( "You clicked the text" );
22
23 if ( value )
24 event.cancelBubble = true;
25 }

P.Kumar, Rajalakshmi Engineering COllege 351


26
27 document.onclick = documentClick;
Outline
28 // -->
29 </script>
30 </head> bubbling.html
31 (2 of 2)
32 <body>
33
34 <p onclick = "paragraphClick( false )">Click here!</p>
35 <p onclick = "paragraphClick( true )">Click here, too!</p>
36 </body>
37 </html>

P.Kumar, Rajalakshmi Engineering COllege 352


P.Kumar, Rajalakshmi Engineering COllege 353
More DHTML Events

• Remaining DHTML events and their descriptions

P.Kumar, Rajalakshmi Engineering COllege 354


More DHTML Events
Event Description
Clipboard events
onbeforecut Fires before a selection is cut to the clipboard.
onbeforecopy Fires before a selection is copied to the clipboard.
onbeforepaste Fires before a selection is pasted from the clipboard.
oncopy Fires when a selection is copied to the clipboard.
oncut Fires when a selection is cut to the clipboard.
onabort Fires if image transfer has been interrupted by user.
onpaste Fires when a selection is pasted from the clipboard.
Data binding events
onafterupdate Fires immediately after a databound object has been updated.
onbeforeupdate Fires before a data source is updated.
oncellchange Fires when a data source has changed.
ondataavailable Fires when new data from a data source become available.
ondatasetchanged Fires when content at a data source has changed.
ondatasetcomplete Fires when transfer of data from the data source has
completed.
onerrorupdate Fires if an error occurs while updating a data field.
onrowenter Fires when a new row of data from the data source is
available.
onrowexit Fires when a row of data from the data source has just
finished.
onrowsdelete Fires when a row of data from the data source is deleted.
onrowsinserted Fires when a row of data from the data source is inserted.
Fig. 14.10 Dynamic HTML events.
P.Kumar, Rajalakshmi Engineering COllege 355
More DHTML Events
Event Description
Keyboard events
onhelp Fires when the user initiates help (i.e., by pressing the F1 key).
onkeydown Fires when the user pushes down a key.
onkeypress Fires when the user presses a key.
onkeyup Fires when the user ends a key press.
Marquee events
onbounce Fires when a scrolling marquee bounces back in the other
direction.
onfinish Fires when a marquee finishes its scrolling.
onstart Fires when a marquee begins a new loop.
Mouse events
oncontextmenu Fires when the context menu is shown (right-click).
ondblclick Fires when the mouse is double clicked.
ondrag Fires during a mouse drag.
ondragend Fires when a mouse drag ends.
ondragenter Fires when something is dragged onto an area.
ondragleave Fires when something is dragged out of an area.
ondragover Fires when a drag is held over an area.
ondragstart Fires when a mouse drag begins.
ondrop Fires when a mouse button is released over a valid target
during a drag.
onmousedown Fires when a mouse button is pressed down.
Fig. 14.10 Dynamic HTML events.
P.Kumar, Rajalakshmi Engineering COllege 356
More DHTML Events
Event Description
onmouseup Fires when a mouse button is released.
Miscellaneous events
onafterprint Fires immediately after the document prints.
onbeforeeditfocus Fires before an element gains focus for editing.
onbeforeprint Fires before a document is printed.
onbeforeunload Fires before a document is unloaded (i.e., the window was closed or a link was
clicked).
onchange Fires when a new choice is made in a select element, or when a text input is
changed and the element loses focus.
onfilterchange Fires when a filter changes properties or finishes a transition (see Chapter 15,
Dynamic HTML: Filters and Transitions).
onlosecapture Fires when the releaseCapture method is invoked.
onpropertychange Fires when the property of an object is changed.
onreadystatechange Fires when the readyState property of an element
changes.
onreset Fires when a form resets (i.e., the user clicks a reset button).
onresize Fires when the size of an object changes (i.e., the user resizes a window or frame).
onscroll Fires when a window or frame is scrolled.
onselect Fires when a text selection begins (applies to input or
textarea).
onselectstart Fires when the object is selected.
onstop Fires when the user stops loading the object.
onunload Fires when a page is about to unload.
Fig. 14.10 Dynamic HTML events.
P.Kumar, Rajalakshmi Engineering COllege 357
Dynamic HTML: Filters and Transitions

Outline
Introduction
Flip Filters: flipv and fliph
Transparency with the chroma Filter
Creating Image masks
Miscellaneous Image Filters: invert, gray and xray
Adding shadows to Text
Creating Gradients with alpha
Making Text glow
Creating Motion with blur
Using the wave Filter
Advanced Filters: dropShadow and light
blendTrans Transition
revealTrans Transition

P.Kumar, Rajalakshmi Engineering COllege 358


Introduction

• Filters
– Cause changes that are persistent
• Transitions
– Temporary
– Allow transfer from one page to another with pleasant visual
effect
• For example, random dissolve

P.Kumar, Rajalakshmi Engineering COllege 359


Flip Filters: flipv and fliph

• flipv and fliph filters mirror text or images


vertically and horizontally, respectively

P.Kumar, Rajalakshmi Engineering COllege 360


Example
<HTML>

<!-- Using the flip filters -->

<HEAD> <TITLE>The flip filter</TITLE></HEAD>

<BODY>

<TABLE>
<TR>
<!-- Filters are applied in style declarations -->
<TD STYLE = "filter: fliph">Text</TD>
<TD>Text</TD>
</TR>
<TR>
<!-- More than one filter can be applied at once -->
<TD STYLE = "filter:. flipv fliph">Text</TD>
<TD STYLE = "filter: flipv">Text</TD>
</TR>
</TABLE>
</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 361


fliph filter applied No filters applied

Both fliph and flipv flipv filter applied


filters applied

P.Kumar, Rajalakshmi Engineering COllege 362


Transparency with the chroma Filter

• chroma filter applies transparency effects


dynamically
– Without using a graphics editor to hard-code transparency
into the image
• onchange
– Fires when the value of a form changes

P.Kumar, Rajalakshmi Engineering COllege 363


Creating Image masks

• Background is a solid color


• Foreground is transparent to the image or color
behind it

P.Kumar, Rajalakshmi Engineering COllege 364


Example
<HTML>
<!-- Placing a mask over an image -->
<HEAD>
<TITLE>Mask Filter</TITLE>
</HEAD>
<BODY>

<H1>Mask Filter</H1>

<DIV STYLE = "position: absolute; top: 125; left: 20;


filter: mask( color = #CCFFFF )">
<H1 STYLE = "font-family: Courier, monospace">
AaBbCcDdEeFfGgHhIiJj<BR>KkLlMmNnOoPpQqRrSsTt
</H1>
</DIV>
<IMG SRC = "gradient.gif" WIDTH = "400" HEIGHT = "200">
</BODY>
</HTML>
P.Kumar, Rajalakshmi Engineering COllege 365
Outline

P.Kumar, Rajalakshmi Engineering COllege 366


Image Filters: invert, gray and xray

• invert filter
– Negative image effect
• Dark areas become light and light areas become dark
• gray filter
– Grayscale image effect
• All color is stripped from the image, only brightness data
remains
• xray filter
– X-ray effect
• Inversion of the grayscale effect

P.Kumar, Rajalakshmi Engineering COllege 367


Example
<HTML>
<!-- Image filters to invert, grayscale, or xray an image -->
<HEAD><TITLE>Misc. Image filters</TITLE></HEAD>
<BODY>
<TABLE>
<TR CLASS = "cap">
<TD>Normal</TD>
<TD>Grayscale</TD>
<TD>Xray</TD>
<TD>Invert</TD>
</TR>
<TR>
<TD><IMG SRC = "harvey.jpg"></TD>
<TD><IMG SRC = "harvey.jpg" STYLE = "filter: gray"></TD>
<TD><IMG SRC = "harvey.jpg" STYLE = "filter: xray"></TD>
<TD><IMG SRC = "harvey.jpg" STYLE = "filter: invert"></TD>
</TR>
</TABLE>
</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 368


P.Kumar, Rajalakshmi Engineering COllege 369
Adding shadows to Text
• shadow filter
– Showing effect
• Three-dimensional appearance
<html>
<head>
<style>
h2
{
width:100%;
}
</style>
</head>

<body>

<h2 style="filter:glow()">Glow</h2>
<h2 style="filter:blur()">Blur</h2>
<h2 style="filter:fliph()">Flip H</h2>
<h2 style="filter:flipv()">Flip V</h2>
<h2 style="filter:shadow()">Shadow</h2>
<h2 style="filter:dropshadow()">Drop Shadow</h2>
<h2 style="filter:wave(Strength=2)">Wave</h2>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 370
blendTrans Transition

• Example of the blendTrans transition


– Creates a smooth fade-in/fade-out effect

P.Kumar, Rajalakshmi Engineering COllege 371


blendTrans Transition

• The blendTrans() filter fades an element out or


in. It can be applied only through scripting.
• Three steps are required.
1. First, a duration value is established giving the
number of seconds for the transition to take
place. The general format is shown below.
• object.style.filter="blendTrans(duration=secon
ds)"

P.Kumar, Rajalakshmi Engineering COllege 372


blendTrans Transition

2. the filter's apply() method is run, followed by the


setting of the element's visibility ("visible" when
fading in and "hidden" when fading out).
• object.filters.blendTrans.apply()
object.style.visibility="visible|hidden"
3. Finally, the filter's play() method is run to
perform the blend.
• object.filters.blendTrans.play()

P.Kumar, Rajalakshmi Engineering COllege 373


<html> Outline
<head>
<script type="text/javascript">

function Blend()
{
if (document.getElementById("Macaws").style.visibility == "visible") {
document.getElementById("Macaws").style.filter="blendTrans(duration=3)";
document.getElementById("Macaws").filters.blendTrans.apply();
document.getElementById("Macaws").style.visibility="hidden";
document.getElementById("Macaws").filters.blendTrans.play();
document.getElementById("Lion").style.filter="blendTrans(duration=3)";
document.getElementById("Lion").filters.blendTrans.apply();
document.getElementById("Lion").style.visibility="visible";
document.getElementById("Lion").filters.blendTrans.play();
} else {
document.getElementById("Lion").style.filter="blendTrans(duration=3)";
document.getElementById("Lion").filters.blendTrans.apply();
document.getElementById("Lion").style.visibility="hidden";
document.getElementById("Lion").filters.blendTrans.play();
document.getElementById("Macaws").style.filter="blendTrans(duration=3)";
document.getElementById("Macaws").filters.blendTrans.apply();
document.getElementById("Macaws").style.visibility="visible";
document.getElementById("Macaws").filters.blendTrans.play();
}
}

</script>
<body>
<input type = button value = clickme onclick = Blend()>
<img id="Macaws" src="Macaws.jpg"
style= "position:absolute;visibility:visible"/>
<img id="Lion" src="Lion.jpg"
style="position:absolute;visibility:hidden"/>
P.Kumar, Rajalakshmi Engineering COllege 374
revealTrans Transition

• revealTrans filter
– Create professional-style transitions
– From box out to random dissolve

P.Kumar, Rajalakshmi Engineering COllege 375


Filters: revealTrans()

• First, duration and transition values are


established giving the number of seconds for the
transition to take place and the type of transition to
apply.

• object.style.filter="revealTrans(duration=second
s, transition=n)"

P.Kumar, Rajalakshmi Engineering COllege 376


Transition types
• 0 - Box in
1 - Box out
2 - Circle in
3 - Circle out
4 - Wipe up
5 - Wipe down
6 - Wipe right
7 - Wipe left
8 - Vertical blinds
9 - Horizontal blinds
10 - Checkerboard across
11 - Checkerboard down
12 - Random dissolve
13 - Split vertical in
14 - Split vertical out
15 - Split horizontal in
16 - Split horizontal out
17 - Strips left down
18 - Strips left up
19 - Strips right down
20 - Strips right up
21 - Random bars horizontal
22 - Random bars vertical
23 - Any Random

P.Kumar, Rajalakshmi Engineering COllege 377


Filters: revealTrans()

• Second, the filter's apply() method is run,


followed by the setting of the element's visibility
("visible" when fading in and "hidden" when
fading out).
• object.filters.revealTrans.apply()
object.style.visibility="visible|hidden"

P.Kumar, Rajalakshmi Engineering COllege 378


Filters: revealTrans()

• Finally, the filter's play() method is run to perform


the blend.
• object.filters.revealTrans.play()

P.Kumar, Rajalakshmi Engineering COllege 379


Filters: revealTrans()
<script type="text/javascript"> function Blend()
{ if (document.getElementById("Macaws").style.visibility == "visible") {
document.getElementById("Macaws").style.filter="revealTrans(duration=2,
transition=8)";
document.getElementById("Macaws").filters.revealTrans.apply();
document.getElementById("Macaws").style.visibility="hidden";
document.getElementById("Macaws").filters.revealTrans.play();
document.getElementById("Lion").style.filter="revealTrans(duration=2, transition=8)";
document.getElementById("Lion").filters.revealTrans.apply();
document.getElementById("Lion").style.visibility="visible";
document.getElementById("Lion").filters.revealTrans.play(); } else {
document.getElementById("Lion").style.filter="revealTrans(duration=2, transition=8)";
document.getElementById("Lion").filters.revealTrans.apply();
document.getElementById("Lion").style.visibility="hidden";
document.getElementById("Lion").filters.revealTrans.play();
document.getElementById("Macaws").style.filter="revealTrans(duration=2,
transition=8)";
document.getElementById("Macaws").filters.revealTrans.apply();
document.getElementById("Macaws").style.visibility="visible";
document.getElementById("Macaws").filters.revealTrans.play(); } }
</script>

P.Kumar, Rajalakshmi Engineering COllege 380


Dynamic HTML: Data Binding with
Tabular Data Control
Outline
Introduction
Simple Data Binding
Moving within a Recordset
Binding to an img
Binding to a table
Sorting table Data
Data Binding Elements

P.Kumar, Rajalakshmi Engineering COllege 381


Introduction

• Data binding
– Data no longer reside exclusively on the server
– Data can be maintained on the client
– Eliminate server activity and network delays
• Data Source Objects (DSOs)
– Tabular Data Control (TDC)

P.Kumar, Rajalakshmi Engineering COllege 382


Simple Data Binding

• Data file
– Header row
• Specifies the names of the columns below
– Text qualifiers ( @ )
• Enclose data in each field
– Field delimiter ( | )
• Separate each field
– Recordset

– Eg: @ColorName@|@ColorHexRGBValue@
@green@|@#008000@

P.Kumar, Rajalakshmi Engineering COllege 383


Simple data binding and recordset manipulation

<HTML>

<HEAD>
<TITLE>Intro to Data Binding</TITLE>

<!-- This OBJECT element inserts an ActiveX control for -->


<!-- handling and parsing our data. The PARAM tags -->
<!-- give the control starting parameters such as URL. -->
<OBJECT ID = "Colors"
CLASSID = "CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83">
<PARAM NAME = "DataURL" VALUE = "HTMLStandardColors.txt">
<PARAM NAME = "UseHeader" VALUE = "TRUE">
<PARAM NAME = "TextQualifier" VALUE = "@">
<PARAM NAME = "FieldDelim" VALUE = "|">
</OBJECT>
P.Kumar, Rajalakshmi Engineering COllege 384
<SCRIPT LANGUAGE = "JavaScript">
recordSet = Colors.recordset;

function reNumber()
{
if( !recordSet.EOF )
recordNumber.innerText = recordSet.absolutePosition;
else
recordNumber.innerText = " ";
}

function forward()
{
if( !recordSet.EOF )
recordSet.MoveNext();
else
recordSet.MoveFirst();

colorSample.style.backgroundColor = colorRGB.innerText;
reNumber();
}

</SCRIPT>
</HEAD> P.Kumar, Rajalakshmi Engineering COllege 385
<BODY ONLOAD = "reNumber()" ONCLICK = "forward()">

<H1>HTML Color Table</H1>


<H3>Click to move forward in the recordset.</H3>

<P><STRONG>Color Name: </STRONG>


<SPAN ID = "colorName" STYLE = "font-family: monospace"
DATASRC = "#Colors" DATAFLD = "ColorName"></SPAN><BR>

<STRONG>Color RGB Value: </STRONG>


<SPAN ID = "colorRGB" STYLE = "font-family: monospace"
DATASRC = "#Colors" DATAFLD = "ColorHexRGBValue"></SPAN>
<BR>

Currently viewing record number


<SPAN ID = "recordNumber" STYLE = "font-weight: 900"></SPAN>
<BR>

<SPAN ID = "colorSample" STYLE = "background-color: aqua;


color: 888888; font-size: 30pt">Color Sample</SPAN>
</P>

</BODY>
P.Kumar, Rajalakshmi Engineering COllege 386
</HTML>
75 </body>
76 </html>
Outline

introdatabind.html
(4 of 4)

P.Kumar, Rajalakshmi Engineering COllege 387


Binding to an img

• Many different types of HTML elements can be


bound to data sources
– Binding to an img element
• Changing the recordset updates the src attribute of the image

P.Kumar, Rajalakshmi Engineering COllege 388


1 image
2 numbers/0.gif
Outline
3 numbers/1.gif
4 numbers/2.gif
5 numbers/3.gif images.txt
6 numbers/4.gif (1 of 1)
7 numbers/5.gif
8 numbers/6.gif
9 numbers/7.gif
10 numbers/8.gif
11 numbers/9.gif

P.Kumar, Rajalakshmi Engineering COllege 389


Binding data to an image
<HTML>

<HEAD>
<TITLE>Binding to a IMG</TITLE>

<OBJECT ID = "Images"
CLASSID = "CLSID:333C7BC4-460F-11D0-BC04-
0080C7055A83">
<PARAM NAME = "DataURL" VALUE = "images.txt">
<PARAM NAME = "UseHeader" VALUE = "True">
</OBJECT>

P.Kumar, Rajalakshmi Engineering COllege 390


function move( whereTo ) case "next":
{
switch( whereTo ) { if( recordSet.EOF )
recordSet.MoveFirst();
case "first": else
recordSet.MoveFirst(); recordSet.MoveNext();
break;
break;
case "previous":
case "last":
if( recordSet.BOF ) recordSet.MoveLast();
recordSet.MoveLast(); break;
else }
recordSet.MovePrevious(); }

break; </SCRIPT>
• </HEAD>
P.Kumar, Rajalakshmi Engineering COllege 391
P.Kumar, Rajalakshmi Engineering COllege 392
Binding to a table

• Binding data to a table is perhaps the most


important of data binding
– Different from the data binding we’ve seen

P.Kumar, Rajalakshmi Engineering COllege 393


Using Data Binding with tables

<HTML>

<HEAD>
<TITLE>Data Binding and Tables</TITLE>
<OBJECT ID = "Colors"
CLASSID = "CLSID:333C7BC4-460F-11D0-BC04-
0080C7055A83">
<PARAM NAME = "DataURL" VALUE =
"HTMLStandardColors.txt">
<PARAM NAME = "UseHeader" VALUE = "TRUE">
<PARAM NAME = "TextQualifier" VALUE = "@">
<PARAM NAME = "FieldDelim" VALUE = "|">
</OBJECT>
</HEAD>
P.Kumar, Rajalakshmi Engineering COllege 394
<BODY STYLE = "background-color: darkseagreen">

<H1>Binding Data to a <CODE>TABLE</CODE></H1>

<TABLE DATASRC = "#Colors" STYLE = "border-style: ridge;


border-color: darkseagreen; background-color: lightcyan">

<THEAD>
<TR STYLE = "background-color: mediumslateblue">
<TH>Color Name</TH>
<TH>Color RGB Value</TH>
</TR>
</THEAD>

<TBODY>
<TR STYLE = "background-color: lightsteelblue">
<TD><SPAN DATAFLD = "ColorName"></SPAN></TD>
<TD><SPAN DATAFLD = "ColorHexRGBValue"
STYLE = "font-family: monospace"></SPAN></TD>
</TR>
</TBODY>

</TABLE>

</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 395


P.Kumar, Rajalakshmi Engineering COllege 396
Sorting table Data

• Manipulate a large data source


– Need to sort data
• Can be accomplished by the Sort property of the TDC

P.Kumar, Rajalakshmi Engineering COllege 397


Sorting TABLE data

<HEAD>
<TITLE>Data Binding and Tables</TITLE>
<OBJECT ID = "Colors"
CLASSID = "CLSID:333C7BC4-460F-11D0-BC04-
0080C7055A83">
<PARAM NAME = "DataURL" VALUE =
"HTMLStandardColors.txt">
<PARAM NAME = "UseHeader" VALUE = "TRUE">
<PARAM NAME = "TextQualifier" VALUE = "@">
<PARAM NAME = "FieldDelim" VALUE = "|">
</OBJECT>
</HEAD>
P.Kumar, Rajalakshmi Engineering COllege 398
<BODY STYLE = "background-color: darkseagreen">

<H1>Sorting Data</H1>

<TABLE DATASRC = "#Colors" STYLE = "border-style: ridge;


border-color: darkseagreen; background-color: lightcyan">
<CAPTION>
Sort by:

<SELECT ONCHANGE = "Colors.Sort = this.value;


Colors.Reset();">
<OPTION VALUE = "ColorName">Color Name (Ascending)
<OPTION VALUE = "-ColorName">Color Name (Descending)
</SELECT>
</CAPTION>

<THEAD>
<TR STYLE = "background-color: mediumslateblue">
<TH>Color Name</TH>
<TH>Color RGB Value</TH>
</TR>
</THEAD>

<TBODY>
<TR STYLE = "background-color: lightsteelblue">
<TD><SPAN DATAFLD = "ColorName"></SPAN></TD>
<TD><SPAN DATAFLD = "ColorHexRGBValue"
STYLE = "font-family: monospace"></SPAN></TD>
</TR>
</TBODY>

</TABLE>

</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 399


<BODY STYLE = "background-color: <THEAD>
darkseagreen"> <TR STYLE = "background-color:
mediumslateblue">
<H1>Sorting Data</H1> <TH>Color Name</TH>
<TH>Color RGB Value</TH>
<TABLE DATASRC = "#Colors" STYLE </TR>
= "border-style: ridge; </THEAD>
border-color: darkseagreen; background-
color: lightcyan"> <TBODY>
<CAPTION> <TR STYLE = "background-color:
Sort by: lightsteelblue">
<TD><SPAN DATAFLD =
<SELECT ONCHANGE = "Colors.Sort = "ColorName"></SPAN></TD>
this.value; <TD><SPAN DATAFLD =
Colors.Reset();"> "ColorHexRGBValue"
<OPTION VALUE = STYLE = "font-family:
"ColorName">Color Name monospace"></SPAN></TD>
(Ascending) </TR>
<OPTION VALUE = "- </TBODY>
ColorName">Color Name </TABLE>
(Descending)
</SELECT> </BODY>
</CAPTION> </HTML>

P.Kumar, Rajalakshmi Engineering COllege 400


P.Kumar, Rajalakshmi Engineering COllege 401
Data Binding Elements

• Exactly how a data source is displayed by the


browser depends on the HTML element to which
the data is bound
– Different elements may use the data for different purposes.

P.Kumar, Rajalakshmi Engineering COllege 402


Data Binding Elements

Element Bindable Property/Attribute


a href
div Contained text
frame href
iframe href
img src
input type = "button" value (button text)
input type = "checkbox" checked (use a boolean value in the data)
input type = "hidden" value
input type = "password" value
input type = "radio" checked (use a boolean value in the data)
input type = "text" value
marquee Contained text
param value
select Selected option
span Contained text
table Cell elements (see Section 16.6)
textarea Contained text (value)
Fig. 16.10 XHTML elements that allow data binding.

P.Kumar, Rajalakshmi Engineering COllege 403


IT1451 – WEB TECHNOLOGY

8TH SEMESTER – INFORMATION TECHNOLOGY

UNIT – 3 NOTES

P.Kumar, Rajalakshmi Engineering COllege 404


Multimedia: Audio, Video, Speech
Synthesis and Recognition
Outline
Introduction
Audio and Video
Adding Background Sounds with the bgsound Element
Adding Video with the img Element’s dynsrc Property
Adding Audio or Video with the embed Element
Using the Windows Media Player ActiveX Control
RealOne Player Plug-in
Synchronized Multimedia Integration Language (SMIL)

P.Kumar, Rajalakshmi Engineering COllege 405


Introduction

• Multimedia
– Use of sound, images, graphics and video
– Add sound, video, and animated characters to Web-based
applications
– Streaming technologies

P.Kumar, Rajalakshmi Engineering COllege 406


Audio and Video

• Can be embedded in Web page


• Can be downloaded “on-demand”
• Encoding algorithm or codec
– Transforms raw audio or video into a format that Web
browsers can display

P.Kumar, Rajalakshmi Engineering COllege 407


Adding Background Sounds with the
bgsound Element
• bgsound element
– src property
• Specifies the URL of audio clip to be played
– loop property
• Specifies number of times audio clip will play
– balance property
• Specifies balance between left and right speakers
– volume property
• Determines volume of audio clip

P.Kumar, Rajalakshmi Engineering COllege 408


Back ground Audio

<HTML>
<HEAD><TITLE>The BGSOUND Element</TITLE>
<BGSOUND ID = "audio" SRC = "jazzgos.mid" LOOP = 1"></BGSOUND>

<SCRIPT LANGUAGE = "JavaScript">


function changeProperties()
{
var loop = parseInt( audioForm.loopit.value );
audio.loop = ( isNaN( loop ) ? 1 : loop );

var vol = parseInt( audioForm.vol.value );


audio.volume = ( isNaN( vol ) ? 0 : vol );
}
</SCRIPT>
</HEAD>
P.Kumar, Rajalakshmi Engineering COllege 409
<BODY>
<H1>Background Music via the BGSOUND Element</H1>
<H2>Jazz Gospel</H2>

This sound is from the free sound downloads at the


<a href = "http://msdn.microsoft.com/downloads/default.asp">
Microsoft Developer Network</a> downloads site.
<HR>
Use the fields below to change the number of iterations
and the volume for the audio clip<BR>
Press <B>Stop</B> to stop playing the sound.<BR>
Press <B>Refresh</B> to begin playing the sound again.

<FORM NAME = "audioForm"><P>


Loop [-1 = loop forever]
<INPUT NAME = "loopit" TYPE = "text" VALUE = "1"><BR>
Volume [-10000 (low) to 0 (high)]
<INPUT NAME = "vol" TYPE = "text" VALUE = "0"><BR>
<INPUT TYPE = "button" VALUE = "Set Properties"
ONCLICK = "changeProperties()">
</P></FORM>
</BODY>

</HTML>

P.Kumar, Rajalakshmi Engineering COllege 410


Outline

P.Kumar, Rajalakshmi Engineering COllege . 411


Adding Video with the img Element’s
dynsrc Property
• img element
– Incorporates both images and videos
– src property
• Indicates source is image
– dynsrc property
• Indicates source is video clip
– start property
• Specifies when video should start playing
• Event fileopen
– Video should play as soon as it loads
• Event mouseover
– Video should play when user position mouse over video

P.Kumar, Rajalakshmi Engineering COllege 412


DynamicIMG

<HTML>
<HEAD>
<TITLE>An Embedded Image Using the DYNSRC Property</TITLE>
<BGSOUND SRC="newage.mid" LOOP="-1">
</HEAD>

<BODY>
<H1>An Embedded Video Using the IMG Element's DYNSRC
Property</H1>
<H2>Spinning Globe and New Age Music</H2>
This video is from the
<a href="http://www.nasa.gov/gallery/">
NASA Multimedia Gallery</a><BR>
This sound is from the free sound downloads at the
<a href="http://msdn.microsoft.com/downloads/default.asp">
Microsoft Developer Network</a> downloads site.
<HR>
P.Kumar, Rajalakshmi Engineering COllege 413
<TABLE><TR>
<TD>
<IMG DYNSRC="pathfinder.mpeg" START="mouseover"
WIDTH="180" HEIGHT="135" LOOP="-1"
ALT="A spinning image of the Earth"></TD>
<TD>This page will play the audio clip and video in a
loop.<BR>The video will not begin playing until you move
the mouse over the video.<BR>Press <B>Stop</B> to stop
playing the sound and the video.</TD></TR></TABLE>
</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 414


Adding Audio or Video with the embed
Element
• Element embed
– Embeds media clip into Web page
– Displays a graphical user interface (GUI)
– Supported by both Microsoft Internet Explorer and Netscape

<EMBED SRC="approach_1_337.mpeg" LOOP="false"></EMBED>

P.Kumar, Rajalakshmi Engineering COllege 415


RealOne Player Plug-in

• Element embed
– Embed RealOne Player plug-ins for video and audio
– Attribute type
• Specifies MIME type of embedded file
– Attributes width and height
• Specify dimensions of space the control occupies
– Attribute autostart
• Determines whether media start playing when page loads
– Attribute controls
• Specifies which controls users can access
– Attribute src
• Set to location of streaming media

P.Kumar, Rajalakshmi Engineering COllege 416


Synchronized Multimedia Integration
Language (SMIL)
• Coordinate wide range of multimedia elements
• XML-based description language
• Organize text, audio, video to occur
simultaneously or sequentially
• Provide time reference for all instances of text and
media
• Specifies source and presentation of multimedia

P.Kumar, Rajalakshmi Engineering COllege 417


P.Kumar, Rajalakshmi Engineering COllege 418
e-Business & e-Commerce
Outline
Introduction
e-Business Models
Storefront Model
Shopping-Cart Technology
Auction Model
Portal Model
Name-Your-Price Model
Comparison-Pricing Model
Bartering Model
Building an e-Business
e-Marketing
Branding
Marketing Research
e-Mail Marketing

P.Kumar, Rajalakshmi Engineering COllege 419


e-Business & e-Commerce
Promotions
Consumer Tracking
Electronic Advertising
Search Engines
Affiliate Programs
Public Relations
Customer Relationship Management (CRM)
Online Payments
Credit-Card Payment
Digital Cash and e-Wallets
Micropayments
Smart Cards

P.Kumar, Rajalakshmi Engineering COllege 420


e-Business & e-Commerce

Security
Public-Key Cryptography
Cryptanalysis
Key Agreement Protocols
Key Management
Secure Sockets Layer (SSL)
WTLS
IPSec and Virtual Private Networks (VPN)
Security Attacks
Network Security
Legal Issues
Privacy
Defamation
Sexually Explicit Speech
SPAM
Copyright and Patents

P.Kumar, Rajalakshmi Engineering COllege 421


e-Business & e-Commerce

XML and e-Commerce


Introduction to Wireless Technology and m-Business
m-Business
Identifying User Location
E911 Act
Location-Identification Technologies
Wireless Marketing, Advertising and Promotions
Wireless Payment Options
Privacy and the Wireless Internet
Web Resources

P.Kumar, Rajalakshmi Engineering COllege 422


Introduction
• Successful online businesses
– Recognize need or demand
– Meet that need
– Must constantly readjust to shifting trends and technologies
– Personalization
• Tradeoff between convenience and privacy concerns
• E-commerce vs. e-business
– E-commerce
• Aspects of doing business online that relate to exchanges with
customers, partners and vendors.
• Forexample, suppliers interact with manufacturers, customers interact
with sales representatives

– E-business
• All aspects of e-commerce, plus internal operations of doing business
e-business not included under the category of e-commerce
• For example, production, development, corporate infrastructure and
product management are aspects of e-business not included under the
category of e-commerce

P.Kumar, Rajalakshmi Engineering COllege 423


e-Business Models

• e-business
– Expansion of old technologies and techniques
• Electronic Funds Transfers
– Requires new business models and categories
– Pioneered by early e-businesses
• Amazon.com, eBay, Yahoo among others

P.Kumar, Rajalakshmi Engineering COllege 424


Storefront Model

• Simulates the experience of shopping in a store


– Very common
– Provides services similar to real “brick and mortar” store
• Transaction processing
• Security
• On-line Payment
• Information storage
– Products organized into catalogs that users can browse and
search

P.Kumar, Rajalakshmi Engineering COllege 425


Shopping-Cart Technology

• Shopping-cart metaphor
– Holds items a user has selected to buy
– Merchant server contains database of available items
– User puts all desired items in the cart
– When finished, user “checks out”
• Prices totaled
• Shipping, tax and other charges applied
• Shipping and payment details gathered
• Order confirmed
• Ex: www.amazon.com

P.Kumar, Rajalakshmi Engineering COllege 426


Auction Model

• Online auctions
– Buyers bid on items made available by various sellers
• No fixed price
– Very attractive to customers
• Often able to get lower prices on goods than traditional stores
– Site is searchable to allow easy location of desired items
– Site receives a commission on each sale
– Model also employed in business-to-business transactions
– www.eBay.com is the leading auction site

P.Kumar, Rajalakshmi Engineering COllege 427


Auction Model
eBay home page.

P.Kumar, Rajalakshmi Engineering COllege 428


Auction Model

P.Kumar, Rajalakshmi Engineering COllege 429


Portal Model
• Portal sites - offer visitors the chance to find almost
anything they are looking for in one place.
• Combine many services into one page
• News
• Sports
• Weather
• Web searches
– Horizontal portals
• Search engines
• Aggregate information on broad range of topics
– Vertical portals
• Information on narrow range of topics
– Convenient, centralized access to information

P.Kumar, Rajalakshmi Engineering COllege 430


Name-Your-Price Model

• Empowers customers by allowing them to state the


price they are willing to pay for products and services.
• User submits price they are willing to pay
– Site then passes it along to partner sites, who evaluate the offer
– If accepted, user must pay that price
– If rejected, user may submit a new price
– Many such sites employ intelligent agents
• Search, arrange, analyze large amounts of data

P.Kumar, Rajalakshmi Engineering COllege 431


Comparison-Pricing Model

• Poll merchants for lowest price on an item


– Often generate revenue through partnerships with other sites
– Convenient way to search multiple merchants
– Not always the true best price
• Non-partner merchants might have better offers, but be
unlisted
– Can employ search-engine technology to automatically seek
out best prices or related products

P.Kumar, Rajalakshmi Engineering COllege 432


Bartering Model

• The offering of one item in exchange for another

• Trade items rather than currency


– Similar to auction sites
– Merchant and customer haggle to a fair price
– In practice, transaction is usually a combination of currency
and items

P.Kumar, Rajalakshmi Engineering COllege 433


Building an e-Business

• Multiple approaches
– Turnkey solutions (a prepackaged e-business)
• Ready-made e-Business sites [store.yahoo.com]
– e-Business templates
• Outline business’ structure
• Design details left open to owner
– Outsource control entirely to a specialized firm
• Expensive
• Little hassle, lets experts control it while you control your
business
– Build original, custom solution
• Allows maximum control, makes your site unique
• Most expensive, involves “reinventing the wheel”
P.Kumar, Rajalakshmi Engineering COllege 434
e-Marketing

• Marketing campaign
– Marketing your site through multiple means
• Market research
• Advertising
• Promotions
• Branding
• Public Relations (PR)
• Search engines

P.Kumar, Rajalakshmi Engineering COllege 435


Branding

• Brand
– Name, logo or symbol that defines company’s products or
services
• Unique
• Recognizable
• Easy to remember
– Brand equity
• “Value” of the brand
• Customer perception and loyalty
– Companies with existing brand may more easily establish
their brand on the Internet
• New companies must work to establish trust in their brand

P.Kumar, Rajalakshmi Engineering COllege 436


Marketing Research

• Marketing research
– Marketing mix
• Product or service details
• Pricing
• Promotion
• Distribution
– Focus groups
– Interviews
– Surveys and questionnaires
– Secondary research
• Reviewing pre-existing data

P.Kumar, Rajalakshmi Engineering COllege 437


e-Mail Marketing

• e-Mail marketing
– Part of the reach of the campaign
• Span of people who marketing should target
– Direct mail vs. indirect mail
• Direct mail is personalized to the individual recipient
• Direct is often more effective
• Offers right product at right time
• Tailor mailing to customer’s interests
– Opt-in e-Mail lists
• Customer chooses to subscribe
• Send newsletters with information on offers and promotions

P.Kumar, Rajalakshmi Engineering COllege 438


e-Mail Marketing

• e-Mail marketing, cont.


– Dangers of e-Mail marketing
• Do not flood customers with too much e-Mail in too short a
time
• Do not send unsolicited e-Mail
– Spam
– Gives company a poor reputation, illegal in some areas

P.Kumar, Rajalakshmi Engineering COllege 439


Promotions

• Promotions
– Attract visitors
– Encourage purchasing
– Increase brand loyalty
– Should not be only reason people purchase from your
company
• Sign of weak product or brand
– Be sure cost of promotion is not so great that no profit is
ever seen

P.Kumar, Rajalakshmi Engineering COllege 440


Consumer Tracking

• Consumer tracking
– Keep user profiles
– Record visits
– Analyze results of advertising and promotion
– Helps define target market
• Group toward whom it is most profitable to target marketing
resources
– Log files contain many useful details
• IP address
• Time and frequency of visits

P.Kumar, Rajalakshmi Engineering COllege 441


Consumer Tracking

• Consumer tracking, cont.


– Cookies
• Text file stored on customer’s computer
• Can contain record of user’s actions, preferences, buying
habits

P.Kumar, Rajalakshmi Engineering COllege 442


Electronic Advertising

• Advertising
– Establish and strengthen branding
– Publish URL in all advertising
• Internet advertising becoming important
– Links and banners on sites viewed often by target market
• Can be interactive or animated
– Allow advertising on your site in return for payment
– Pop-up ads
• Appear in a separate window when page loads
• Often extremely irritating to customers
• Actually decrease interest in advertised product due to negative
association with pop-up ad

P.Kumar, Rajalakshmi Engineering COllege 443


Electronic Advertising

• Search engine advertising


– Pay for better placement of your site in search results
– Sites that receive more clicks on their advertisements move
higher in rankings

P.Kumar, Rajalakshmi Engineering COllege 444


Search Engines

• Search engines
– Scan websites for desired content
– Being highly ranked in search results important
• People tend not to browse results too deeply
– Some sites base your ranking on meta tags
• Hidden XHTML tags that contain information about site
• Keywords, title, summary
– Others simply “spider” the site
• Program reads content and decides what is important

P.Kumar, Rajalakshmi Engineering COllege 445


Search Engines

• Search engines, cont.


– Google a leading search engine
• Uses complex formulas to rank pages
• Number of sites linked to you, and their ranking
• Number of clicks on your site
• Relevance to keyword user is searching for

P.Kumar, Rajalakshmi Engineering COllege 446


Affiliate Programs

• Affiliate programs
– Company pays other sites to be affiliates
• Advertise the company’s products
• When their ad leads to purchases from the company, affiliate
site receives a commission
– Increases exposure and number of site visits
– Amazon.com has large, successful affiliate program

P.Kumar, Rajalakshmi Engineering COllege 447


Public Relations

• Public relations
– Provide customers with latest information
• Products and services
• Sales
• Promotions
– Press releases
– Presentations and speeches
– e-Mail
– Crisis management
• Issue statements regarding company problems
• Minimize damage to company, brand and reputation

P.Kumar, Rajalakshmi Engineering COllege 448


Customer Relationship Management

• Customer Relationship Management (CRM)


– Provision and maintenance of quality service
– Communicate with customers
– Deliver responses to customers’ wants and needs
– Customer satisfaction key to successful business
• Much easier, less expensive to retain customers than attract
new customers
– Challenging for online businesses
• Transactions not conducted in person
• Requires innovative new techniques
– eCRM, iCRM
• Refer to CRM conduced via Internet, interchangeable terms

P.Kumar, Rajalakshmi Engineering COllege 449


Customer Relationship Management

• Aspects of CRM
– Call handling
• Management of calls between customers and service
representatives
– Sales tracking
– Transaction support
• Support for people and technology involved in keeping
transactions running smoothly
– Personalization of customer experience

P.Kumar, Rajalakshmi Engineering COllege 450


Online Payments

• Electronic Funds Transfer


– Basis for online payments
– Multiple ways of conducting EFT’s and presenting them to
the customer
– Many companies offer EFT solutions

P.Kumar, Rajalakshmi Engineering COllege 451


Credit-Card Payment

• Online credit-card payment


– Popular and common
• Many people have and are familiar with credit cards
– Some customers have security and privacy concerns
– Require merchant account at bank
• Special card-not-present (CNP) account for online transactions

P.Kumar, Rajalakshmi Engineering COllege 452


Digital Cash and e-Wallets

• Digital cash
– Stored electronically
– Analogous to traditional bank account
• Customers deposit money
– Overcomes drawbacks of credit cards
• Digital cash accounts often allow deposits in form of checks or
bank transfers
• Allows merchants to accept customers without credit cards
• e-Wallets
– Store billing and shipping information
– Fill out forms at compatible sites in one click

P.Kumar, Rajalakshmi Engineering COllege 453


Micropayments

• Micropayments
– Merchants often charged fee for credit card transactions
• For small items, fee can exceed cost of item
– Micropayments allow merchants to avoid this problem
• Add together all small transactions and pay percentage of that
– Similar to concept of phone bill
• Pay one large sum monthly rather than tiny sum per each use

P.Kumar, Rajalakshmi Engineering COllege 454


Smart Cards

• Smart cards
– Memory cards
• Only allow for storage of information
– Microprocessor cards
• Like tiny computers
• Can do processing in addition to storing data
– Contact interface
• Card inserted into reading device for use
– Contactless interface
• Data transmitted via wireless device inside card
– Data and money protected by personal identification number
(PIN)

P.Kumar, Rajalakshmi Engineering COllege 455


Security

• Security is an increasingly important concern


– Highly confidential data being transmitted all the time
• Credit cards, social security numbers, business data
– Attackers attempt to steal, corrupt or otherwise compromise
this data
– Requirements for successful secure transaction:
• Privacy
• Integrity
• Authentication
• Authorization
• Non-repudiation
– Also concerned with availability of site

P.Kumar, Rajalakshmi Engineering COllege 456


Public-Key Cryptography

• Cryptography
– Transforms data using cipher or cryptostream
– Key acts as password that combined with cipher will decrypt
encoded message into original message
– Early cryptography relied on symmetric cryptography
• Same key used to encrypt and decrypt
• Problem of how to securely transmit key itself arose
– Solution was public-key cryptography
• Two related but different keys used
• Sender uses receiver’s public key to encode
• Receiver decodes with private key
• Keys long enough that guessing or cracking them takes so
much time it is not worth the effort
P.Kumar, Rajalakshmi Engineering COllege 457
Public-Key Cryptography

Encrypting and decrypting a message using public-key cryptography.

P.Kumar, Rajalakshmi Engineering COllege 458


Public-Key Cryptography

• Digital signatures
– Same concept as physical written signatures
• Authenticate signer
• Difficult to forge
– Part of public-key cryptography
– Generated by running phrase through hash function
• Returns hash value
– Hash value for a phrase is over 99% guaranteed unique
• ie., two different phrases very unlikely to generate same value

P.Kumar, Rajalakshmi Engineering COllege 459


Public-Key Cryptography

Authentication with a public-key algorithm.

P.Kumar, Rajalakshmi Engineering COllege 460


Public-Key Cryptography

• Public Key Infrastructure


– Digital certificates
• Digital documents issued by certification authority
• Name of individual/group
• Public key
• Serial number
• Expiration date
• Signature of trusted authority
– Certificate repositories
• Hold database of public digital certificates

P.Kumar, Rajalakshmi Engineering COllege 461


Public-Key Cryptography

• PKI implementations
– More secure than standard point-of-sale (POS) transactions
• Strong encryption can take decades to crack using current
technology
– RSA encryption popular choice for PKI
• Developed at MIT in 1977
– Pretty Good Privacy (PGP)
• Implementation of PKI
• Very popular way to encrypt e-mail
• Operates using web of trust

P.Kumar, Rajalakshmi Engineering COllege 462


Cryptanalysis

• Searching for weaknesses in encryption


– Try to find ways to decrypt ciphertext without having key
– Not just done by malicious attackers
• Researchers want to find and fix flaws before attackers find
and exploit them
• Cryptanalytic attacks
– Common attack searches for relationship between ciphertext
and key
– Easier when all or part of decoded message known in
advance
• Goal not to determine original message, but to discover key
• Allows attacker to forge messages from that sender

P.Kumar, Rajalakshmi Engineering COllege 463


Cryptanalysis

• Preventative measures
– Key expiration dates
• If attacker breaks or steals key, only useful for limited time
– Exchange secret keys securely with public-key cryptography

P.Kumar, Rajalakshmi Engineering COllege 464


Key-Agreement Protocols

• Public-key encryption not perfect solution


– Requires significant computing power
– Best used to exchange secret keys once, then use those keys
for rest of transaction
• Key-agreement protocol
– Protocol is set of rules for communication
– Digital envelope most common
• Encrypt message using secret key
• Encrypt secret key with public-key encryption
• Both encrypted portions sent to receiver
• Receiver decrypts secret key using private key
• Receiver then uses decrypted secret key to decrypt message

P.Kumar, Rajalakshmi Engineering COllege 465


Key-Agreement Protocols

Creating a digital envelope.

P.Kumar, Rajalakshmi Engineering COllege 466


Key Management

• Protecting private keys vital to security


– Key generates possible source of vulnerability
• Susceptible to brute-force cracking
• If keys always chosen from small subset of all possible keys,
much easier to crack
• Algorithm must generate random keys from large set of
possible keys
– Key should be very long
– Common standard is 128 bits
• 2 to the 128 power

P.Kumar, Rajalakshmi Engineering COllege 467


Secure Sockets Layer (SSL)

• SSL facilitates secure online communications


– Developed by Netscape
– Built into most browsers and servers
• Standard Internet communication process
– Data sent and received through sockets
• Software mechanism that sends, receives and interprets
network data
– Transmission Control Protocol/Internet Protocol (TCP/IP)
• Standard protocol for Internet communication
• Controls how data is transferred and interpreted over networks
– Messages broken down into packets
• Add ordering, routing and error-correction information

P.Kumar, Rajalakshmi Engineering COllege 468


Secure Sockets Layer (SSL)

• Standard Internet communication process, cont.


– Packet’s destination is an IP address
• Unique number that identifies computer on network
– TCP puts received packets in order and checks for errors
• Can request retransmission if errors discovered
– Only basic error checking exists
• Attackers can forge data with relative ease
• More secure methods necessary to increase integrity

P.Kumar, Rajalakshmi Engineering COllege 469


Secure Sockets Layer (SSL)

• SSL
– Layer on top of TCP/IP
– Implements public-key encryption using RSA algorithm
– Generates secret key referred to as session key
• Rest of transaction encrypted using this key
– Messages still sent through TCP/IP after encryption step
– Generally used for point-to-point connections
• One computer communicating with another directly
– Transport Layer Security (TLS) another similar technology

P.Kumar, Rajalakshmi Engineering COllege 470


Secure Sockets Layer (SSL)

• SSL, cont.
– SSL does not protect data stored on server
• Only data that is currently traveling across network
– Stored data should be encrypted by another means
– Always take standard precautions against cracker attacks
• Making SSL more efficient
– Encryption taxing on server resources
– Dedicated SSL encoding/decoding hardware exists
• Peripheral component interface (PCI) cards
• Offload these tasks from CPU

P.Kumar, Rajalakshmi Engineering COllege 471


WTLS

• Wireless Transport Layer Security


– Security layer for Wireless Application Protocol (WAP)
• WAP used for wireless communication on cell phones and
other devices
– Provides authentication, integrity, privacy and denial-of-
service protection
– Encrypts data sent between WAP device and WAP gateway
• Where wireless network connects to wired network
– Data translated from WTLS to SSL at gateway
• For an instant, data is unencrypted
• WAP gap
• No successful WAP gap attack ever reported

P.Kumar, Rajalakshmi Engineering COllege 472


IPSec and Virtual Private Networks (VPN)

• Types of networks
– Local Area Network (LAN)
• Connects physically close computers
– Wide Area Network (WAN)
• Connect computers in multiple locations
• Employ private phone lines, radio waves or other techniques
– Virtual Private Network (VPN)
• Leverage Internet to simulate LAN for multiple remote
networks and wireless users
• Secure tunnel over Internet
• Data protected by encryption

P.Kumar, Rajalakshmi Engineering COllege 473


IPSec and Virtual Private Networks (VPN)

• Internet Protocol Security (IPSec)


– Developed by Internet Engineering Task Force (IETF)
– Uses public-key and symmetric-key cryptography
– Protects against data manipulation and IP-spoofing
– Conceptually similar to SSL
• Secures entire network rather than point-to-point transaction
– Often employs RSA or Diffie-Hellman encryption for key
exchange
– DES or 3DES used for secret key
• IPSec packets
– Three components

P.Kumar, Rajalakshmi Engineering COllege 474


IPSec and Virtual Private Networks (VPN)

• IPSec packets, cont.


– Authentication header (AH)
• Verifies identity of sender and integrity of data
– Encapsulating security payload (ESP)
• Encrypts packet to prevent reading while in transit
– Internet Key Exchange (IKE)
• Authenticates encryption keys
• VPN shortcomings
– Time consuming and complicated to initially set up
– Must be careful who is given access
• VPN users essentially the same as LAN users
• Potentially have access to sensitive data

P.Kumar, Rajalakshmi Engineering COllege 475


Security Attacks

• Security of greater concern than ever before


– Great variety of attacks to defend against
– Denial of Service (DoS) and Distributed DOS (DDoS)
• Flood server or network with data packets
• Prevents any legitimate traffic from passing through
• DDoS occurs when attacker gains control of multiple machines
• Uses them all to coordinate massive attack
– Viruses
• Malicious programs
• Attach to or overwrite legitimate programs
• Vary in severity from minor irritations to complete destruction
of hard drive data

P.Kumar, Rajalakshmi Engineering COllege 476


Security Attacks

• Security of greater concern than ever before, cont.


– Worms
• Similar to viruses
• Able to reproduce and spread over networks
• Generate extreme amount of traffic, slowing networks
• CodeRed and ILOVEYOU two infamous worms

• Attackers commonly called hackers or crackers


– Traditionally, terms not interchangeable
• Hacker is a skilled programmer and computer user
• Cracker maliciously attacks computers for personal gain
• In practice, hacker has become blanket term for computer
criminals

P.Kumar, Rajalakshmi Engineering COllege 477


Security Attacks

• Protecting against attacks


– Software exists to mitigate effects of these attacks
– Anti-Virus software
• Detects and deletes viruses and worms before they execute

P.Kumar, Rajalakshmi Engineering COllege 478


Network Security

• Network security
– Allow authorized users access they need
– Prevent unauthorized users from accessing and damaging
network
– Firewall a vital tool for network security
• Protects LANs from unauthorized traffic
• Placed between external Internet connection and computers on
local network
• Blocks or allows traffic based on rules set by administrator
• Administrator must balance users’ needs for functionality
against need for network security

P.Kumar, Rajalakshmi Engineering COllege 479


Network Security

• Network security, cont.


– Intrusion detection systems (IDS)
• Detect that an attacker has penetrated the firewall
• Monitor network traffic and log files
• If intrusion detected, immediately closes that connection and
alerts administrator through various means

P.Kumar, Rajalakshmi Engineering COllege 480


Legal Issues

• Internet poses new challenges to lawmakers


– File-sharing could redefine copyright laws
– Marketing techniques clash with users’ desire for privacy
– Cyberspace requires rethinking many traditional legal ideas

P.Kumar, Rajalakshmi Engineering COllege 481


Privacy

• U.S. Constitution has no explicit right to privacy


– Regardless, privacy is vital concern to many people
– Many sites track activity and personal information
• Provides personalization and sometimes better service
• Balanced against desire for marketers to not follow one’s every
move or steal valuable information
– Affects company employees as well as customers
• Companies install key loggers or keystroke cops
• Monitor what employees do on their system
• Right of company to ensure employees doing their jobs versus
employee desire for privacy and free-speech
– Idea of right to privacy still being created in courts

P.Kumar, Rajalakshmi Engineering COllege 482


Defamation

• Defamation
– Consists of slander and libel
• Slander is spoken
• Libel is written or spoken in a broader context than slander
• Proving defamation
– Plaintiff must:
• Show that statement was written, spoken or broadcast
• Reasonably identify individual responsible
• Show that the statement is indeed defamatory
• Show that the statement was intended to cause harm and
known to be false
• Show evidence of injury or actual loss

P.Kumar, Rajalakshmi Engineering COllege 483


Sexually Explicit Speech

• Pornography is protected by First Amendment


– Obscenity is not
– Miller test has been deciding factor between the two
• Obscenity “appeals to the prurient interest”
• Lacks serious literary, artistic, political or scientific value
– In cyberspace, community standards are different
• “Communities” not defined by physical location
• Issues of jurisdiction are unclear
– Problem of what standard to hold Internet to
• Broadcast laws restrict content rather than audience
• Print laws use non-content-related means
• Restrict audience rather than content
• Either is possible on the Internet
P.Kumar, Rajalakshmi Engineering COllege 484
Spam

• E-mail marketing
– Can be useful or harmful
– Unsolicited mass-mailings, or Spam, strongly frowned on
• Many Internet users received hundreds per day
• Content often at best irrelevant and at worst highly offensive
• Possible for children to receive pornography, for example
– Legislation being created to deal with Spam epidemic
– Software to combat spam also exists
– Spammers constantly evolve to circumvent new measures
– One of the toughest usability and privacy issues with
Internet today

P.Kumar, Rajalakshmi Engineering COllege 485


Copyrights and Patents

• Copyright
– Protection given to author of original piece
• Protects an expression of idea, not idea itself
– Incentive to create by guaranteeing credit for work
• Life of author plus 70 years
– Digital technology has made copyright gray area
• Fair use vs. piracy
• Copies can be perfect, not cheap imitations
– Movies and MP3-encoded music files hottest area of debate
• File-sharing programs lets users download copyrighted works
freely
• Costs distributors and artists money
• Users want to sample music, enjoy lower prices
P.Kumar, Rajalakshmi Engineering COllege 486
Copyrights and Patents

• Patents
– Grant creator sole rights to a discovery
– Designed to foster invention and innovation
• Guarantees new idea cannot be stolen from inventor
– Possible to patent method of doing business
• Must be non-obvious to person skilled in relevant field
– Also contentious area
• Some feel patents stifle rather than foster innovation
• 20-year duration may be too long in fast-paced software world
• Some companies file patents solely to profit from infringement
lawsuits later on

P.Kumar, Rajalakshmi Engineering COllege 487


XML and e-Commerce

• Extensible Markup Language (XML)


– One parent of HTML
– Allows users to create customized tags to mark up data
• Share data in standard, easily-used format worldwide
• Portable between multiple applications and platforms
– Some industries have standard XML formats already
• MathML
• CML
• XMI
• OSD
– Facilitates Electronic Data Interchange (EDI)

P.Kumar, Rajalakshmi Engineering COllege 488


Introduction to Wireless Technology and m-
Business
• Wireless technology
– One of technology’s fastest growing sectors
– Brings communications and Internet everywhere
– Wireless devices support increasing number of features
– Convergence beginning to occur
• Features of several distinct products combined into one
• PDAs merging with cell phones

P.Kumar, Rajalakshmi Engineering COllege 489


m-Business

• Mobile business
– E-business enabled by wireless technology
– Relatively new, but rapidly growing
– Access critical business information anytime, anywhere
• Employees can conduct their duties more easily
• Customers can interact with online businesses in new ways and
locations

P.Kumar, Rajalakshmi Engineering COllege 490


Identifying User Location

• Location-identification technologies
– Determine users’ physical location to within yards
– Useful in wireless marketing
• Send promotion data when user is near relevant location
– Great benefits to emergency services
• Quickly and accurately locate victims
– Made possible by relationships between wireless providers,
networks and users
– Multipath errors can cause problems
• Signals reflecting off nearby objects

P.Kumar, Rajalakshmi Engineering COllege 491


E911 Act

• Enhanced 911 Act


– Standardize 911 service across mobile devices
– Improve response time to calls made from cell phones
– First phase requires cellular providers to disclose phone
number of caller as well as location of nearest cell site
– Second phase requires disclosure of location of caller to
within 125 meters
– Several benefits
• Callers often do not know their exact location
• If call breaks up, emergency responders can still send help

P.Kumar, Rajalakshmi Engineering COllege 492


Location-Identification Technologies

• Methods of locating the user


– Triangulation
• Analyze angle of signals from at least two fixed points
– Information presented as geocode
• Latitude and longitude
– Different methods have varying degrees of accuracy

P.Kumar, Rajalakshmi Engineering COllege 493


Location-Identification Technologies

Technology Degree of Accuracy


Cell of Origin (COO) Least accurate. User could be anywhere in tower’s range.
Meets only Phase I of E911 Act.
Angle of Arrival (AOA) Fairly accurate. User is within the overlap of two towers’
cell sites. Used primarily in rural areas where there are
fewer towers. Complies with Phase II of E911.
Time Difference of Arrival Accurate. User’s location is determined by triangulating
(TDOA) from three locations. Complies with Phase II of E911. Most
effective when towers are close together.
Enhanced Observed Time Accurate. User’s location is determined by triangulating
Difference (E-OTD) from three locations. Complies with Phase II of E911.
Location Pattern Matching Accurate. User’s location is determined by analyzing
multipath interference in a given area, making the method
more effective for locating a device in an urban area.
Global Positioning Systems Highly accurate. Satellites determine a user’s location
(GPS) anywhere on earth. However, GPS is not as effective when
the user is indoors.
Fig. 38.6 Location-identification technologies.

P.Kumar, Rajalakshmi Engineering COllege 494


Wireless Marketing, Advertising and
Promotions
• Wireless Marketing
– Wireless technology provides unique opportunities
– Augments, rather than replaces, traditional marketing
• Push and pull strategies
– Pull
• Users request data to be sent in real-time
– Push
• Company delivers messages at time it deems appropriate
– Using either one, advertising should be opt-in
• User must have explicitly requested the service
• Otherwise it is essentially spam, creates ill-will toward the
company

P.Kumar, Rajalakshmi Engineering COllege 495


Wireless Marketing, Advertising and
Promotions
• Effective wireless marketing
– Must deliver right content at right time
– Perfect match for location-identification technology
– Advertisers much more likely to place and pay more for ads
that are well-targeted and likely to generate response
– Several challenges and obstacles
• Security
• Ensuring ads display properly on diverse devices
• Additional middle-men
• Selecting suitable publisher and transmission technology

P.Kumar, Rajalakshmi Engineering COllege 496


Wireless Marketing, Advertising and
Promotions
• Short Message Service
– Deliver simple text-only messages
– Interactivity is limited
– Nearly no load time
– Work well for quick, simple alerts

P.Kumar, Rajalakshmi Engineering COllege 497


Wireless Payment Options

• Wireless payments (m-payments)


– Must be secure and reliable, like standard online payments
– Mobile Virtual Network Operators (MVNOs)
• Purchase bandwidth and re-brand with added services
• Option for banks to make micropayments profitable
– M-wallets
• Users store billing and shipping information
• Recall with one click
• Promote convenience

P.Kumar, Rajalakshmi Engineering COllege 498


Privacy and the Wireless Internet

• Privacy problems magnified on wireless devices


– Transmissions can be intercepted
– Users located accurately
– Accepted standard is opt-in policy
• Users request to be sent information
• Consumer should always expect the information they receive
• No unauthorized information sharing with partners
– Sometimes double opt-in
• User requests information, then has to confirm decision
– Opt-out frowned upon
• Send users information unless they say to stop

P.Kumar, Rajalakshmi Engineering COllege 499


Privacy and the Wireless Internet

• CITA
– Cellular Telecommunications and Internet Association
– Group that has created guidelines for consumer privacy
– Outlined four guidelines
• Alert consumers when location being identified
• Always use opt-in marketing
• Consumers able to access their own information
• Same protections offered by all devices and carriers

P.Kumar, Rajalakshmi Engineering COllege 500


Web Servers
Outline
Introduction
HTTP Request Types
System Architecture
Client-Side Scripting versus Server-Side Scripting
Accessing Web Servers
Microsoft Internet Information Services (IIS)
Microsoft Internet Information Services (IIS) 5.0
Microsoft Internet Information Services (IIS) 6.0
Apache Web Server

P.Kumar, Rajalakshmi Engineering COllege 501


Introduction

• Web server
– Responds to client requests by providing resources
• URI (Uniform Resource Identifier)
• Web server and client communicate with
platform-independent Hypertext Transfer Protocol
(HTTP)

P.Kumar, Rajalakshmi Engineering COllege 502


Introduction

IIS 5.0 IIS 6.0 Apache Web server


Company Microsoft Microsoft Apache Software
Corporation Corporation Foundation
Version 5.0 6.0 2.0.47
Released 2/17/00 3/28/03 7/10/03
Platforms Windows 2000, Windows Server 2003Windows NT/2000/XP,
Windows XP Mac OS X, Linux and
other UNIX-based
platforms,
experimentally supports
Windows 95/98
Brief The most popular The newest release of Currently the most
description Web server for IIS from Microsoft. popular Web server.
Windows 2000.
Price Included with Included with Freeware.
Windows 2000 Windows Server 2003
and Windows
XP.
Fig. 21.1 Web servers discussed in this chapter.
P.Kumar, Rajalakshmi Engineering COllege 503
HTTP Request Types

• Request methods
– get
– post
– Retrieve and send client form data to Web server
– Post data to a server-side form handler

P.Kumar, Rajalakshmi Engineering COllege 504


System Architecture

• Multi-tier application (n-tier application)


– Information tier (data or bottom tier)
• Maintains data for the application
• Stores data in a relational database management system
(RDBMS)
– Middle tier
• Implements business logic and presentation logic
• Control interactions between application clients and
application data
– Client tier (top tier)
• Application’s user interface
• Users interact directly with the application through the client
tier

P.Kumar, Rajalakshmi Engineering COllege 505


Client-Side Scripting Vs Server-Side Scripting

• Client-side scripts
– Validate user input
• Reduce requests needed to be passed to server
• Access browser
• Enhance Web pages with DHTML, ActiveX controls, and
applets
• Server-side scripts
– Executed on server
– Generate custom response for clients
– Wide range of programmatic capabilities
– Access to server-side software that extends server
functionality

P.Kumar, Rajalakshmi Engineering COllege 506


Accessing Web Servers

• Request documents from Web servers


– Host names
– Local Web servers
• Access through machine name or localhost
– Remote Web servers
• Access through machine name
– Domain name or Internet Protocol (IP) address
• Domain name server (DNS)
– Computer that maintains a database of host names and
their corresponding IP address

P.Kumar, Rajalakshmi Engineering COllege 507


Microsoft Internet Information Services
(IIS)
• An enterprise-level Web server that is included
with Windows

P.Kumar, Rajalakshmi Engineering COllege 508


Microsoft Internet Information Services (IIS)
5.0
• FTP Site
– Used for transferring large files across the Internet
• HTTP Site
– Used most frequently to request documents from Web
servers
• SMTP Virtual Server
– Sends and receives electronic mail
• Web Site Content Directory
– Directory containing the documents that clients will view

P.Kumar, Rajalakshmi Engineering COllege 509


Microsoft Internet Information Services (IIS)
5.0

Internet Information Services window of Internet Services Manager.

P.Kumar, Rajalakshmi Engineering COllege 510


Microsoft Internet Information Services (IIS)
5.0

Virtual Directory Creation Wizard welcome dialog.

P.Kumar, Rajalakshmi Engineering COllege 511


Microsoft Internet Information Services (IIS)
5.0

Virtual Directory Alias dialog of the Virtual Directory Creation Wizard.

P.Kumar, Rajalakshmi Engineering COllege 512


Microsoft Internet Information Services (IIS)
5.0

Web Site Content Directory dialog of the Virtual Directory Creation Wizard.

P.Kumar, Rajalakshmi Engineering COllege 513


Microsoft Internet Information Services (IIS)
5.0

Access Permissions dialog of the Virtual Directory Creation Wizard.

P.Kumar, Rajalakshmi Engineering COllege 514


Microsoft Internet Information Services (IIS)
6.0

Internet Information (IIS) Services Manager window.

P.Kumar, Rajalakshmi Engineering COllege 515


Microsoft Internet Information Services (IIS)
6.0

Virtual Directory Creation Wizard welcome dialog.

P.Kumar, Rajalakshmi Engineering COllege 516


Microsoft Internet Information Services (IIS)
6.0

Virtual Directory Alias dialog of the Virtual Directory Creation Wizard.

P.Kumar, Rajalakshmi Engineering COllege 517


Microsoft Internet Information Services (IIS)
6.0

Web Site Content Directory dialog of the Virtual Directory Creation Wizard.

P.Kumar, Rajalakshmi Engineering COllege 518


Microsoft Internet Information Services (IIS)
6.0

Access Permissions dialog of the Virtual Directory Creation Wizard.

P.Kumar, Rajalakshmi Engineering COllege 519


Apache Web Server

• Currently the most popular Web server


• Stability
• Efficiency
• Portability
• Open-source

P.Kumar, Rajalakshmi Engineering COllege 520


Apache Web Server

Apache Web server starting. (Courtesy of The Apache Software Foundation.)

P.Kumar, Rajalakshmi Engineering COllege 521


Requesting Documents

• Request HTML documents from IIS 6.0 or


Apache
– Launch Internet Explorer
– Enter HTML document’s location in Address field

P.Kumar, Rajalakshmi Engineering COllege 522


HTML

Requesting test.html from IIS 5.

Requesting test.html from IIS 6 or Apache.

P.Kumar, Rajalakshmi Engineering COllege 523


Web Resources

• www.microsoft.com/msdownload/ntoptionpack/askwiz.asp
• www.w3.org/Protocols
• www.apache.org
• httpd.apache.org
• httpd.apache.org/docs-2.0
• www.apacheweek.com
• linuxtoday.com/stories/18780.html
• www.iisanswers.com
• www.iisadministrator.com

P.Kumar, Rajalakshmi Engineering COllege 524


CSS Vs SSS
Outline
Introduction
HTTP Request Types
System Architecture
Client-Side Scripting versus Server-Side Scripting

P.Kumar, Rajalakshmi Engineering COllege 525


Introduction

• Web server
– Responds to client requests by providing resources
• URI (Uniform Resource Identifier)
• Web server and client communicate with
platform-independent Hypertext Transfer Protocol
(HTTP)

P.Kumar, Rajalakshmi Engineering COllege 526


HTTP Request Types

• Request methods
– get
– post
– Retrieve and send client form data to Web server
– Post data to a server-side form handler

P.Kumar, Rajalakshmi Engineering COllege 527


URI, URL, URN

• URL - Uniform Resource Locator


used to identify an Internet resource, and can be
specified in a single line of text.
• URN - Uniform Resource Name
used to identify an Internet resource, without the
use of a scheme, and can be specified in a single
line of text.
• URI - Uniform Resource Identifier (URI)
used by a browser to identify a single document,
and it too can be specified in a single line of text.
P.Kumar, Rajalakshmi Engineering COllege 528
Examples

• URL http://www.abc.org/iis/review1.htm

• URN www.abc.org/iis/review1.htm#one

• URI http://www.abc.org/iis/review1.htm.html#one

P.Kumar, Rajalakshmi Engineering COllege 529


System Architecture

• Multi-tier application (n-tier application)


– Information tier (data or bottom tier)
• Maintains data for the application
• Stores data in a relational database management system
(RDBMS)
– Middle tier
• Implements business logic and presentation logic
• Control interactions between application clients and
application data
– Client tier (top tier)
• Application’s user interface
• Users interact directly with the application through the client
tier

P.Kumar, Rajalakshmi Engineering COllege 530


Client-Side Scripting versus Server-Side
Scripting
• Client-side scripts
– Validate user input
• Reduce requests needed to be passed to server
• Access browser
• Enhance Web pages with DHTML, ActiveX controls, and
applets
• Server-side scripts
– Executed on server
– Generate custom response for clients
– Wide range of programmatic capabilities
– Access to server-side software that extends server
functionality

P.Kumar, Rajalakshmi Engineering COllege 531


Types

Client-side scripts
• VBScript , JavaScript and Ajax
(Asynchronous JavaScript and XML )

Server-side scripts
• ASP, JSP, PHP (Hypertext Preprocessor-
OSS), Cold fusion etc

P.Kumar, Rajalakshmi Engineering COllege 532


Comparison

JavaScript VBScript
• Scripting language Scripting language
• Object-based Not object-based
• Supports functions Supports functions
• Secure Secure
• C/C++ based Subset of Visual Basic
• Supported by all browsers Presently supported by
only Internet Explorer
• Easy to learn Based on BASIC

P.Kumar, Rajalakshmi Engineering COllege 533


Microsoft Internet Information Services (IIS)

• FTP Site
– Used for transferring large files across the Internet
• HTTP Site
– Used most frequently to request documents from Web
servers
• SMTP Virtual Server
– Sends and receives electronic mail
• Web Site Content Directory
– Directory containing the documents that clients will view

P.Kumar, Rajalakshmi Engineering COllege 534


IT1451 – WEB TECHNOLOGY

8TH SEMESTER – INFORMATION TECHNOLOGY

UNIT – 4 NOTES

P.Kumar, Rajalakshmi Engineering COllege 535


Database: SQL

Outline
Introduction
Relational Database Model
Relational Database Overview: Books.mdb Database
SQL (Structured Query Language)
Basic SELECT Query
WHERE Clause
ORDER BY Clause
Merging Data from Multiple Tables: INNER JOIN
Joining Data from Tables Authors, AuthorISBN,
Titles and Publishers
INSERT Statement
UPDATE Statement
DELETE Statement

P.Kumar, Rajalakshmi Engineering COllege 536


Introduction

• Database
– Integrated collection of data
– Database management system (DBMS)
• Store and organize data consistent with database’s format
• Relational database
– SQL (Structured Query Language)
• Queries
• Manipulate data

P.Kumar, Rajalakshmi Engineering COllege 537


Relational Database Model

• Composed of tables
• Row
– Number column
– Primary key
• Reference data in the table
• A column or set of columns in table contains unique data

P.Kumar, Rajalakshmi Engineering COllege 538


Relational Database Model

number name department salary location


23603 Jones 413 1100 New Jersey
24568 Kerwin 413 2000 New Jersey
Row 34589 Larson 642 1800 Los Angeles
35761 Myers 611 1400 Orlando
47132 Neumann 413 9000 New Jersey
78321 Stephens 611 8500 Orlando

Primary key Column

Fig. 22.1 Relational database structure of an Employee table.

P.Kumar, Rajalakshmi Engineering COllege 539


Relational Database Model

department location
413 New Jersey
611 Orlando
642 Los Angeles

Fig. 22.2 Table formed by selecting department and location data from the Employee table.

P.Kumar, Rajalakshmi Engineering COllege 540


Relational Database Overview: Books.mdb
Database
• Primary key uniquely identifies each row
– Rule of Entity Integrity
• Composite primary key
• Lines connecting tables
– Relationships
• One-to-many relationship
• Foreign key
– Join multiple tables
– Rule of Referential Integrity

P.Kumar, Rajalakshmi Engineering COllege 541


Relational Database Overview: Books.mdb
Database

Field Description
authorID Author’s ID number in the database. In the Books.mdb
database, this Integer column is defined as auto-
increment. For each new row inserted in this table, the
database increments the authorID value, ensuring that
each row has a unique authorID. This column represents
the table’s primary key.
firstName Author’s first name (a String).
lastName Author’s last name (a String).
Fig. 22.3 Authors table from Books.mdb.

P.Kumar, Rajalakshmi Engineering COllege 542


Relational Database Overview: Books.mdb
Database

authorID firstName lastName


1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Kate Steinbuhler
5 Sean Santry
6 Ted Lin
7 Praveen Sadhu
8 David McPhie
9 Cheryl Yaeger
10 Marina Zlatkina
11 Ben Wiedermann
12 Jonathan Liperi
Fig. 22.4 Data from the Authors table of
Books.mdb.

P.Kumar, Rajalakshmi Engineering COllege 543


Relational Database Overview: Books.mdb
Database
Field Description
publisherID The publisher’s ID number in the database. This
auto-incremented Integer is the table’s primary
key.
publisherName The name of the publisher (a String).
Fig. 22.5 Publishers table from Books.mdb.

publisherID publisherName
1 Prentice Hall
2 Prentice Hall PTG
Fig. 22.6 Data from the Publishers table of Books.mdb.

Field Description
authorID The author’s ID number, which allows the database
to associate each book with a specific author. The
integer ID number in this column must also appear
in the Authors table.
isbn The ISBN number for a book (a String).
Fig. 22.7 AuthorISBN table from Books.mdb.

P.Kumar, Rajalakshmi Engineering COllege 544


Relational Database Overview: Books.mdb
Database
authorID isbn authorID isbn
1 0130895725 2 0139163050
1 0132261197 2 013028419x
1 0130895717 2 0130161438
1 0135289106 2 0130856118
1 0139163050 2 0130125075
1 013028419x 2 0138993947
1 0130161438 2 0130852473
1 0130856118 2 0130829277
1 0130125075 2 0134569555
1 0138993947 2 0130829293
1 0130852473 2 0130284173
1 0130829277 2 0130284181
1 0134569555 2 0130895601
1 0130829293 3 013028419x
1 0130284173 3 0130161438
1 0130284181 3 0130856118
1 0130895601 3 0134569555
2 0130895725 3 0130829293
2 0132261197 3 0130284173
2 0130895717 3 0130284181
2 0135289106 4 0130895601
Fig. 22.8 Data from AuthorISBN table in Books.mdb.
P.Kumar, Rajalakshmi Engineering COllege 545
Relational Database Overview: Books.mdb
Database
Field Description
isbn ISBN number of the book (a String).
title Title of the book (a String).
editionNumber Edition number of the book (a String).
copyright Copyright year of the book (an Integer).
description Description of the book (a String).
publisherID Publisher’s ID number (an Integer). This value
must correspond to an ID number in the
Publishers table.
imageFile Name of the file containing the book’s cover image
(a String).
price Suggested retail price of the book (a real number).
[Note: The prices shown in this database are for
example purposes only.]
Fig. 22.9 Titles table from Books.mdb.

P.Kumar, Rajalakshmi Engineering COllege 546


Relational Database Overview: Books.mdb
Database
isbn title edition- publisherID copy- price
Number right
0130923613 Python How to Program 1 1 2002 $69.95
0130622214 C# How to Program 1 1 2002 $69.95
0130341517 Java How to Program 4 1 2002 $69.95
0130649341 The Complete Java Training 4 2 2002 $109.95
Course
0130895601 Advanced Java 2 Platform 1 1 2002 $69.95
How to Program
0130308978 Internet and World Wide 2 1 2002 $69.95
Web How to Program
0130293636 Visual Basic .NET How to 2 1 2002 $69.95
Program
0130895636 The Complete C++ Training 3 2 2001 $109.95
Course
0130895512 The Complete e-Business & 1 2 2001 $109.95
e-Commerce Programming
Training Course
Fig. 22.10 Portion of the data from the Titles table of Books.mdb.

P.Kumar, Rajalakshmi Engineering COllege 547


Relational Database Overview: Books.mdb
Database

Fig. 22.11 Table relationships in Books.mdb.

P.Kumar, Rajalakshmi Engineering COllege 548


SQL (Structured Query Language)

SQL keyword Description


SELECT Selects (retrieves) columns from one or more tables.
FROM Specifies tables from which to get columns or delete
rows. Required in every SELECT and DELETE
statement.
WHERE Specifies criteria that determine the rows to be
retrieved.
INNER JOIN Joins rows from multiple tables to produce a single
set of rows.
GROUP BY Specifies criteria for grouping rows.
ORDER BY Specifies criteria for ordering rows.
INSERT Inserts data into a specified table.
UPDATE Updates data in a specified table.
DELETE Deletes data from a specified table.
CREATE Creates a new table.
DROP Deletes an existing table.
COUNT Returns the number of records that satisfy given
search criteria.
Fig. 22.12 SQL keywords.

P.Kumar, Rajalakshmi Engineering COllege 549


Basic SELECT Query

• SELECT * FROM tableName


– SELECT * FROM Authors
– SELECT authorID, lastName FROM Authors

P.Kumar, Rajalakshmi Engineering COllege 550


Basic SELECT Query

authorID lastName authorID lastName


1 Deitel 7 Sadhu
2 Deitel 8 McPhie
3 Nieto 9 Yaeger
4 Steinbuhler 10 Zlatkina
5 Santry 11 Wiedermann
6 Lin 12 Liperi
Fig. 22.13 authorID and lastName from the Authors table.

P.Kumar, Rajalakshmi Engineering COllege 551


WHERE Clause

• Specify selection criteria for query


– SELECT columnName1, columnName2, … FROM tableName
WHERE criteria
• SELECT title, editionNumber, copyright FROM
Titles WHERE copyright > 1999
– LIKE
• Pattern matching
– Asterisk ( * )
• SELECT authorID, firstName, lastName
FROM Authors WHERE lastName LIKE ‘D*’
– Question mark ( ? )
• SELECT authorID, firstName, lastName
FROM Authors WHERE lastName LIKE ‘?I*’

P.Kumar, Rajalakshmi Engineering COllege 552


WHERE Clause
Title editionNumber copyright
Internet and World Wide Web How to 2 2002
Program
Java How to Program 4 2002
The Complete Java Training Course 4 2002
The Complete e-Business & e-Commerce 1 2001
Programming Training Course
The Complete Internet & World Wide Web 2 2001
Programming Training Course
The Complete Perl Training Course 1 2001
The Complete XML Programming Training 1 2001
Course
C How to Program 3 2001
C++ How to Program 3 2001
The Complete C++ Training Course 3 2001
e-Business and e-Commerce How to Program 1 2001
Internet and World Wide Web How to 1 2000
Program
The Complete Internet and World Wide Web 1 2000
Programming Training Course

P.Kumar, Rajalakshmi Engineering COllege 553


WHERE Clause

Java How to Program (Java 2) 3 2000


The Complete Java 2 Training Course 3 2000
XML How to Program 1 2001
Perl How to Program 1 2001
Advanced Java 2 Platform How to 1 2002
Program
e-Business and e-Commerce for Managers 1 2000
Wireless Internet and Mobile Business 1 2001
How to Program
C# How To Program 1 2002
Python How to Program 1 2002
Visual Basic .NET How to Program 2 2002
Fig. 22.14 Titles with copyrights after 1999 from table Titles.

P.Kumar, Rajalakshmi Engineering COllege 554


WHERE Clause

authorID firstName lastName


1 Harvey Deitel
2 Paul Deitel
Fig. 22.15 Authors from the Authors table whose last names start with D.

authorID firstName lastName


3 Tem Nieto
6 Ted Lin
11 Ben Wiedermann
12 Jonathan Liperi
Fig. 22.16 Authors from table Authors whose last names contain i as their
second letter.

P.Kumar, Rajalakshmi Engineering COllege 555


ORDER BY Clause

• Arranged in ascending or descending order


– SELECT columnName1, columnName2, … FROM
tableName ORDER BY column ASC
• SELECT authorID, firstName, lastName FROM
Authors ORDER BY lastName ASC
– SELECT columnName1, columnName2, … FROM
tableName ORDER BY column DESC
• SELECT authorID, firstName, lastName FROM
Authors ORDER BY lastName DESC

P.Kumar, Rajalakshmi Engineering COllege 556


ORDER BY Clause

authorID firstName lastName


2 Paul Deitel
1 Harvey Deitel
6 Ted Lin
12 Jonathan Liperi
8 David McPhie
3 Tem Nieto
7 Praveen Sadhu
5 Sean Santry
4 Kate Steinbuhler
11 Ben Wiedermann
9 Cheryl Yaeger
10 Marina Zlatkina
Fig. 22.17 Authors from table Authors in ascending order by
lastName.

P.Kumar, Rajalakshmi Engineering COllege 557


ORDER BY Clause

authorID firstName lastName


10 Marina Zlatkina
9 Cheryl Yaeger
11 Ben Wiedermann
4 Kate Steinbuhler
5 Sean Santry
7 Praveen Sadhu
3 Tem Nieto
8 David McPhie
12 Jonathan Liperi
6 Ted Lin
2 Paul Deitel
1 Harvey Deitel
Fig. 22.18 Authors from table Authors in descending order by
lastName.

P.Kumar, Rajalakshmi Engineering COllege 558


ORDER BY Clause

authorID firstName lastName


1 Harvey Deitel
2 Paul Deitel
6 Ted Lin
12 Jonathan Liperi
8 David McPhie
3 Tem Nieto
7 Praveen Sadhu
5 Sean Santry
4 Kate Steinbuhler
11 Ben Wiedermann
9 Cheryl Yaeger
10 Marina Zlatkina
Fig. 22.19 Authors from table Authors in ascending order by
lastName and by firstName.

P.Kumar, Rajalakshmi Engineering COllege 559


ORDER BY Clause

isbn title edition- copy- price


Number right
0130895601 Advanced Java 2 Platform 1 2002 $69.95
How to Program
0131180436 C How to Program 1 1992 $69.95
0130895725 C How to Program 3 2001 $69.95
0132261197 C How to Program 2 1994 $49.95
0130622214 C# How To Program 1 2002 $69.95
0135289106 C++ How to Program 2 1998 $49.95
0131173340 C++ How to Program 1 1994 $69.95
0130895717 C++ How to Program 3 2001 $69.95
013028419X e-Business and e- 1 2001 $69.95
Commerce How to
Program
0130308978 Internet and World Wide 2 2002 $69.95
Web How to Program
0130161438 Internet and World Wide 1 2000 $69.95
Web How to Program

P.Kumar, Rajalakshmi Engineering COllege 560


ORDER BY Clause

0130341517 Java How to Program 4 2002 $69.95


0136325890 Java How to Program 1 1998 $69.95
0130284181 Perl How to Program 1 2001 $69.95
0130923613 Python How to 1 2002 $69.95
Program
0130293636 Visual Basic .NET 2 2002 $69.95
How to Program
0134569555 Visual Basic 6 How to 1 1999 $69.95
Program
0130622265 Wireless Internet and 1 2001 $69.95
Mobile Business How
to Program
0130284173 XML How to Program 1 2001 $69.95
Fig. 22.20 Books from table Titles whose titles end with How
to Program in ascending order by title.

P.Kumar, Rajalakshmi Engineering COllege 561


Merging Data from Multiple Tables: INNER
JOIN
• Normalize databases
– Ensure database does not store data redundantly
– SELECT columnName1, columnName2, … FROM table1
INNER JOIN table2 ON table1, columnName =
table2.columnName

P.Kumar, Rajalakshmi Engineering COllege 562


Merging Data from Multiple Tables: INNER
JOIN
firstName lastName isbn firstName lastName isbn
Harvey Deitel 0130895601 Harvey Deitel 0130856118
Harvey Deitel 0130284181 Harvey Deitel 0130161438
Harvey Deitel 0130284173 Harvey Deitel 013028419x
Harvey Deitel 0130829293 Harvey Deitel 0139163050
Harvey Deitel 0134569555 Harvey Deitel 0135289106
Harvey Deitel 0130829277 Harvey Deitel 0130895717
Harvey Deitel 0130852473 Harvey Deitel 0132261197
Harvey Deitel 0138993947 Harvey Deitel 0130895725
Harvey Deitel 0130125075 Paul Deitel 0130895601
Paul Deitel 0130284181 Paul Deitel 0135289106
Paul Deitel 0130284173 Paul Deitel 0130895717
Paul Deitel 0130829293 Paul Deitel 0132261197
Paul Deitel 0134569555 Paul Deitel 0130895725
Paul Deitel 0130829277 Tem Nieto 0130284181
Paul Deitel 0130852473 Tem Nieto 0130284173
Paul Deitel 0138993947 Tem Nieto 0130829293
Paul Deitel 0130125075 Tem Nieto 0134569555
Paul Deitel 0130856118 Tem Nieto 0130856118
Paul Deitel 0130161438 Tem Nieto 0130161438
Paul Deitel 013028419x Tem Nieto 013028419x
Paul Deitel 0139163050 Sean Santry 0130895601
Fig. 22.21 Authors from table Authors and ISBN numbers of the authors’
books, sorted in ascending order by lastName and firstName.
P.Kumar, Rajalakshmi Engineering COllege 563
1 SELECT Titles.title, Titles.isbn, Authors.firstName,
2 Authors.lastName, Titles.copyright, Outline
3 Publishers.publisherName
4 FROM
5 ( Publishers INNER JOIN Titles Fig. 22.22
6 ON Publishers.publisherID = Titles.publisherID ) (1 of 1)
7 INNER JOIN
8 ( Authors INNER JOIN AuthorISBN
9 ON Authors.authorID = AuthorISBN.authorID )
10 ON Titles.isbn = AuthorISBN.isbn
11 ORDER BY Titles.title

P.Kumar, Rajalakshmi Engineering COllege 564


Joining Data from Tables Authors,
AuthorISBN, Titles and Publishers
Title isbn first- last- copy- publisher-
Name Name right Name
Advanced Java 2 Platform 0130895601 Paul Deitel 2002 Prentice Hall
How to Program
Advanced Java 2 Platform 0130895601 Harvey Deitel 2002 Prentice Hall
How to Program
Advanced Java 2 Platform 0130895601 Sean Santry 2002 Prentice Hall
How to Program
C How to Program 0131180436 Harvey Deitel 1992 Prentice Hall
C How to Program 0131180436 Paul Deitel 1992 Prentice Hall
C How to Program 0132261197 Harvey Deitel 1994 Prentice Hall
C How to Program 0132261197 Paul Deitel 1994 Prentice Hall
C How to Program 0130895725 Harvey Deitel 2001 Prentice Hall
C How to Program 0130895725 Paul Deitel 2001 Prentice Hall
C# How To Program 0130622214 Tem Nieto 2002 Prentice Hall
C# How To Program 0130622214 Paul Deitel 2002 Prentice Hall
C# How To Program 0130622214 Cheryl Yaeger 2002 Prentice Hall
C# How To Program 0130622214 Marina Zlatkina 2002 Prentice Hall
C# How To Program 0130622214 Harvey Deitel 2002 Prentice Hall
C++ How to Program 0130895717 Paul Deitel 2001 Prentice Hall
C++ How to Program 0130895717 Harvey Deitel 2001 Prentice Hall
P.Kumar, Rajalakshmi Engineering COllege 565
Joining Data from Tables Authors,
AuthorISBN, Titles and Publishers
C++ How to Program 0131173340 Paul Deitel 1994 Prentice Hall
C++ How to Program 0131173340 Harvey Deitel 1994 Prentice Hall
C++ How to Program 0135289106 Harvey Deitel 1998 Prentice Hall
C++ How to Program 0135289106 Paul Deitel 1998 Prentice Hall
e-Business and e-Commerce 0130323640 Harvey Deitel 2000 Prentice Hall
for Managers
e-Business and e-Commerce 0130323640 Kate Steinbuhler 2000 Prentice Hall
for Managers
e-Business and e-Commerce 0130323640 Paul Deitel 2000 Prentice Hall
for Managers
e-Business and e-Commerce 013028419X Harvey Deitel 2001 Prentice Hall
How to Program
e-Business and e-Commerce 013028419X Paul Deitel 2001 Prentice Hall
How to Program
e-Business and e-Commerce 013028419X Tem Nieto 2001 Prentice Hall
How to Program
Fig. 22.23 Portion of the result set produced by the query in Fig. 22.22.

P.Kumar, Rajalakshmi Engineering COllege 566


INSERT Statement

• Inserts new row in table


– INSERT INTO tableName ( columnName1, columnName2,
…, columnNameN ) VALUES ( value1 , value2, …, valueN )

P.Kumar, Rajalakshmi Engineering COllege 567


INSERT Statement

authorID firstName lastName


1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Kate Steinbuhler
5 Sean Santry
6 Ted Lin
7 Praveen Sadhu
8 David McPhie
9 Cheryl Yaeger
10 Marina Zlatkina
11 Ben Wiedermann
12 Jonathan Liperi
13 Sue Smith
Fig. 22.24 Table Authors after an INSERT operation to add a
row.

P.Kumar, Rajalakshmi Engineering COllege 568


UPDATE Statement

• Modifies data in a table


– UPDATE tableName SET columnName1 = value1,
columnName2 = value2, …, columnNameN = valueN
WHERE criteria

P.Kumar, Rajalakshmi Engineering COllege 569


UPDATE Statement

authorID firstName lastName


1 Harvey Deitel
2 Paul Deitel
3 Tem Nieto
4 Kate Steinbuhler
5 Sean Santry
6 Ted Lin
7 Praveen Sadhu
8 David McPhie
9 Cheryl Yaeger
10 Marina Zlatkina
11 Ben Wiedermann
12 Jonathan Liperi
13 Sue Jones
Fig. 22.25 Table Authors after an UPDATE operation to
change a row.

P.Kumar, Rajalakshmi Engineering COllege 570


DELETE Statement

• Removes data from a table


– DELETE FROM tableName
WHERE criteria
authorID firstName lastName
1 H a rv e y D e ite l
2 Paul D e ite l
3 T em N ie to
4 K a te S te in b u h le r
5 Sean S a n try
6 T ed L in
7 P ra v e e n Sadhu
8 D a v id M c P h ie
9 C h e ry l Y aeger
10 M a rin a Z la tk in a
11 B en W ie d e r m a n n
12 J o n a th a n L ip e ri
F ig . 2 2 .2 6 T a b le A u t h o r s a fte r a D E L E T E o p e ra tio n to re m o v e
a ro w .

P.Kumar, Rajalakshmi Engineering COllege 571


Active Server Pages (ASP)
 Server-side technologies
 Dynamically creates Web pages
 Use client information, server information
and information from the Internet
 Active Server Pages (ASP)
 Microsoft Server-side technology
 Dynamically build documents in response to
client requests
 Deliver dynamic Web content
 HTML, DHTML, ActiveX controls, client-side
scripts and Java applets

P.Kumar, Rajalakshmi Engineering COllege 572


ASP – Cont.
 Dynamically edit, change or add any content of a Web
page
 Respond to user queries or data submitted from HTML
forms
 Access any data or databases and return the results
to a browser
 Customize a Web page to make it more useful for
individual users
 The advantages of using ASP instead of CGI and Perl,
are those of simplicity and speed
 Provide security since your ASP code can not be
viewed from the browser

P.Kumar, Rajalakshmi Engineering COllege 573


How Active Server Pages Work
 Active Server Pages
 Processed by scripting engine
 Server-side ActiveX control
 .asp file extension
 Can contain HTML tags
 Scripting written with VBScript
 JavaScript also used
 Others (Independent Software Vendors)
 Communication with Server
 Client HTTP request to server
 Active server page processes request and
returns results

P.Kumar, Rajalakshmi Engineering COllege 574


Write text with ASP

<html> <body>
<% response.write("Hello World!") %>
</body> </html>
 An ASP file can also contain server
scripts, surrounded by the delimiters <%
and %>.
 Server scripts are executed on the
server, and can contain any expressions,
statements, procedures, or operators valid
for the scripting language you prefer to
use.
P.Kumar, Rajalakshmi Engineering COllege 575
ASP Variables
 <html>
<body>
<%
dim name
name=“Gold"
response.write("My name is: " & name)
%>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 576


Loop
 <html>
<body>

<%
dim i
for i=1 to 6
response.write("<h" & i & ">Header " & i & "</h" & i
& ">")
next
%>

</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 577


ASP Procedures

 <%@ language="javascript" %>


<html>
<head>
<%
function proc(num1,num2)
{
Response.Write(num1*num2)
}
%>
</head>
<body>
<p>
Result: <%proc(3,4)%>
</p>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 578


Forms – a.html
 <form method="get"
action="simpleform.asp"> First
Name: <input type="text"
name="fname" /> <br /> Last
Name: <input type="text"
name="lname" /> <br /><br />
<input type="submit"
value="Submit" /> </form>

P.Kumar, Rajalakshmi Engineering COllege 579


simpleform.asp
<body> Welcome
<%
response.write(request.form("fname"))
response.write(" " &
request.form("lname"))
%>
</body>

P.Kumar, Rajalakshmi Engineering COllege 580


ASP Cookies
 A cookie is often used to identify a
user.
 A cookie is a small file that the server
embeds on the user's computer.
 Each time the same computer
requests a page with a browser, it will
send the cookie too.
 With ASP, you can both create and
retrieve cookie values.

P.Kumar, Rajalakshmi Engineering COllege 581


Example
 <%
dim numvisits
response.cookies("NumVisits").Expires=date+365
numvisits=request.cookies("NumVisits")
if numvisits="" then
response.cookies("NumVisits")=1
response.write("Welcome! This is the first time you are visiting this Web
page.")
else
response.cookies("NumVisits")=numvisits+1
response.write("You have visited this ")
response.write("Web page " & numvisits)
if numvisits=1 then response.write " time before!"
else
response.write " times before!"
end if
end if
%>
<html>
<body>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 582


ASP Session Object
 The Session object is used to store
information about, or change settings
for a user session.
 Variables stored in the Session object
hold information about one single user,
and are available to all pages in one
application.
 <% Session.Timeout=5 %>

P.Kumar, Rajalakshmi Engineering COllege 583


ASP Objects

 ASP Response
ASP Request
ASP Application
ASP Session
ASP Server
ASP Error
ASP FileSystem
ASP TextStream
ASP Drive
ASP File
ASP Folder
ASP Dictionary
ASP ADO
P.Kumar, Rajalakshmi Engineering COllege 584
Response Object
 used to send output to the user from the
server
 <html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 585


Request Object
 used to get information from the user
 <html>
<body>
<form action="demo.asp" method="post">
First name:
<input type="text" name="fname" value="Donald" />
<br />
Last name:
<input type="text" name="lname" value="Duck" />
<br />
<input type="submit" value="Submit" />
</form>
<%
Response.Write(Request.Form)
%>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 586
Session Object
 The Session object is used to store
information about, or change settings
for a user session.
 Variables stored in the Session object
hold information about one single
user, and are available to all pages in
one application.

P.Kumar, Rajalakshmi Engineering COllege 587


Ex: A session's timeout
 This example sets and returns the timeout (in minutes) for the session.
 <html>
<body>
<%
response.write("<p>")
response.write("Default Timeout is: " & Session.Timeout & " minutes.")
response.write("</p>")
Session.Timeout=30
response.write("<p>")
response.write("Timeout is now: " & Session.Timeout & " minutes.")
response.write("</p>")
%>
</body>
</html>

 Output:
 Default Timeout is: 20 minutes. (Server time out)
 Timeout is now: 30 minutes. (Now client can change to 30 min as session
out)
P.Kumar, Rajalakshmi Engineering COllege 588
FileSystemObject
 The FileSystemObject is used to
access the file system on the server.
 This object can manipulate files,
folders, and directory paths.

P.Kumar, Rajalakshmi Engineering COllege 589


Does a specified file exist?
 <html>
<body>
<%
Set fs=Server.CreateObject("Scripting.FileSystemObject")
If (fs.FileExists("c:\test.html"))=true Then
Response.Write("File c:\test.html exists.")
Else
Response.Write("File c:\test.html does not exist.")
End If
set fs=nothing
%>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 590


FileSystemObject - methods
 DriveExists- Checks if a specified drive exists
 File Exists -Checks if a specified file exists
 Folder Exists -Checks if a specified folder exists
 Copy File - Copies one or more files from one
location to another
 Copy Folder- Copies one or more folders from
one location to another
 Delete File - Deletes one or more specified files
 Delete Folder - Deletes one or more specified
folders

P.Kumar, Rajalakshmi Engineering COllege 591


ADO - ActiveX Data Objects
 ADO can be used to access databases from
your web pages.
 The common way to access a database from
inside an ASP page is to:
 Create an ADO connection to a database
 Open the database connection
 Create an ADO recordset
 Open the recordset
 Extract the data you need from the recordset
 Close the recordset
 Close the connection

P.Kumar, Rajalakshmi Engineering COllege 592


Create a DSN-less Database
Connection
 If you have a database called “test.mdb"
located in a web directory like
"c:/webdata/", you can connect to the
database with the following ASP code:
 <% set
conn=Server.CreateObject("ADODB.Con
nection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/test.mdb" %>
P.Kumar, Rajalakshmi Engineering COllege 593
Display records
 First create a database connection,
 Then a recordset,
 and then display the data in HTML.

 <html>
<body>
<%
set
conn=Server.CreateObject("ADODB.Connection
")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/test.mdb"))

P.Kumar, Rajalakshmi Engineering COllege 594


Example
 set rs = Server.CreateObject("ADODB.recordset")
rs.Open "Select * from Customers", conn
do until rs.EOF
for each x in rs.Fields
Response.Write(x.name)
Response.Write(" = ")
Response.Write(x.value & "<br />")
next
Response.Write("<br />")
rs.MoveNext
loop
rs.close
conn.close
%>

P.Kumar, Rajalakshmi Engineering COllege 595


CASE STUDY
 Add a Record to a Table in a
Database
 Update a Record in a Table
 Delete a Record in a Table

P.Kumar, Rajalakshmi Engineering COllege 596


Add a Record to a Table in a
Database
 To add a new record to the
Customers table in the Test database
 First create a form that contains the
fields we want to collect data from

P.Kumar, Rajalakshmi Engineering COllege 597


Main.html
<html> <body>
<form method="post" action="adds.asp">
<table> <tr> <td>CustomerID:</td>
<td><input name="custid"></td> </tr>
<tr> <td>Company Name:</td>
<td><input name="compname"></td> </tr>
<tr> <td>Contact Name:</td> <td>
<input name="contname"></td> </tr>
<tr> <td>Address:</td> <td>
<input name="address"></td> </tr>
<tr> <td>City:</td> <td><input name="city"></td> </tr>
<tr> <td>Postal Code:</td> <td>
<input name="postcode"></td> </tr>
<tr> <td>Country:</td> <td><input name="country"></td> </tr>
</table> <br /><br />
<input type="submit" value="Add New">
<input type="reset" value="Cancel"> </form></body> </html>

P.Kumar, Rajalakshmi Engineering COllege 598


adds.asp
 When the user presses the submit button the form is sent to a
file called "adds.asp"
<html> <body>
<% set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open "c:/webdata/test.mdb“
sql="INSERT INTO customers (customerID,companyname,"
sql=sql & "contactname,address,city,postalcode,country)"
sql=sql & " VALUES " sql=sql & "('" & Request.Form("custid") & "',"
sql=sql & "'" & Request.Form("compname") & "',"
sql=sql & "'" & Request.Form("contname") & "',"
sql=sql & "'" & Request.Form("address") & "',"
sql=sql & "'" & Request.Form("city") & "',"
sql=sql & "'" & Request.Form("postcode") & "',"
sql=sql & "'" & Request.Form("country") & "')“

P.Kumar, Rajalakshmi Engineering COllege 599


Contd.
on error resume next
conn.Execute sql,recaffected
if err<>0 then
Response.Write("No update permissions!")
else Response.Write("<h3>" & recaffected & "
record added</h3>")
end if
conn.close %>
</body> </html>
P.Kumar, Rajalakshmi Engineering COllege 600
Quiz
1. What does ASP stand for?
 Active Server Pages
 A Server Page
 All Standard Pages
 Active Standard Pages

P.Kumar, Rajalakshmi Engineering COllege 601


2. ASP server scripts are
surrounded by delimiters, which?
 <&>...</&>
 <%>...</%>
 <script>...</script>
 <%...%>

P.Kumar, Rajalakshmi Engineering COllege 602


3. How do you write "Hello World" in
ASP ?
 Response.Write("Hello World")
 Document.Write("Hello World")
 "Hello World"

P.Kumar, Rajalakshmi Engineering COllege 603


4. "<%=" is the same as:
 <%Equal
 <%Write
 <%Document.Write
 <%Response.Write

P.Kumar, Rajalakshmi Engineering COllege 604


5. What is the default scripting
language in ASP?
 VBScript
 EcmaScript
 PERL
 JavaScript

P.Kumar, Rajalakshmi Engineering COllege 605


6. How can you script your ASP code in
JavaScript?

 JavaScript is the default scripting language


 End the document with: <% language="javascript" %>

 Start the document with: <%@ language="javascript"


%>
 Start the document with: <% language="javascript"
%>

P.Kumar, Rajalakshmi Engineering COllege 606


7. How do you get information from
a form that is submitted using
the "get" method?

 Request.Form
 Request.QueryString

P.Kumar, Rajalakshmi Engineering COllege 607


8. How do you get information from
a form that is submitted using the
"post" method?

 Request.QueryString
 Request.Form

P.Kumar, Rajalakshmi Engineering COllege 608


9. Which ASP property is used to
identify a user?

 The Server object


 The Application object
 An ASP Cookie

P.Kumar, Rajalakshmi Engineering COllege 609


10. All users of the same application
share ONE Session object.

 True
 False

P.Kumar, Rajalakshmi Engineering COllege 610


11. If a user has Cookies enabled, a
session variable is available to all
pages in one application.

 True
 False

P.Kumar, Rajalakshmi Engineering COllege 611


Answers
 1- Active Server Pages
 2 - <%...%>
 3 - Response.Write("Hello World")
 4 - <%Response.Write
 5 - VBScript
 6 - Start the document with: <%@
language="javascript" %>
 7 - Request.QueryString
 8 - Request.Form
 9 - An ASP Cookie
 10 – False
 11 - True

P.Kumar, Rajalakshmi Engineering COllege 612


8.1 Introduction
- SGML is a meta-markup language

- Developed in the early 1980s; ISO std. In 1986

- HTML was developed using SGML in the early


1990s - specifically for Web documents

- Two problems with HTML:

1. Fixed set of tags and attributes

- User cannot define new tags or attributes

- So, the given tags must fit every kind of


document, and the tags cannot connote
any particular meaning

2. There are no restrictions on arrangement or


order of tag appearance in a document

- One solution to the first of these problems:


Let each group of users define their own tags
(with implied meanings)

(i.e., design their own “HTML”s using SGML)

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 1 613
8.1 Introduction (continued)
- Problem with using SGML:

- It’s too large and complex to use, and it is very


difficult to build a parser for it

- A better solution: Define a lite version of SGML

- XML is not a replacement for HTML

- HTML is a markup language used to describe the


layout of any kind of information

- XML is a meta-markup language that can be used


to define markup languages that can define the
meaning of specific kinds of information

- XML is a very simple and universal way of storing


and transferring data of any kind

- XML does not predefine any tags

- XML has no hidden specifications

- All documents described with an XML-derived


markup language can be parsed with a single
parser

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 2 614
8.1 Introduction (continued)
- We will refer to an XML-based markup language as
a tag set

- Strictly speaking, a tag set is an XML application,


but that terminology can be confusing

- An XML processor is a program that parses XML


documents and provides the parts to an application

- Documents that use an XML-based markup


language is an XML document

- Both IE6 and NS7 support basic XML

8.2 The Syntax of XML


- The syntax of XML is in two distinct levels:

1. The general low-level rules that apply to all


XML documents

2. For a particular XML tag set, either a document


type definition (DTD) or an XML schema

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 3 615
8.2 The Syntax of XML (continued)
- General XML Syntax

- XML documents consist of:

1. data elements
2. markup declarations (instructions for the XML
parser)
3. processing instructions (for the application
program that is processing the data in the
document)

- All XML documents begin with an XML declaration:

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

- XML comments are just like HTML comments

- XML names:

- Must begin with a letter or an underscore


- They can include digits, hyphens, and periods
- There is no length limitation
- They are case sensitive (unlike HTML names)

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 4 616
8.2 The Syntax of XML (continued)
- Syntax rules for XML: same as those of XHTML

- Every XML document defines a single root


element, whose opening tag must appear as
the first line of the document

- An XML document that follows all of these rules


is well formed

<?xml version = "1.0">


<ad>
<year> 1960 </year>
<make> Cessna </make>
<model> Centurian </model>
<color> Yellow with white trim </color>
<location>
<city> Gulfport </city>
<state> Mississippi </state>
</location>
</ad>

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 5 617
8.2 The Syntax of XML (continued)
- Attributes are not used in XML the way they are in
HTML

- In XML, you often define a new nested tag to


provide more info about the content of a tag

- Nested tags are better than attributes, because


attributes cannot describe structure and the
structural complexity may grow

- Attributes should always be used to identify


numbers or names of elements (like HTML id and
name attributes)

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 6 618
8.2 The Syntax of XML (continued)
<!-- A tag with one attribute -->
<patient name = "Maggie Dee Magpie">
...
</patient>

<!-- A tag with one nested tag -->


<patient>
<name> Maggie Dee Magpie </name>
...
</patient>

<!-- A tag with one nested tag, which contains


three nested tags -->
<patient>
<name>
<first> Maggie </first>
<middle> Dee </middle>
<last> Magpie </last>
</name>
...
</patient>

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 7 619
8.3 XML Document Structure
- An XML document often uses two auxiliary files:

- One to specify the structural syntactic rules

- One to provide a style specification

- An XML document has a single root element, but


often consists of one or more entities

- Entities range from a single special character to


a book chapter

- An XML document has one document entity

- All other entities are referenced in the


document entity

- Reasons for entity structure:

1. Large documents are easier to manage

2. Repeated entities need not be literally repeated

3. Binary entities can only be referenced in the


document entities (XML is all text!)

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 8 620
8.3 XML Document Structure (continued)
- When the XML parser encounters a reference to
a non-binary entity, the entity is merged in

- Entity names:

- No length limitation
- Must begin with a letter, a dash, or a colon
- Can include letters, digits, periods, dashes,
underscores, or colons

- A reference to an entity has the form:

&entity_name;

- One common use of entities is for special


characters that may be used for markup delimiters

- These are predefined (as in XHTML):

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

- The user can only define entities in a DTD

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 9 621
8.3 XML Document Structure (continued)
- If several predefined entities must appear near
each other in a document, it is better to avoid
using entity references

- Character data section

<![CDATA[ content ]]>

e.g., instead of

Start &gt; &gt; &gt; &gt; HERE


&lt; &lt; &lt; &lt;

use

<![CDATA[Start >>>> HERE <<<<]]>

- If the CDATA content has an entity reference,


it is taken literally

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 10
622
8.4 Document Type Definitions
- A DTD is a set of structural rules called
declarations

- These rules specify a set of elements, along


with how and where they can appear in a
document

- Purpose: provide a standard form for a collection


of XML documents and define a markup
language for them

- Not all XML documents have or need a DTD

- The DTD for a document can be internal or


external

- All of the declarations of a DTD are enclosed in


the block of a DOCTYPE markup declaration

- DTD declarations have the form:

<!keyword … >

- There are four possible declaration keywords:


ELEMENT, ATTLIST, ENTITY, and NOTATION

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 11
623
8.4 Document Type Definitions (continued)
- Declaring Elements

- Element declarations are similar to BNF

- An element declaration specifies the name of an


an element, and the element’s structure

- If the element is a leaf node of the document tree,


its structure is in terms of characters

- If it is an internal node, its structure is a list of


children elements (either leaf or internal nodes)

- General form:

<!ELEMENT element_name (list of child names)>

e.g.,

<!ELEMENT memo (from, to, date, re, body)>

memo

from to date re body

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 12
624
8.4 Document Type Definitions (continued)
- Declaring Elements (continued)

- Child elements can have modifiers, +, *, ?

e.g.,

<!ELEMENT person
(parent+, age, spouse?, sibling*)>

- Leaf nodes specify data types, most often


PCDATA, which is an acronym for parsable
character data

- Data type could also be EMPTY (no content)


and ANY (can have any content)

- Example of a leaf declaration:

<!ELEMENT name (#PCDATA)>

- Declaring Attributes

- General form:

<!ATTLIST el_name at_name at_type [default]>

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 13
625
8.4 Document Type Definitions (continued)
- Declaring Attributes (continued)

- Attribute types: there are ten different types, but


we will consider only CDATA

- Default values:

a value
#FIXED value (every element will have
this value),
#REQUIRED (every instance of the element must
have a value specified), or
#IMPLIED (no default value and need not specify
a value)

<!ATTLIST car doors CDATA "4">


<!ATTLIST car engine_type CDATA #REQUIRED>
<!ATTLIST car price CDATA #IMPLIED>
<!ATTLIST car make CDATA #FIXED "Ford">

<car doors = "2" engine_type = "V8">


...
</car>

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 14
626
8.4 Document Type Definitions (continued)
- Declaring Entities

- Two kinds:

- A general entity can be referenced anywhere in


the content of an XML document

- A parameter entity can be referenced only in


a markup declaration

- General form of declaration:

<!ENTITY [%] entity_name "entity_value">

e.g., <!ENTITY jfk "John Fitzgerald Kennedy">

- A reference: &jfk;

- If the entity value is longer than a line, define it


in a separate file (an external text entity)

<!ENTITY entity_name SYSTEM "file_location">

 SHOW planes.dtd

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 15
627
8.4 Document Type Definitions (continued)
- XML Parsers

- Always check for well formedness

- Some check for validity, relative to a given DTD

- Called validating XML parsers

- You can download a validating XML parser from:

http://xml.apache.org/xerces-j/index.html

- Internal DTDs

<!DOCTYPE root_name [

]>

- External DTDs

<!DOCTYPE XML_doc_root_name SYSTEM


“DTD_file_name”>

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 16
628
8.5 Namespaces
- A markup vocabulary is the collection of all of the
element types and attribute names of a markup
language (a tag set)

- An XML document may define its own tag set and


also use those of another tag set - CONFLICTS!

- An XML namespace is a collection of names used


in XML documents as element types and attribute
names

- The name of an XML namespace has the form of


a URI

- A namespace declaration has the form:

<element_name xmlns[:prefix] = URI>

- The prefix is a short name for the namespace,


which is attached to names from the
namespace in the XML document

<gmcars xmlns:gm = "http://www.gm.com/names">

- In the document, you can use <gm:pontiac>

- Purposes of the prefix:


1. Shorthand
2. URI includes characters that are illegal in XML

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 17
629
8.5 Namespaces (continued)
- Can declare two namespaces on one element

<gmcars xmlns:gm = "http://www.gm.com/names"


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

- The gmcars element can now use gm names and


html names

- One namespace can be made the default by


leaving the prefix out of the declaration

8.6 XML Schemas


- Problems with DTDs:

1. Syntax is different from XML - cannot be parsed


with an XML parser

2. It is confusing to deal with two different syntactic


forms

3. DTDs do not allow specification of particular


kinds of data

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 18
630
8.6 XML Schemas (continued)
- XML Schemas is one of the alternatives to DTD

- Two purposes:

1. Specify the structure of its instance XML


documents

2. Specify the data type of every element and


attribute of its instance XML documents

- Schemas are written using a namespace:

http://www.w3.org/2001/XMLSchema

- Every XML schema has a single root, schema

The schema element must specify the namespace


for schemas as its xmlns:xsd attribute

- Every XML schema itself defines a tag set, which


must be named

targetNamespace =
"http://cs.uccs.edu/planeSchema"

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 19
631
8.6 XML Schemas (continued)
- If we want to include nested elements, we must
set the elementFormDefault attribute to
qualified

- The default namespace must also be specified

xmlns = "http://cs.uccs.edu/planeSchema"

- A complete example of a schema element:

<xsd:schema

<!-- Namespace for the schema itself -->

xmlns:xsd =
"http://www.w3.org/2001/XMLSchema"

<!-- Namespace where elements defined here


will be placed -->

targetNamespace =
"http://cs.uccs.edu/planeSchema"

<!-- Default namespace for this document -->

xmlns = "http://cs.uccs.edu/planeSchema"

<!-- Next, specify non-top-level elements to


be in the target namespace -->

elementFormDefault = "qualified">

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 20
632
8.6 XML Schemas (continued)
- Defining an instance document

- The root element must specify the namespaces


it uses

1. The default namespace

2. The standard namespace for instances


(XMLSchema-instance)

3. The location where the default namespace is


defined, using the schemaLocation attribute,
which is assigned two values

<planes
xmlns = "http://cs.uccs.edu/planeSchema"
xmlns:xsi =
http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation =
"http://cs.uccs.edu/planeSchema
planes.xsd" >

- Data Type Categories

1. Simple (strings only, no attributes and no


nested elements)

2. Complex (can have attributes and nested


elements)

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 21
633
8.6 XML Schemas (continued)
- XMLS defines 44 data types

- Primitive: string, Boolean, float, …

- Derived: byte, decimal, positiveInteger, …

- User-defined (derived) data types – specify


constraints on an existing type (the base type)

- Constraints are given in terms of facets

(totalDigits, maxInclusive, etc.)

- Both simple and complex types can be either


named or anonymous

- DTDs define global elements (context is irrelevant)

- With XMLS, context is essential, and elements


can be either:

1. Local, which appears inside an element


that is a child of schema, or

2. Global, which appears as a child of schema

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 22
634
8.6 XML Schemas (continued)
- Defining a simple type:

- Use the element tag and set the name and type
attributes

<xsd:element name = "bird"


type = "xsd:string" />

- An instance could have:

<bird> Yellow-bellied sap sucker </bird>

- Element values can be constant, specified with


the fixed attribute

fixed = "three-toed"

- User-Defined Types

- Defined in a simpleType element, using facets


specified in the content of a restriction
element

- Facet values are specified with the value


attribute

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 23
635
8.6 XML Schemas (continued)
<xsd:simpleType name = "middleName" >
<xsd:restriction base = "xsd:string" >
<xsd:maxLength value = "20" />
</xsd:restriction>
</xsd:simpleType>

- There are several categories of complex types,


but we discuss just one, element-only elements

- Element-only elements are defined with the


complexType element

- Use the sequence tag for nested elements that


must be in a particular order

- Use the all tag if the order is not important

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 24
636
8.6 XML Schemas (continued)
<xsd:complexType name = "sports_car" >
<xsd:sequence>
<xsd:element name = "make"
type = "xsd:string" />
<xsd:element name = "model "
type = "xsd:string" />
<xsd:element name = "engine"
type = "xsd:string" />
<xsd:element name = "year"
type = "xsd:string" />
</xsd:sequence>
</xsd:complexType>

- Nested elements can include attributes that give


the allowed number of occurrences
(minOccurs, maxOccurs, unbounded)

 SHOW planes.xsd and planes1.xml

- We can define nested elements elsewhere

<xsd:element name = "year" >


<xsd:simpleType>
<xsd:restriction base = "xsd:decimal" >
<xsd:minInclusive value = "1990" />
<xsd:maxInclusive value = "2003" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 25
637
8.6 XML Schemas (continued)
- The global element can be referenced in the
complex type with the ref attribute

<xsd:element ref = "year" />

- Validating Instances of XML Schemas

- Can be done with several different tools

- One of them is xsv, which is available from:

http://www.ltg.ed.ac.uk/~ht/xsv-status.html

- Note: If the schema is incorrect (bad format), xsv


reports that it cannot find the schema

8.7 Displaying Raw XML Documents


- There is no presentation information in an XML
document

- An XML browser should have a default style sheet


for an XML document that does not specify one

- You get a stylized listing of the XML

 SHOW planes.xml

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 26
638
8.8 Displaying XML Documents with
CSS
- A CSS style sheet for an XML document is just a
list of its tags and associated styles

- The connection of an XML document and its style


sheet is made through an xml-stylesheet
processing instruction

<?xml-stylesheet type = "text/css"


href = "mydoc.css"?>

--> SHOW planes.css and run planes.xml

8.9 XSLT Style Sheets


- XSL began as a standard for presentations of XML
documents

- Split into three parts:

- XSLT – Transformations
- XPATH - XML Path Language
- XSL-FO - Formatting objects

- XSLT uses style sheets to specify


transformations

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 27
639
8.9 XSLT Style Sheets (continued)
- An XSLT processor merges an XML document into
an XSLT style sheet

- This merging is a template-driven process

- An XSLT style sheet can specify page layout,


page orientation, writing direction, margins, page
numbering, etc.

- The processing instruction we used for connecting


a XSLT style sheet to an XML document is used to
connect an XSLT style sheet to an XML document

<?xml-stylesheet type = "text/xsl"


href = "XSLT style sheet"?>

- An example:

<?xml version = "1.0"?>


<!-- xslplane.xml -->
<?xml-stylesheet type = "text/xsl"
href = "xslplane.xsl" ?>
<plane>
<year> 1977 </year>
<make> Cessna </make>
<model> Skyhawk </model>
<color> Light blue and white </color>
</plane>

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 28
640
8.9 XSLT Style Sheets (continued)
- An XSLT style sheet is an XML document with a
single element, stylesheet, which defines
namespaces

<xsl:stylesheet xmlns:xsl =
"http://www.w3.org/1999/XSL/Format"
xmlns =
"http://www.w3.org/1999/xhtml">

- If a style sheet matches the root element of the


XML document, it is matched with the template:

<xsl:template match = "/">

- A template can match any element, just by naming


it (in place of /)

- XSLT elements include two different kinds of


elements, those with content and those for which
the content will be merged from the XML doc

- Elements with content often represent HTML


elements

<span style = "font-size: 14">


Happy Easter!
</span>

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 29
641
8.9 XML Transformations and Style
Sheets (continued)
- XSLT elements that represent HTML elements are
simply copied to the merged document

- The XSLT value-of element

- Has no content

- Uses a select attribute to specify part of the XML


data to be merged into the new document

<xsl:value-of select = ”CAR/ENGINE" />

- The value of select can be any branch of the


document tree

--> SHOW xslplane.xsl and display xslplane.xml

- The XSLT for-each element

- Used when an XML document has a sequence of


the same elements

--> SHOW xslplanes.xml


--> SHOW xslplanes.xsl & display

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 30
642
8.10 XML Processors
- Purposes:

1. Check the syntax of a document for well-


formedness

2. Replace all references to entities by their


definitions

3. Copy default values (from DTDs or schemas)


into the document

4. If a DTD or schema is specified and the


processor includes a validating parser, the
structure of the document is validated

- Two ways to check well-formedness:

1. A browser with an XML parser

2. A stand-alone XML parser

- There are two different approaches to designing


XML processors:

- SAX and the DOM approach

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 31
643
8.10 XML Processors (continued)
- The SAX (Simple API for XML) Approach:

- Widely accepted and supported

- Based on the concept of event processing:

- Every time a syntactic structure (e.g., a tag, an


attribute, etc.) is recognized, the processor
raises an event

- The application defines event handlers to


respond to the syntactic structures

- The DOM Approach

- The DOM processor builds a DOM tree structure


of the document

(Similar to the processing by a browser of an


XHTML document)

- When the tree is complete, it can be traversed


and processed

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 32
644
8.10 XML Processors (continued)
- Advantages of the DOM approach:

1. Good if any part of the document must be


accessed more than once

2. If any rearrangement of the document must be


done, it is facilitated by having a
representation of the whole document in
memory

3. Random access to any part of the document is


possible

4. Because the whole document is parsed before


any processing takes place, processing of an
invalid document is avoided

- Disadvantages of the DOM approach:

1. Large documents require a large memory

2. The DOM approach is slower

- Note: Most DOM processors use a SAX front


end

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 33
645
8.10 Web Services
- The ultimate goal of Web services:
- Allow different software in different places,
written in different languages and resident on
different platforms, to connect and interoperate

- The Web began as provider of markup documents,


served through the HTTP methods, GET and
POST
- An information service system

- A Web service is closely related to an information


service

- Rather than having a server provide documents,


the server provides services, through server-
resident software

- The same Web server can provide both


documents and services

- The original Web services were provided via


Remote Procedure Call (RPC), through two
technologies, DCOM and CORBA

- DCOM and CORBA use different protocols,


which defeats the goal of universal component
interoperability

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 34
646
8.10 Web Services (continued)
- There are three roles required to provide and use
Web services:

1. Service providers
2. Service requestors
3. A service registry

- Web Serviced Definition Language (WSDL)

- Used to describe available services, as well as


of message protocols for their use

- Such descriptions reside on the Web server

- Universal Description, Discovery, and


Integration Service (UDDI)

- Used to create Web services registry, and also


methods that allow a remote system to
determine which services are available

- Standard Object Access Protocol (SOAP)

- An XML-based specification that defines the


forms of messages and RPCs

- Supports the exchange of information among


distributed systems

Chapter 8 P.Kumar, Rajalakshmi Engineering COllege


© 2005 by Addison Wesley Longman, Inc. 35
647
IT1451 – WEB TECHNOLOGY

8TH SEMESTER – INFORMATION TECHNOLOGY

UNIT – 5 NOTES

P.Kumar, Rajalakshmi Engineering COllege 648


Servlets
Introduction
Servlet Overview and Architecture
Interface Servlet and the Servlet Life Cycle
HttpServlet Class
HttpServletRequest Interface
HttpServletResponse Interface
Handling HTTP get Requests
Setting Up the Apache Tomcat Server
Deploying a Web Application
Handling HTTP get Requests Containing Data
Handling HTTP post Requests
Redirecting Requests to Other Resources
Multi-Tier Applications: Using JDBC from a Servlet

P.Kumar, Rajalakshmi Engineering COllege 649


Objectives

1. To execute servlets with the Apache Tomcat server.


2. To be able to respond to HTTP requests from an
HttpServlet.
3. To be able to redirect requests to static and dynamic Web
resources.

P.Kumar, Rajalakshmi Engineering COllege 650


Servlets

• A Servlet is a program that runs on a server and


generates a response upon a HTTP request
• Building Web pages on the fly is useful (and commonly
done) for a number of reasons:
• The Web page is based on data submitted by the user.
For example the results pages from search engines are
generated this way, and programs that process orders for e-
commerce sites do this as well.
• The data changes frequently. For example, a weather-
report or news headlines page might build the page
dynamically, perhaps returning a previously built page if it
is still up to date.
• The Web page uses information from corporate
databases or other such sources. For example, you
would use this for making a Web page at an on-line store
that lists current prices and number of items in stock.
P.Kumar, Rajalakshmi Engineering COllege 651
Servlets

• A client sends an HTTP request to the server or


servlet container.
• The server or servlet container receives the request
and directs it to be processed by the appropriate
servlet.
• The servlet does its processing, which may include
interacting with a database or other server-side
components such as other servlets, JSPs
• The servlet returns its results to the client—
normally in the form of an HTML

P.Kumar, Rajalakshmi Engineering COllege 652


Servlet Overview and Architecture

• Servlet container (servlet engine)


– Server that executes a servlet
• Web servers and application servers
– Sun ONE Application Server
– Microsoft’s Internet Information Server (IIS)
– Apache HTTP Server
– BEA’s WebLogic Application Server
– IBM’s WebSphere Application Server
– World Wide Web Consortium’s Jigsaw Web Server

P.Kumar, Rajalakshmi Engineering COllege 653


Interface Servlet and the Servlet Life Cycle

• Interface Servlet
– All servlets must implement this interface
– All methods of interface Servlet are invoked by servlet
container
• Servlet life cycle
– Servlet container invokes the servlet’s init method
– Servlet’s service method handles requests
– Servlet’s destroy method releases servlet resources when
the servlet container terminates the servlet
• Servlet implementation
– GenericServlet
– HttpServlet
P.Kumar, Rajalakshmi Engineering COllege 654
Interface Servlet and the Servlet Life Cycle
(Cont.)
• Init - This method is automatically called once
during a servlet’s execution cycle to initialize the
servlet.
• service method - which receives the request,
processes the request and sends a response to the
client.
• Destroy - This “cleanup” method is called when a
servlet is terminated by its servlet container.
Resources used by the servlet, such as an open file
or an open database connection, should be
deallocated here.
P.Kumar, Rajalakshmi Engineering COllege 655
HttpServlet Class

• which defines enhanced processing capabilities for


servlets that extend the functionality of a Web
server.
• Two most common HTTP request types
– get requests - gets (or retrieves) information from a server.
– post requests – posts (or sends) data to a server.

• Method doGet responds to get requests


• Method doPost responds to post requests
• HttpServletRequest and
HttpServletResponse objects
P.Kumar, Rajalakshmi Engineering COllege 656
HttpServletRequest Interface

• Web server
– creates an HttpServletRequest object
– passes it to the servlet’s service method
• HttpServletRequest object contains the request from the
client
• Methods: getParameter, Enumeration, getCookies, getSession

HttpServletResponse Interface
• Web server
– creates an HttpServletResponse object
– passes it to the servlet’s service method
• Methods: addCookie, PrintWriter, setContentType

P.Kumar, Rajalakshmi Engineering COllege 657


Example 1: HTTPGetServlet.java
// Creating and sending a page to the client
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HTTPGetServlet extends HttpServlet {


public void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
PrintWriter output;

response.setContentType( "text/html" ); // content type


output = response.getWriter(); // get writer

// create and send HTML page to client


StringBuffer buf = new StringBuffer();
buf.append( "<HTML><HEAD><TITLE>\n" );
buf.append( "A Simple Servlet Example\n" );
buf.append( "</TITLE></HEAD><BODY>\n" );
buf.append( "<H1>Welcome to Servlets!</H1>\n" );
buf.append( "</BODY></HTML>" );
output.println( buf.toString() );
output.close(); // close PrintWriter stream
}
}
P.Kumar, Rajalakshmi Engineering COllege 658
HTTPGetServlet.html

<HTML>
<HEAD>
<TITLE>Servlet HTTP GET Example</TITLE>
</HEAD>

<BODY>
<FORM ACTION="http://localhost:8080/servlet/HTTPGetServlet"
METHOD="GET">
<P>Click the button to have the servlet send an HTML document</P>
<INPUT TYPE="submit" VALUE="Get HTML Document">
</FORM>
</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 659


Setting Up the Apache Tomcat Server

• Download Tomcat (version 4.1.27)


– jakarta.apache.org/site/binindex.cgi

• Define environment variables


– JAVA_HOME
– CATALINA_HOME
• Start the Tomcat server
– startup
• Launch the Tomcat server
– http://localhost:8080/

P.Kumar, Rajalakshmi Engineering COllege 660


Setting Up the Apache Tomcat Server
(Cont.).

Tomcat documentation home page. (Courtesy of The Apache Software Foundation.)


P.Kumar, Rajalakshmi Engineering COllege 661
Deploying a Web Application

• Web applications
– JSPs, servlets and their supporting files
• Deploying a Web application
– Directory structure
• Context root
– Web application archive file (WAR file)
– Deployment descriptor
• web.xml

P.Kumar, Rajalakshmi Engineering COllege 662


Deploying a Web Application (Cont.)

Directory Description
context root This is the root directory for the Web application. All the
JSPs, HTML documents, servlets and supporting files such
as images and class files reside in this directory or its
subdirectories. The name of this directory is specified by the
Web application creator. To provide structure in a Web
application, subdirectories can be placed in the context root.
For example, if your application uses many images, you
might place an images subdirectory in this directory. The
examples of this chapter use jhtp5 as the context root.
WEB-INF This directory contains the Web application deployment
descriptor (web.xml).
WEB-INF/classes This directory contains the servlet class files and other
supporting class files used in a Web application. If the
classes are part of a package, the complete package directory
structure would begin here.
WEB-INF/lib This directory contains Java archive (JAR) files. The JAR
files can contain servlet class files and other supporting class
files used in a Web application.
Fig. 36.8 Web application standard directories.

P.Kumar, Rajalakshmi Engineering COllege 663


Deployment
<web-app>
<!-- General description of your Web application -->
<display-name> Advanced Java How to Program JSP and Servlet </display-name>

<description>
This is the Web application in which we demonstrate our JSP and Servlet examples.
</description>

<!-- Servlet definitions -->


<servlet>
<servlet-name>welcome1</servlet-name>

<description> A simple servlet that handles an HTTP get request. </description>

<servlet-class> com.deitel.advjhtp1.servlets.WelcomeServlet </servlet-class>


</servlet>

<!-- Servlet mappings -->


<servlet-mapping>
<servlet-name>welcome1</servlet-name>
<url-pattern>/welcome1</url-pattern>
</servlet-mapping>
P.Kumar, Rajalakshmi Engineering COllege 664
</web-app>
Deploying a Web Application (Cont.)

• Invoke WelcomeServlet example


– /iw3htp3/welcome1
• /iw3htp3 specifies the context root
• /welcome1 specifies the URL pattern

• URL pattern formats


– Exact match
• /iw3htp3/welcome1
– Path mappings
• /iw3htp3/example/*
– Extension mappings
• *.jsp
– Default servlet
•/
P.Kumar, Rajalakshmi Engineering COllege 665
Deploying a Web Application (Cont.)

WelcomeServlet Web application directory and file structure


iw3htp3
servlets
WelcomeServlet.html
WEB-INF
web.xml
classes
WelcomeServlet.class
Fig. 36.10 Web application directory and file structure for
WelcomeServlet.

P.Kumar, Rajalakshmi Engineering COllege 666


Handling HTTP post Requests

• HTTP post request


– Post data from an HTML form to a server-side form handler
– Browsers cache Web pages

P.Kumar, Rajalakshmi Engineering COllege 667


CookieExample.java

// Using cookies.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CookieExample extends HttpServlet {


private final static String names[] = { "C", "C++", "Java", "Visual Basic 6" };
private final static String isbn[] = { “11", “12", “13", “14" };

public void doPost( HttpServletRequest request, HttpServletResponse response )


throws ServletException, IOException
{
PrintWriter output;
String language = request.getParameter( "lang" );

Cookie c = new Cookie( language, getISBN( language ) );


c.setMaxAge( 120 ); // seconds until cookie removed
response.addCookie( c ); // must precede getWriter

response.setContentType( "text/html" );
output = response.getWriter();
P.Kumar, Rajalakshmi Engineering COllege 668
// send HTML page to client
output.println( "<HTML><HEAD><TITLE>" );
output.println( "Cookies" );
output.println( "</TITLE></HEAD><BODY>" );
output.println( "<P>Welcome to Cookies!<BR>" );
output.println( "<P>" );
output.println( language );
output.println( " is a great language." );
output.println( "</BODY></HTML>" );

output.close(); // close stream


}

public void doGet( HttpServletRequest request, HttpServletResponse response )


throws ServletException, IOException
{
PrintWriter output;
Cookie cookies[];

cookies = request.getCookies(); // get client's cookies

response.setContentType( "text/html" );
output = response.getWriter();

output.println( "<HTML><HEAD><TITLE>" );
output.println( "Cookies II" );
output.println( "</TITLE></HEAD><BODY>" );

P.Kumar, Rajalakshmi Engineering COllege 669


if ( cookies != null && cookies.length != 0 ) {
output.println( "<H1>Recommendations</H1>" );

// get the name of each cookie


for ( int i = 0; i < cookies.length; i++ )
output.println(
cookies[ i ].getName() + " How to Program. " +
"ISBN#: " + cookies[ i ].getValue() + "<BR>" );
}
else {
output.println( "<H1>No Recommendations</H1>" );
output.println( "You did not select a language or" );
output.println( "the cookies have expired." );
}

output.println( "</BODY></HTML>" );
output.close(); // close stream
}

private String getISBN( String lang )


{
for ( int i = 0; i < names.length; ++i )
if ( lang.equals( names[ i ] ) )
return isbn[ i ];

return ""; // no matching string found


}
}
P.Kumar, Rajalakshmi Engineering COllege 670
SelectLanguage.html
<HTML>
<HEAD>
<TITLE>Cookies</TITLE>
</HEAD>

<BODY>
<FORM ACTION=http://localhost:8080/servlet/CookieExample METHOD="POST">
<STRONG>Select a programming language:</STRONG><BR>
<INPUT TYPE="radio" NAME="lang" VALUE="C">C<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="C++">C++<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="Java" CHECKED>
Java<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="Visual Basic 6">
Visual Basic 6
<P><INPUT TYPE="submit" VALUE="Submit">
<INPUT TYPE="reset"> </P>
</FORM>
</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 671


Cookies

P.Kumar, Rajalakshmi Engineering COllege 672


SessionExample.java

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

public class SessionExample extends HttpServlet {


private final static String names[] = { "C", "C++", "Java", "Visual Basic 6" };
private final static String isbn[] = { “11", “12", “13", “14" };

public void doPost( HttpServletRequest request, HttpServletResponse response )


throws ServletException, IOException
{
PrintWriter output;
String language = request.getParameter( "lang" );

// Get the user's session object.


// Create a session (true) if one does not exist.
HttpSession session = request.getSession( true );

// add a value for user's choice to session


session.putValue( language, getISBN( language ) );

response.setContentType( "text/html" );
output = response.getWriter();

P.Kumar, Rajalakshmi Engineering COllege 673


SessionExample.java
// send HTML page to client
output.println( "<HTML><HEAD><TITLE>" );
output.println( "Sessions" );
output.println( "</TITLE></HEAD><BODY>" );
output.println( "<P>Welcome to Sessions!<BR>" );
output.println( "<P>" );
output.println( language );
output.println( " is a great language." );
output.println( "</BODY></HTML>" );

output.close(); // close stream


}

public void doGet( HttpServletRequest request, HttpServletResponse response )


throws ServletException, IOException
{
PrintWriter output;

// Get the user's session object.


// Don't create a session (false) if one does not exist.
HttpSession session = request.getSession( false );
P.Kumar, Rajalakshmi Engineering COllege 674
SessionExample.java
// get names of session object's values
String valueNames[];

if ( session != null )
valueNames = session.getValueNames();
else
valueNames = null;

response.setContentType( "text/html" );
output = response.getWriter();

output.println( "<HTML><HEAD><TITLE>" );
output.println( "Sessions II" );
output.println( "</TITLE></HEAD><BODY>" );

if ( valueNames != null && valueNames.length != 0 ) {


output.println( "<H1>Recommendations</H1>" );

// get value for each name in valueNames


for ( int i = 0; i < valueNames.length; i++ ) {
String value = (String) session.getValue( valueNames[ i ] );

P.Kumar, Rajalakshmi Engineering COllege 675


SessionExample.java
output.println(
valueNames[ i ] + " How to Program. " + "ISBN#: " + value + "<BR>" );
}
}
else {
output.println( "<H1>No Recommendations</H1>" );
output.println( "You did not select a language" );
}

output.println( "</BODY></HTML>" );
output.close(); // close stream
}

private String getISBN( String lang )


{
for ( int i = 0; i < names.length; ++i )
if ( lang.equals( names[ i ] ) )
return isbn[ i ];

return ""; // no matching string found


}
}

P.Kumar, Rajalakshmi Engineering COllege 676


SelectLanguage.html
<HTML>
<HEAD>
<TITLE>Sessions</TITLE>
</HEAD>

<BODY>
<FORM ACTION=http://localhost:8080/servlet/SessionExample METHOD="POST">
<STRONG>Select a programming language:</STRONG><BR>
<INPUT TYPE="radio" NAME="lang" VALUE="C">C<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="C++">C++<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="Java" CHECKED> Java<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="Visual Basic 6"> Visual Basic 6
<P><INPUT TYPE="submit" VALUE="Submit">
<INPUT TYPE="reset"> </P>
</FORM>
</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 677


P.Kumar, Rajalakshmi Engineering COllege 678
Multi-Tier Applications: Using JDBC from a
Servlet
• Three-tier distributed applications
– User interface
– Business logic
– Database access
• Web servers often represent the middle tier
• Three-tier distributed application example
– Student
– Student.html
– MS Access database – student.mdb

P.Kumar, Rajalakshmi Engineering COllege 679


Multi-Tier Applications: Using JDBC from a
Servlet (Cont.)

Descriptor element Value


servlet element
servlet-name animalsurvey
description Connecting to a database from a servlet.
servlet-class com.deitel.iw3htp3.servlets.SurveyServlet
init-param
param-name databaseDriver
param-value sun.jdbc.odbc.JdbcOdbcDriver
init-param
param-name databaseName
param-value jdbc:odbc:animalsurvey
servlet-mapping element
servlet-name animalsurvey
url-pattern /animalsurvey
Fig. 36.22 Deployment descriptor information for servlet SurveyServlet.

P.Kumar, Rajalakshmi Engineering COllege 680


Displaying Student Details
Student.html
<HTML>
<BODY>
<CENTER>
<FORM name = "students" method = "post“
action="http://localhost:8080/Student/Student">
<TABLE>
<tr>
<td><B>Roll No. </B> </td>
<td><input type = "textbox" name="rollno" size="25“ value=""></td>
</tr>
</TABLE>
<INPUT type = "submit" value="Submit">
</FORM>
<CENTER>
</BODY>
</HTML>

P.Kumar, Rajalakshmi Engineering COllege 681


Displaying Student Details
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;
import java.sql.*;

public class Student extends HttpServlet {


Connection dbConn ;
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
dbConn = DriverManager.getConnection("jdbc:odbc:Student“ ,"","") ;
}
catch(ClassNotFoundException e)
{ System.out.println(e); }
catch(Exception e) P.Kumar, Rajalakshmi Engineering COllege 682

{ System.out.println(e);}
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String mrollno = req.getParameter("rollno") ;
try {
PreparedStatement ps = dbConn.prepareStatement("select * from stud
where rollno = ?") ;
ps.setString(1, mrollno) ;
ResultSet rs = ps.executeQuery() ;
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<table border = 1>");
P.Kumar, Rajalakshmi Engineering COllege 683
while(rs.next())
{
out.println("<tr><td>Roll No. : </td>");
out.println("<td>" + rs.getString(1) + "</td></tr>");
out.println("<tr><td>Name : </td>");
out.println("<td>" + rs.getString(2) +"</td></tr>");
out.println("<tr><td>Branch : </td>");
out.println("<td>" + rs.getString(3) + "</td></tr>");
out.println("<tr><td>10th Mark : </td>");
out.println("<td>" + rs.getString(4) + "</td></tr>");
out.println("<tr><td>12th Mark : </td>");
out.println("<td>" + rs.getString(5) + "</td></tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
catch (Exception e)
{ System.out.println(e); }
}
} P.Kumar, Rajalakshmi Engineering COllege 684
• Database Structure – Student.mdb

P.Kumar, Rajalakshmi Engineering COllege 685


web.xml
<?xml version="1.0" ?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN“ "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Welcome to Tomcat</display-name>
<description> Welcome to Tomcat </description>
<!-- JSPC servlet mappings start -->
<servlet>
<servlet-name>Student</servlet-name>
<servlet-class>Student</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Student</servlet-name>
<url-pattern>/Student</url-pattern>
</servlet-mapping>
<!-- JSPC servlet mappings end -->
</web-app>

P.Kumar, Rajalakshmi Engineering COllege 686


Step 1: Create ODBC connection for the database
Step 2: Open Web Browser and type
Step 3: http://localhost:8080
Step 4: Select Tomcat Manager
Step 5: Deploy the war file and Run

P.Kumar, Rajalakshmi Engineering COllege 687


JavaServer Pages (JSP)
Outline
Introduction
JavaServer Pages Overview
First JavaServer Page Example
Implicit Objects
Scripting
Scripting Components
Scripting Example
Standard Actions
<jsp:include> Action
<jsp:forward> Action
<jsp:useBean> Action
Directives
page Directive
include Directive
Case Study: Guest Book

P.Kumar, Rajalakshmi Engineering COllege 688


Introduction

• JavaServer Pages
– Extension of Servlet technology
• Web content delivery
• Reuse existing Java components
– Without programming Java
• Create custom tags
– Encapsulate complex functionality
• Classes and interfaces specific to JSP
– Package javax.servlet.jsp
– Package javax.servlet.jsp.tagext

P.Kumar, Rajalakshmi Engineering COllege 689


JavaServer Pages Overview

• Key components
– Directives
– Actions
– Scriptlets
– Tag libraries

– JavaServer Pages (JSP) technology is the Java platform


technology for delivering dynamic content to web clients in
a portable, secure and well-defined way.

P.Kumar, Rajalakshmi Engineering COllege 690


JavaServer Pages Overview (cont.)

• Directive
– Message to JSP container
• i.e., program that compiles/executes JSPs
• They are used to set global values such as class declaration,
methods to be implemented, output content type, etc.
• They do not produce any output to the client.
• The three directives
– are page - specify page settings,
– to include content from other resources and
– to specify custom tag libraries for use in a JSP.

P.Kumar, Rajalakshmi Engineering COllege 691


JavaServer Pages Overview (cont.)

• Actions
– Predefined JSP tags that encapsulate functionality
– Often performed based on information from client request
– Can be used to create Java objects for use in scriptlets

P.Kumar, Rajalakshmi Engineering COllege 692


JavaServer Pages Overview (cont.)

• Scriptlet
– Also called “Scripting Elements”
• A scriptlet consists of one or more valid Java statements.

• A scriptlet is a block of Java code that is executed at request-


processing time.

• A scriptlet is enclosed between "<%" and "%>".

P.Kumar, Rajalakshmi Engineering COllege 693


JavaServer Pages Overview (cont.)

• Custom Tag Library


– JSP’s tag extension mechanism
– Enables programmers to define new tags
• Tags encapsulate complex functionality
– Tags can manipulate JSP content

P.Kumar, Rajalakshmi Engineering COllege 694


Advantages of JSP?

• vs. Active Server Pages (ASP). ASP is a similar technology from Microsoft. The
advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS-specific language, so it is more powerful and easier to use. Second, it
is portable to other operating systems and non-Microsoft Web servers.
• vs. Pure Servlets. JSP doesn't give you anything that you couldn't in principle do with a
servlet. But it is more convenient to write (and to modify!) regular HTML than to have a
zillion println statements that generate the HTML. Plus, by separating the look from the
content you can put different people on different tasks: your Web page design experts
can build the HTML, leaving places for your servlet programmers to insert the dynamic
content.
• vs. Server-Side Includes (SSI). SSI is a widely-supported technology for including
externally-defined pieces into a static Web page. JSP is better because it lets you use
servlets instead of a separate program to generate that dynamic part. Besides, SSI is
really only intended for simple inclusions, not for "real" programs that use form data,
make database connections, and the like.
• vs. JavaScript. JavaScript can generate HTML dynamically on the client. This is a
useful capability, but only handles situations where the dynamic information is based on
the client's environment. With the exception of cookies, HTTP and form submission
data is not available to JavaScript. And, since it runs on the client, JavaScript can't
access server-side resources like databases, catalogs, pricing information, and the like.

P.Kumar, Rajalakshmi Engineering COllege 695


A First JavaServer Page Example

• Simple JSP example


– Demonstrates
• Fixed-template data (HTML markup)
• Creating a Java object (java.util.Date)
• Automatic conversion of JSP expression to a String
• meta element to refresh Web page at specified interval
– First invocation of clock.jsp
• Notice the delay while:
– JSP container translates the JSP into a servlet
– JSP container compiles the servlet
– JSP container executes the servlet
• Subsequent invocations should not experience the same delay

P.Kumar, Rajalakshmi Engineering COllege 696


clock.jsp

<html>

<head>
<meta http-equiv = "refresh" content = "60" />

<title>A Simple JSP Example</title>

</head>

<body>

<!-- JSP expression to insert date/time -->


<%= new java.util.Date() %>

</body>

</html>
P.Kumar, Rajalakshmi Engineering COllege 697
Outline

Clock.jsp

P.Kumar, Rajalakshmi Engineering COllege 698


Implicit Objects

• Implicit Objects
– Provide access to many servlet capabilities within a JSP
– Four scopes
• Application scope
– Objects owned by the container application
– Any servlet or JSP can manipulate these objects
• Page scope
– Objects that exist only in page in which they are defined
– Each page has its own instance of these objects
• Request scope
– Objects exist for duration of client request
– Objects go out of scope when response sent to client
• Session scope
– Objects exist for duration of client’s browsing session
– Objects go out of scope when client terminates session or when
session timeout occurs
P.Kumar, Rajalakshmi Engineering COllege 699
Implicit object Description
Application Scope
application This javax.servlet.ServletContext object represents the container in which the JSP
executes.
Page Scope
config This javax.servlet.ServletConfig object represents the JSP configuration options. As
with servlets, configuration options can be specified in a Web application descriptor.
exception This java.lang.Throwable object represents the exception that is passed to the JSP error
page. This object is available only in a JSP error page.
out This javax.servlet.jsp.JspWriter object writes text as part of the response to a
request. This object is used implicitly with JSP expressions and actions that insert string content
in a response.
page This java.lang.Object object represents the this reference for the current JSP instance.

pageContext This javax.servlet.jsp.PageContext object hides the implementation details of the


underlying servlet and JSP container and provides JSP programmers with access to the implicit
objects discussed in this table.
response This object represents the response to the client and is normally an instance of a class that
implements HttpServletResponse (package javax.servlet.http). If a protocol
other than HTTP is used, this object is an instance of a class that implements
javax.servlet.ServletResponse.
Request Scope
request This object represents the client request. The object normally is an instance of a class that
implements HttpServletRequest (package javax.servlet.http). If a protocol other
than HTTP is used, this object is an instance of a subclass of javax.servlet.Servlet-
Request.
Session Scope
session This javax.servlet.http.HttpSession object represents the client session
information if such a session has been created. This object is available only in pages that
participate in a session.
Fig. 37.2 JSP implicit objects.

P.Kumar, Rajalakshmi Engineering COllege 700


Scripting

• Scripting
– Dynamically generated content
– Insert Java code and logic in JSP using scripting

P.Kumar, Rajalakshmi Engineering COllege 701


Scripting Components

• JSP scripting components


– Scriptlets (delimited by <% and %>)
– Comments
• JSP comments (delimited by <%-- and --%>)
• HTML comments (delimited by <!-- and -->)
• Java’s comments (delimited by // and /* and */)
– Expressions (delimited by <%= and %>)
– Declarations (delimited by <%! And %>)
Ex: <%! int counter = 0; %>

– Escape sequences

P.Kumar, Rajalakshmi Engineering COllege 702


Scripting Components (cont.)

Literal Escape Description


sequence
<% <\% The character sequence <% normally indicates the
beginning of a scriptlet. The <\% escape sequence
places the literal characters <% in the response to the
client.
%> %\> The character sequence %> normally indicates the end
of a scriptlet. The %\> escape sequence places the
literal characters %> in the response to the client.
' \' As with string literals in a Java program, the escape
" \" sequences for characters ', " and \ allow these
\ \\ characters to appear in attribute values. Remember that
the literal text in a JSP becomes string literals in the
servlet that represents the translated JSP.

Fig. 37.3 JSP escape sequences.

P.Kumar, Rajalakshmi Engineering COllege 703


Scripting Example

• Demonstrate basic scripting capabilities


– Responding to get requests

P.Kumar, Rajalakshmi Engineering COllege 704


welcome.jsp
<!-- JSP that processes a "get" request containing data. -->

<html ><head>
<title>Processing "get" requests with data</title>
</head>
<body>
<% String name = request.getParameter( "firstName" );

if ( name != null ) { %>


<h1>
Hello <%= name %>, <br />
Welcome to JavaServer Pages!
</h1>

<% } else { %>


<form action = "welcome.jsp" method = "get">
<p>Type your first name and press Submit</p>

<p><input type = "text" name = "firstName" />


<input type = "submit" value = "Submit" />
</p>
</form>
<% } %>
</body></html>

P.Kumar, Rajalakshmi Engineering COllege 705


Outline

welcome.jsp

P.Kumar, Rajalakshmi Engineering COllege 706


Standard Actions
• JSP standard actions
– Provide access to common tasks performed in a JSP
• Including content from other resources
– <jsp:include> Dynamically includes another resource in a JSP. As the JSP executes,
the referenced resource is included and processed.

• Forwarding requests to other resources


– <jsp:forward> Forwards request processing to another JSP, servlet or static page.
– This action terminates the current JSP’s execution
– <jsp:plugin> Allows a plug-in component to be added to a page in the form of a
– browser-specific object or embed HTML element.

• Interacting with JavaBeans


<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies
the scope of the bean and assigns it an ID that scripting components can use to manipulate
the bean.

– <jsp:setProperty> Sets a property in the specified JavaBean instance.


<jsp:getProperty> Gets a property in the specified JavaBean instance and converts
the result to a string for output in the response.

– Delimited by <jsp:action> and </jsp:action>

P.Kumar, Rajalakshmi Engineering COllege 707


Standard Actions

Action Description
<jsp:include> Dynamically includes another resource in a JSP. As the JSP executes, the
referenced resource is included and processed.
<jsp:forward> Forwards request processing to another JSP, servlet or static page. This
action terminates the current JSP’s execution.
<jsp:plugin> Allows a plug-in component to be added to a page in the form of a
browser-specific object or embed HTML element. In the case of a
Java applet, this action enables the downloading and installation of the
Java Plug-in, if it is not already installed on the client computer.
<jsp:param> Used with the include, forward and plugin actions to specify
additional name/value pairs of information for use by these actions.
JavaBean Manipulation
<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies the
scope of the bean and assigns it an ID that scripting components can use
to manipulate the bean.
<jsp:setProperty> Sets a property in the specified JavaBean instance. A special feature of
this action is automatic matching of request parameters to bean properties
of the same name.
<jsp:getProperty> Gets a property in the specified JavaBean instance and converts the result
to a string for output in the response.
Fig. 37.5 JSP standard actions.

P.Kumar, Rajalakshmi Engineering COllege 708


<jsp:include> Action

• <jsp:include> action
– Enables dynamic content to be included in a JSP
– More flexible than include directive
• Requires more overhead when page contents change frequently
• banner.html, toc.html, clock.jsp, include.jsp and the images
directory into the jsp directory
• Open your Web browser and enter the following URL to test
• http://localhost:8080/jsp/include.jsp

P.Kumar, Rajalakshmi Engineering COllege 709


Banner.html

<!-- banner to include in another document -->

<p> Internet and World Wide Web Programming


</p>

P.Kumar, Rajalakshmi Engineering COllege 710


Toc.html

<!-- contents to include in another document -->

<p><a href = "http://www.rec.com/books/index.html">


Publications </a></p>

<p><a href = "http://www.rec.com/whatsnew.html">


What's New </a></p>

<p><a href = "http://www.rec.com/books/downloads.html">


Downloads/Resources </a></p>

<p><a href = "http://www.rec.com/faq/index.html">


FAQ (Frequently Asked Questions) </a></p>
P.Kumar, Rajalakshmi Engineering COllege 711
clock.jsp

<!-- clock.jsp -->

<html >
<head>
<meta http-equiv = "refresh" content = "60" />

<title>A Simple JSP Example</title>

</head>

<body>

<!-- JSP expression to insert date/time -->


<%= new java.util.Date() %>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 712
Include.jsp (Action)
<html>
<head><title>Using jsp:include</title></head>
<body>
<table>
<tr> <td>
<%-- include banner.html in this JSP --%>
<jsp:include page = "banner.html" flush = "true" /> </td> </tr>

<tr> <td >


<%-- include toc.html in this JSP --%>
<jsp:include page = "toc.html" flush = "true" /> </td>

<td>
<%-- include clock2.jsp in this JSP --%>
<jsp:include page = "clock.jsp" flush = "true" /> </td>
</tr>
</table>
</body> </html>
P.Kumar, Rajalakshmi Engineering COllege 713
Outline

P.Kumar, Rajalakshmi Engineering COllege 714


<jsp:forward> Action

• <jsp:forward> action
– Enables JSP to forward request to different resources
• Can forwarded requests only resources in same context
• <jsp:param> action
– Specifies name/value pairs of information
• Name/Value pairs are passed to other actions

Example: forward1.jsp forwards the request to


forward2.jsp

P.Kumar, Rajalakshmi Engineering COllege 715


forward1.jsp

<html>
<head> <title>Forward request to another JSP</title></head>
<body>
<% // begin scriptlet

String name = request.getParameter( "firstName" );


if ( name != null ) {
%> <%-- end scriptlet to insert fixed template data --%>

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


<jsp:param name = "date" value = "<%= new java.util.Date() %>" />
</jsp:forward>

<% // continue scriptlet

} // end if

P.Kumar, Rajalakshmi Engineering COllege 716


forward1.jsp

else {

%> <%-- end scriptlet to insert fixed template data --%>

<form action = "forward1.jsp" method = "get">


<p>Type your first name and press Submit</p>

<p><input type = "text" name = "firstName" />


<input type = "submit" value = "Submit" />
</p>
</form>
<% // continue scriptlet
} // end else

%> <%-- end scriptlet --%>


</body></html>
P.Kumar, Rajalakshmi Engineering COllege 717
Forward2.jsp

<head> <title>Processing a forwarded request</title>


</head>
<body>
<p > Hello <%= request.getParameter( "firstName" ) %>
<br />
Your request was received <br /> and forwarded at
</p>
<table>
<tr> <td><p> <%= request.getParameter( "date" ) %>
</p>
</td> </tr> </table>
</body> </html>
P.Kumar, Rajalakshmi Engineering COllege 718
Outline

P.Kumar, Rajalakshmi Engineering COllege 719


<jsp:useBean> Action

• <jsp:useBean> action
– Enables JSP to manipulate Java object
• Creates Java object or locates an existing object for use in JSP

P.Kumar, Rajalakshmi Engineering COllege 720


<jsp:useBean> Action (cont.)

Attribute Description
id The name used to manipulate the Java object with actions
<jsp:setProperty> and <jsp:getProperty>. A variable of
this name is also declared for use in JSP scripting elements. The name
specified here is case sensitive.
scope The scope in which the Java object is accessible—page, request,
session or application. The default scope is page.
class The fully qualified class name of the Java object.
beanName The name of a bean that can be used with method instantiate of
class java.beans.Beans to load a JavaBean into memory.
type The type of the JavaBean. This can be the same type as the class
attribute, a superclass of that type or an interface implemented by that
type. The default value is the same as for attribute class. A
ClassCastException occurs if the Java object is not of the type
specified with attribute type.
Fig. 37.13 Attributes of the <jsp:useBean> action.

P.Kumar, Rajalakshmi Engineering COllege 721


Rotator.java
// A JavaBean that rotates advertisements.
package com.jsp;

public class Rotator {


private String images[] = { "images/a.jpg", "images/b.jpg" };

private String links[] = {"http://www.rec.com/a.html","http://www.rec.com/b.html“ };

private int selectedIndex = 0;

// returns image file name for current ad


public String getImage()
{
return images[ selectedIndex ];
}

// returns the URL for ad's corresponding Web site


public String getLink()
{
return links[ selectedIndex ];
}

// update selectedIndex so next calls to getImage and


// getLink return a different advertisement
public void nextAd()
{
selectedIndex = ( selectedIndex + 1 ) % images.length;
}
}

P.Kumar, Rajalakshmi Engineering COllege 722


adrotator.jsp

<jsp:useBean id = "rotator" scope = "application" class = "com.jsp.Rotator" />


<html >
<head>
<title>AdRotator Example</title>

<%-- update advertisement --%>


<% rotator.nextAd(); %>
</head>

<body>
<p >AdRotator Example</p>
<p>
<% = getImage()%>
<% = getLink()%>
</p>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 723
Outline

P.Kumar, Rajalakshmi Engineering COllege 724


<jsp:useBean> Action (cont.)

Attribute Description
name The ID of the JavaBean for which a property (or properties) will be
set.
property The name of the property to set. Specifying "*" for this attribute
causes the JSP to match the request parameters to the properties of the
bean. For each request parameter that matches (i.e., the name of the
request parameter is identical to the bean’s property name), the
corresponding property in the bean is set to the value of the parameter.
If the value of the request parameter is "", the property value in the
bean remains unchanged.
param If request parameter names do not match bean property names, this
attribute can be used to specify which request parameter should be
used to obtain the value for a specific bean property. This attribute is
optional. If this attribute is omitted, the request parameter names must
match bean property names.
value The value to assign to a bean property. The value typically is the result
of a JSP expression. This attribute is particularly useful for setting
bean properties that cannot be set using request parameters. This
attribute is optional. If this attribute is omitted, the JavaBean property
must be of a type that can be set using request parameters.
Fig. 37.16 Attributes of the <jsp:setProperty> action.

P.Kumar, Rajalakshmi Engineering COllege 725


Directives

• JSP directives
– Messages to JSP container
– Enable programmer to:
• Specify page settings
• Include content from other resources
• Specify custom-tag libraries
– Delimited by <%@ and %>

P.Kumar, Rajalakshmi Engineering COllege 726


Directives (cont.)
Directive Description
page Defines page settings for the JSP container to
process.
include Causes the JSP container to perform a translation-
time insertion of another resource’s content. As the
JSP is translated into a servlet and compiled, the
referenced file replaces the include directive and
is translated as if it were originally part of the JSP.
taglib Allows programmers to define new tags in the form
of tag libraries, which can be used to encapsulate
functionality and simplify the coding of a JSP.
Fig. 37.17 JSP directives.

P.Kumar, Rajalakshmi Engineering COllege 727


page Directive

• JSP page directive


– Specifies JSP’s global settings in JSP container

Attribute Description
language The scripting language used in the JSP. Currently, the only valid value
for this attribute is java.
extends Specifies the class from which the translated JSP will be inherited. This
attribute must be a fully qualified class name.
import Specifies a comma-separated list of fully qualified type names and/or
packages that will be used in the current JSP. When the scripting
language is java, the default import list is java.lang.*,
javax.servlet.*, javax.servlet.jsp.* and
javax.servlet.http.*. If multiple import properties are
specified, the package names are placed in a list by the container.
session Specifies whether the page participates in a session. The values for this
attribute are true (participates in a session—the default) or false
(does not participate in a session). When the page is part of a session,
implicit object session is available for use in the page. Otherwise,
session is not available, and using session in the scripting code
results in a translation-time error.
Fig. 37.18 Attributes of the page directive.
P.Kumar, Rajalakshmi Engineering COllege 728
page Directive (cont.)
Attribute Description
buffer Specifies the size of the output buffer used with the implicit object out. The
value of this attribute can be none for no buffering, or a value such as 8kb
(the default buffer size). The JSP specification indicates that the buffer used
must be at least the size specified.
autoFlush When set to true (the default), this attribute indicates that the output buffer
used with implicit object out should be flushed automatically when the
buffer fills. If set to false, an exception occurs if the buffer overflows.
This attribute’s value must be true if the buffer attribute is set to none.
isThreadSafe Specifies if the page is thread safe. If true (the default), the page is
considered to be thread safe, and it can process multiple requests at the same
time. If false, the servlet that represents the page implements interface
java.lang.SingleThreadModel and only one request can be
processed by that JSP at a time. The JSP standard allows multiple instances
of a JSP to exists for JSPs that are not thread safe. This enables the container
to handle requests more efficiently. However, this does not guarantee that
resources shared across JSP instances are accessed in a thread-safe manner.
info Specifies an information string that describes the page. This string is returned
by the getServletInfo method of the servlet that represents the
translated JSP. This method can be invoked through the JSP’s implicit page
object.
Fig. 37.18 Attributes of the page directive.
P.Kumar, Rajalakshmi Engineering COllege 729
page Directive (cont.)

Attribute Description
errorPage Any exceptions in the current page that are not caught
are sent to the error page for processing. The error page
implicit object exception references the original
exception.
isErrorPage Specifies if the current page is an error page that will be
invoked in response to an error on another page. If the
attribute value is true, the implicit object exception
is created and references the original exception that
occurred. If false (the default), any use of the
exception object in the page results in a translation-
time error.
contentType Specifies the MIME type of the data in the response to
the client. The default type is text/html.
Fig. 37.18 Attributes of the page directive.

P.Kumar, Rajalakshmi Engineering COllege 730


include Directive

• JSP include directive


– Includes content of another resource at JSP translation time
• Not as flexible as <jsp:include> action
– The include directive has only one attribute—file—that specifies
the URL of the page to include.
– The difference between directive include and action
<jsp:include> only if the included content changes.
– For example, if the definition of an HTML document changes
after it is included with directive include, future invocations of
the JSP will show the original content of the HTML document,
not the new content.
– In contrast, action <jsp:include> is processed in each request to
the JSP. Therefore, changes to included content would be
apparent in the next request to the JSP that uses action
<jsp:include>.
P.Kumar, Rajalakshmi Engineering COllege 731
includeDirective.jsp

<html >
<head> <title>Using the include directive</title></head>

<body>
<table> <tr>
<td > <img src = "images/logo.jpg" width = "140" height = "93" alt = “rec " /> </td>

<td>
<%-- include banner.html in this JSP --%>
<%@ include file = "banner.html" %> </td> </tr>

<tr> <td >


<%-- include toc.html in this JSP --%>
<%@ include file = "toc.html" %> </td>

<td >
<%-- include clock2.jsp in this JSP --%>
<%@ include file = "clock2.jsp" %>
</td> </tr> </table>
</body>
</html> P.Kumar, Rajalakshmi Engineering COllege 732
Tag Libraries

• Custom tag libraries define one or more custom


tags that JSP implementors can use to create
dynamic content.

P.Kumar, Rajalakshmi Engineering COllege 733


customTagWelcome.jsp

<!-- JSP that uses a custom tag to output content. -->


<%-- taglib directive --%>
<%@ taglib uri = "adv-taglib.tld" prefix = "adv" %>

<html> <head> <title>Simple Custom Tag


Example</title> </head>
<body>
<p>The following text demonstrates a custom tag:</p>
<h1> <adv:welcome /></h1>
</body>
</html>

P.Kumar, Rajalakshmi Engineering COllege 734


WelcomeTagHandler.java
Custom tag handler that handles a simple tag.
package com.deitel.adv.jsp.taglibrary;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class WelcomeTagHandler extends TagSupport {

// Method called to begin tag processing


public int doStartTag() throws JspException
{
// attempt tag processing
try {
// obtain JspWriter to output content
JspWriter out = pageContext.getOut();

// output content
out.print( "Welcome to JSP Tag Libraries!" );
}

// rethrow IOException to JSP container as JspException


catch( IOException ioException ) {
throw new JspException( ioException.getMessage() );
}

return SKIP_BODY; // ignore the tag's body


}
}

P.Kumar, Rajalakshmi Engineering COllege 735


Case Study: Guest Book

Demonstrate
• Enables users to place their first name, last name
and e-mail address into a guest book database.
• After submitting their information, users see a
Web page containing all the users in the guest
book. Each person’s e-mail address is displayed
as a hyperlink that allows the user to send an e-
mail message to the person.

P.Kumar, Rajalakshmi Engineering COllege 736


• GuestBean.java - JavaBean to store data for a guest in
the guest book.
• GuestDataBean.java - Class GuestDataBean makes a
database connection and supports - inserting and
retrieving data from the database.
• JSPs guestBookLogin.jsp
• guestBookView.jsp

• The example demonstrates action <jsp:setProperty>. In


addition, the example introduces the JSP page directive.
– Action <jsp:setProperty>
– JSP page directive
– Use of JDBC
P.Kumar, Rajalakshmi Engineering COllege 737
GuestBean.java
JavaBean to store data for a guest in the
guestbook
.package com.jsp.beans;

public class GuestBean {


private String firstName, lastName, email;

public void setFirstName( String name ) // set the guest's first name
{
firstName = name;
}
public String getFirstName() // get the guest's first name
{
return firstName;
}
public void setLastName( String name ) // set the guest's last name
{
lastName = name;
}
public String getLastName() // get the guest's last name
{
return lastName;
}
public void setEmail( String address ) // set the guest's email address
{
email = address;
}
public String getEmail() // get the guest's email address

{
return email; P.Kumar, Rajalakshmi Engineering COllege 738
}
}
GuestDataBean.java
Class GuestDataBean makes a database connection and
supports
inserting and retrieving data from the database.
// package com.jsp.beans;
import java.io.*;
import java.sql.*;
import java.util.*;

public class GuestDataBean {


private Connection conn;
private Statement st;
// construct TitlesBean object
public GuestDataBean() throws Exception
{
// load the Cloudscape driver
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );

// connect to the database


conn = DriverManager.getConnection("jdbc:odbc:guestbook" );
st= connection.createStatement();
} // return an ArrayList of GuestBeans

P.Kumar, Rajalakshmi Engineering COllege 739


GuestDataBean.java

public List getGuestList() throws SQLException


{
List guestList = new ArrayList();

// obtain list of titles


ResultSet results = statement.executeQuery(
"SELECT firstName, lastName, email FROM guests" );

// get row data


while ( results.next() ) {
GuestBean guest = new GuestBean();

guest.setFirstName( results.getString( 1 ) );
guest.setLastName( results.getString( 2 ) );
guest.setEmail( results.getString( 3 ) );

guestList.add( guest );
}

return guestList;
}
P.Kumar, Rajalakshmi Engineering COllege 740
GuestDataBean.java

// insert a guest in guestbook database

public void addGuest( GuestBean guest ) throws SQLException


{
statement.executeUpdate( "INSERT INTO guests ( firstName, " +
"lastName, email ) VALUES ( '" + guest.getFirstName() + "', '" +
guest.getLastName() + "', '" + guest.getEmail() + "' )" );
}

// close statements and terminate database connection


protected void finalize()
{
// attempt to close database connection
try {
st.close();
conn.close();
}

// process SQLException on close operation


catch ( SQLException sqlException ) {
sqlException.printStackTrace();
}
}
}
P.Kumar, Rajalakshmi Engineering COllege 741
guestBookLogin.jsp

<%-- beans used in this JSP --%>


<jsp:useBean id = "guest" scope = "page"
class = "com.jsp.beans.GuestBean" />
<jsp:useBean id = "guestData" scope = "request"
class = "com.jsp.beans.GuestDataBean" />

<html >
<head>
<title>Guest Book Login</title>
</head>
P.Kumar, Rajalakshmi Engineering COllege 742
guestBookLogin.jsp
<body>
<jsp:setProperty name = "guest" property = "*" />

<% // start scriptlet

if ( guest.getFirstName() == null || guest.getLastName() == null || guest.getEmail() == null ) {

%> <%-- end scriptlet to insert fixed template data --%>

<form method = "post" action = "guestBookLogin.jsp">

<p>Enter your first name, last name and email address to register in our guest book.</p>

<table>
<tr>
<td>First name</td>

<td>
<input type = "text" name = "firstName" />
</td>
</tr>

P.Kumar, Rajalakshmi Engineering COllege 743


guestBookLogin.jsp
<tr>
<td>Last name</td>

<td> <input type = "text" name = "lastName" /> </td> </tr>

<tr> <td>Email</td>
<td> <input type = "text" name = "email" /> </td> </tr>

<tr> <td colspan = "2">


<input type = "submit" value = "Submit" /> /td> </tr>
</table> </form>
<% // continue scriptlet
} // end if
else { guestData.addGuest( guest ); %>
<%-- end scriptlet to insert jsp:forward action --%>
<%-- forward to display guest book contents --%>
<jsp:forward page = "guestBookView.jsp" />

<% // continue scriptlet

} // end else %> <%-- end scriptlet --%>


</body>

</html>
P.Kumar, Rajalakshmi Engineering COllege 744
guestBookView.jsp

<%-- page settings --%>


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

<%-- GuestDataBean to obtain guest list --%>


<jsp:useBean id = "guestData" scope = "request"
class = "com.jsp.beans.GuestDataBean" />
<html >
<head>
<title>Guest List</title>
</head>
P.Kumar, Rajalakshmi Engineering COllege 745
guestBookView.jsp
<body>
<p>Guest List</p>

<table>
<thead> <tr>
<th>Last name</th>
<th>First name</th>
<th>Email</th>
</tr> </thead> <tbody>

<% // start scriptlet

List guestList = guestData.getGuestList();


Iterator guestListIterator = guestList.iterator();
GuestBean guest;

while ( guestListIterator.hasNext() ) {
guest = ( GuestBean ) guestListIterator.next();

%> <%-- end scriptlet; insert fixed template data --%>

P.Kumar, Rajalakshmi Engineering COllege 746


guestBookView.jsp
<tr>
<td><%= guest.getLastName() %></td>

<td><%= guest.getFirstName() %></td>

<td>
<a href = "mailto:<%= guest.getEmail() %>">
<%= guest.getEmail() %></a>
</td> </tr>

<% // continue scriptlet

} // end while

%> <%-- end scriptlet --%>

</tbody> </table>
</body>
</html> P.Kumar, Rajalakshmi Engineering COllege 747
Case Study: Guest Book (Cont.)

P.Kumar, Rajalakshmi Engineering COllege 748


Case Study: Guest Book (Cont.)

P.Kumar, Rajalakshmi Engineering COllege 749


P.Kumar, Rajalakshmi Engineering COllege 750
Steps to Install
&
Deploy in Tomcat Server

P.Kumar, Rajalakshmi Engineering COllege 751


Steps to Install and Deploy in Tomcat Server

1. Select the Install file and double click.

2. Click Next to Continue.

P.Kumar, Rajalakshmi Engineering COllege 752


3. Click I Agree.

4. Check all the option and click Next.

P.Kumar, Rajalakshmi Engineering COllege 753


5. Delete the default path and type D:\tomcat.

P.Kumar, Rajalakshmi Engineering COllege 754


6. Type the admin password.

7. Select the path of the JVM.

P.Kumar, Rajalakshmi Engineering COllege 755


8. The system displays the installation progress.

9. Make check for Run Apache Tomcat and Show and uncheck Show Readme.

P.Kumar, Rajalakshmi Engineering COllege 756


10. The system display the following screen.

11. Open the Internet Explorer and type http://localhost:8080/

P.Kumar, Rajalakshmi Engineering COllege 757


12. Create the necessary Java for Servlet, HTML and MDB files and store in a directory.

13. Compile the Java file.

14. Create a folder WEB-INF under your folder.

15. Create a folder named CLASSES under Web-INF folder and copy all your .class files.

16. Copy the WEB.XML file from d:\tomcat\webapps\ROOT\WEB-INF folder to your WEB-
INF folder. Edit the servlet-name, servlet-class in servlet tag and also servlet-name, url-
pattern in servlet-mapping.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>

<!-- JSPC servlet mappings start -->

<servlet>
<servlet-name>Banking</servlet-name>
<servlet-class>Banking</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Banking</servlet-name>
<url-pattern>/Banking</url-pattern>
</servlet-mapping>

<!-- JSPC servlet mappings end -->

</web-app>

17. Create a war file by using the following syntax:

D:\Student:>jar –cvf Banking.war .

P.Kumar, Rajalakshmi Engineering COllege 758


18. Open the tomcat home and select Tomcat Manager. Type the password and click Ok.

19. The system opens the following screen.

P.Kumar, Rajalakshmi Engineering COllege 759


20. Go to the WAR file to deploy option and select Browse.

21. Select your war file and click Open.

P.Kumar, Rajalakshmi Engineering COllege 760


22. Click the Deploy button.

23. After successful deployment you will get a screen like as below:

P.Kumar, Rajalakshmi Engineering COllege 761


24. Open the browser by typing the URL as http://localhost:8080/Banking.

P.Kumar, Rajalakshmi Engineering COllege 762