Web Technologies Unit 1-5 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 139

PG & RESEARCH DEPARTMENT OF COMPUTER SCIENCE

WEB TECHNOLOGIES

CLASS III B.Sc COMPUTER SCIENCE


PAPER NAME WEB TECHNOLOGLES
PAPER CODE 17UCSE06
B.Sc. COMPUTER SCIENCE
SEMESTER VI
ELECTIVE II - PAPER III - WEB TECHNOLOGIES

UNIT-I

Internet Principles: Introduction to Internet - Client Server Model- Protocol - Internet IP Address-
Domain Name - Internet Services - Electronic Mail - World Wide Web - Internet Security - E-
Commerce- EDI.

UNIT –II

Introduction to HTML: HTML Tags - HTML Documents - Headings - Hyperlinks using Anchor
Tag- Formatting Characters - Font - Images and Pictures - Listing - Tables in HTML Tags –
Frameset Definition - Fame Definition- Nested framesets - HTML Forms - Elements of a form use
Tags.

UNIT –III

JavaScript : Data Types - Variables - Operators - Conditional statements using Javascript –


Document Objects - Image Objects using Javascript - Forms and Elements - Event Handling -
Browser Object - Submit Event and Data Validation -Parseint() Function - ParseFloat() Function -
Recursive Function.

UNIT-IV

Server Side Script with JSP: Client Responsibilities -Server Responsibilities - Introduction to JSP –
JSP Architecture - JSP Servers - JSP Tags - Request Object - Response Object - JSP Page.

UNIT – V

JSP with JDBC: Creating ODBC Data Source Name - Introduction to JDBC -Telephone Directory
with JDBC - Servlet Environment and Role - Protocol Support - HTML Support - Servelt Life
Cycle -HTML to Servlet Communication.

TEXT BOOK
C.Xavier, "Web Technology and Design", 1st Edition, New Age International, 2011.
REFERENCE BOOK
1. H.M.Deitel, P.J.Deitel, "Internet and World Wide Web - How to Program", 3rd Edition, Pearson
Publication, 2006.
UNIT-I
Internet Principles: Introduction to Internet - Client
Server Model- Protocol - Internet IP Address-Domain
Name - Internet Services - Electronic Mail - World
Wide Web - Internet Security - E-Commerce- EDI.

Internet Principles
 In 1984 William Gibson in his scifinovel Neuromancer coined the term Cyberspace. It
refers to the nonphysical terrain created by computer systems.
 Online systems, for example, create a cyberspace within which people can communicate
with one another (via email), do research, or simply window shop.
 Like physical space, cyberspace contains objects (files, mail messages, graphics, etc.) and
different modes of transportation and delivery.
 Unlike real space, exploring cyberspace does not require any physical movement other
than pressing keys on a keyboard or moving a mouse.
 Some programs, particularly computer games, are designed to create a special
cyberspace, one that resembles physical reality in some ways but defies it in others.
 In its extreme form, called virtual reality, users are presented with visual, auditory, and
even tactile feedback that makes cyberspace feel real.
 The dreams of William Gibson is becoming a reality in the Internet world.

1.1 Introduction to Internet


 A network of computers refers to a group of computers connected with each other as per a
topology. The computers in a network are capable of sharing the resources among
themselves, the resources such as memory, peripherals, etc.
 They communicate with each other in a defined way.
 Internet refers to a global network connecting millions of computers.
 More than 100 countries are linked into exchanges of data, news and opinions.
 Unlike online network services, which are centrally controlled, the Internet is
decentralized by design. Each Internet computer, called a host, is independent.
 Its operators can choose which Internet services to use and which local services to make
available to the global Internet community.
 Remarkably, this anarchy by design works exceedingly well.
 There are a variety of ways to access the Internet.
 Most of the Internet users gain access through a commercial internet Service Provider
(ISP) as illustrated in Figure LI.
 Usually we connect our Home PC to the Internet through the landline telephone
connection
twork

Figure 1.1 Connecting through

Using a device called modem as shown in Figure 1.2. So, through rooting two factors decide the
characteristics of the Internet services.
■ Modem
■ Connectivity for communication

Internet User

1.1.1 Modem

 Short for modulator-demodulator. A modem is a device or program that enables a computer to transmit
data over, for example, telephone or cable lines.
 Computer information is stored digitally, whereas information transmitted over telephone lines is
transmitted in the form of analog wave.
 Fortunately, there is one standard interface for connecting external modems to computers called
RS 232.
 Consequently, any external modem can be attached to any computer that has an RS 232 port,
which almost all personal computers have.
 There are also modems that come as an expansion board that you can insert into a vacant
expansion slot.
 These are sometimes called onboard or internal modems.
 While the modem interfaces are standardized, a number of different protocols for formatting data
to be transmitted over telephone lines exist.
 Some, like CC1TT V.34, are official standards, while others have been developed by private
companies.
 Most modems have built in support for the more common protocols—at slow data transmission
speeds at least, most modems can communicate with each other.
 At high transmission speeds, however, the protocols are less standardized.

Characteristics of a Modem
Aside from the transmission protocols that they support, the following characteristics distinguish one
modem from another:

1. Speed of transmission
 At slow rales, modems are measured in terms of baud rates.
 The slowest rate is 300 baud (about 25 characters per second—cps).
 At higher speeds, modems are measured in terms of bits per second (bps).
 A fast modem transmits at 57,600 bps, although they can achieve even higher data
transfer rates by compressing the data.
 Obviously, the faster the transmission rate, the faster you can send and receive data.
 Note, however, that you cannot receive data any faster than it is being sent.
 If, for example, the device sending data to your computer is sending it at 2,400 bps, you
must receive it at 2.400 bps.
 It does not always pay, therefore, to have a very fast modem. In addition, some
telephone lines are unable to transmit data reliably at very high rates.

2. Modes supported
 Many modems support a switch to change between voice and data modes.
 In data mode, the modem acts like a regular modem.
 In voice mode, the modem acts like a regular telephone.
 Modems that support a voice/data switch have a built in loudspeaker and microphone for voice
communication.

3. Auto-answer
 An auto-answer modem enables your computer to receive calls in your absence.
 This is only necessary if you are offering some type of computer service that people can call in
to use.
4. Data compression
 Some modems perform data compression, which enables them to send data at faster rates.
 However the modem at the receiving end must be able to decompress the data using the same
compression technique.
5. Flash memory
 Some modems come with flash memory rather than conventional ROM.
 Which means that the communication protocols can be easily updated if necessary.
6. Fax capability
 Most modern modems are fax modems, which means that they can send and receive faxes.

1.1.2 Connectivity for Communication


 Connectivity is considered to be the backbone of the Internet world.
 Apart from ordinary telephone line we are also using broad band connectivity such as ISDN
connections.

1.1.3 Standards of Data Communication


 The CCITT (Comitf Consultatif International Telephoniqueet Telegraphique ) is an organization
that sets international communications standards.
 It has developed the X.400 standard, which attempts to provide a universal way of addressing
messages.
 To date, though, the de facto addressing standard is the one used by the Internet system because
almost all e-mail systems have an Internet gateway.

CCITT has defined many important standards for data communications, including the
following:

 Group 3: The universal protocol for sending fax documents across telephone lines. The Group 3
protocol specifies CCITT T.4 data compression and a maximum transmission rate of 9,600
baud. There are two levels of resolution: 203 by 98 and 203 by 196.
 Group 4: A protocol for sending fax documents over ISDN networks. The Group 400 protocol
supports images of up to 400 dpi (dots per inch) resolution.
 V.21: The standard for full-duplex communication at 300 baud in Japan and Europe. In the
United States, Bell 103 is used in place of V.21.
 V.22: The standard for half-duplex communication at 1,200 bps in Japan and Europe. In the
United States, the protocol defined by Bell 212A is more common.
 V.22bis: The worldwide standard for full-duplex modems sending and receiving data across
telephone lines at 1,200 or 2,400 bps.
 V.29: The standard for half-duplex modems sending and receiving data across telephone lines at
1,200, 2,400, 4,800 or 9,600 bps. This is the protocol used by fax modems.
 V32: The standard for full-duplex modems sending and receiving data across phone lines at
4,800 or 9,600 bps. V.32 modems automatically adjust their transmission speeds based on the
quality of the lines.
 V32bis: The V.32 protocol extended to speeds of 7,200, 12,000, and 14,400 bps.
 V34: The standard for full-duplex modems sending and receiving data across phone lines at up to
28,800 bps. V.34 modems automatically adjust their transmission speeds based on the quality of
the lines.
 V.42: An error-detection standard for high-speed modems. V.42 can be used with digital
telephone networks. See MNP for a competing standard.
 V.42bis: A data compression protocol that can enable modems to achieve a data transfer rate of
34.000 bps.
 V.90: The standard for full-duplex modems sending and receiving data across phone lines at up
to 56.600 bps.
 X.25: The most popular packet-switching protocol for WANs.
 X.400: The universal protocol for e-mail. X.400 defines the envelope for e-mail messages so all
messages conform to a standard format.
 X.500: An extension to X.400 that defines addressing formats so all e-mail systems can be linked
together.

1.1.4 ISDN Connections


 ISDN is the abbreviation of integrated services digital network, an international communications
standard for sending voice, video, and data over digital telephone lines or normal telephone
wires.
 ISDN supports data transfer rates of 64 Kbps (64,000 bits per second).
 Typically an ISDN connection has some Bearer-channels (B-channel) which are the main data
channel and some Delta-channels (D-channel ), the channel that carries control and signaling
information
There are two types of ISDN as shown in Table 1.1.1.

 Basic Rate (BRI) ISDN that consists of two 64Kbps B-channels and one D-channel for
transmitting control information.

 Primary Rate ISDN. In the United States of America and a few other countries this type of
ISDN consists of 23 B-channels and one D-channel. In the Europe these have 30 B-channels
and one D-channel.
 The original version of ISDN employs baseband transmission. Another version, called BISDN,
uses broadband transmission and is able to support transmission rates of 1.5 MBPS.
 BISDN requires fiber optic cables and is not widely available at present. The baseband and
broadband transmission are discussed.

1.1.5 DSL (Digital Subscriber Lines) Connection


 DSL is the acronym for Digital Subscriber Lines. DSL technologies use sophisticated
modulation schemes to pack data onto copper wires.
 They are sometimes referred to as last mile technologies because they are used only for
connections from a telephone switching station to a home or office, not between switching
stations.
 DSL is similar to ISDN in as much as both operate over existing copper telephone lines and
both require the short runs to a central telephone office (usually less than 20,000 feet).
 However, DSL offers much higher speeds-up to 32 Mbps for upstream traffic (client to
server), and from 32 Kbps to over 1 Mbps for downstream traffic (server to client).
There two main categories being
 Asymmetric digital subscriber line (ADSL)
 Symmetric digital subscriber line (SDSL)
Depending upon the speed some also classify as follows:
 High data rate DSL (HDSL)
 Very high DSL (VDSL).

Asymmetric Digital Subscriber Line (ADSL)


 Asymmetric digital subscriber line is a new technology that allows more data to be sent over
existing copper telephone lines.
 ADSL supports data transfer downstream rate from 1.5 to 9 Mbps and upstream rate from 16
to 640 Kbps. ADSL requires a special ADSL modem.
 ADSL is growing in popularity as more areas around the world gain access to Internet.

Symmetric Digital Subscriber Line (SDSL)


 Symmetric digital subscriber line is a technology that allows more data to be sent over
existing copper telephone lines.
 SDSL supports data rates up to 3 Mbps.
 SDSL works by sending digital pulses in the high frequency area of telephone wires.
 Since these high frequencies are not used by normal voice communications, SDSL can
operate simultaneously with voice connections over the same wires.
 SDSL requires a special SDSL modem. SDSL is called symmetric because it supports the
same data rates for upstream and downstream traffic.
 ADSL is more popular in North America, whereas SDSL is being developed primarily in
Europe. A comparison of ADSL and SDSL is shown in Table 1.1.2
1.1.6 Broadband and Baseband Transmissions
 Broadband transmission is a type of data transmission in which a single medium (wire) can
carry several channels at once. Cable TV, for example, uses broadband transmission. In
contrast, baseband transmission allows only one signal at a time.
 Most communications between computers, including the majority of local area networks use
only baseband communications. An exception is B 1SDN network, which employ broadband
transmission.

1.2 Client Server Model


 Internet works in a client server model.
 This section throws some light on the servers that are used in the marketplace today.
 Server Platforms refers to the operating system that drives the server.

1.2.1 Application Servers


 Application Servers are the type of middleware, which occupy a large chunk of computing
territory between database servers and the end user, and they often connect the two.

1.2.2 Audio/Video Servers


 Audio/Video Servers bring multimedia capabilities to Web sites by enabling them to
broadcast streaming multimedia content.

1.2.3 Chat Servers


 Chat Servers enable a large number of users to exchange information in an environment
similar to Internet newsgroups that offer real time discussion capabilities.

1.2.4 Fax Servers


 Fax Servers are ideal solution for organizations looking to reduce incoming and outgoing
telephone resources but that need to fax actual documents.
1.2.5 FTP Servers
 FTP Servers serve one of the oldest Internet services.
 It makes it possible to move one or more files securely between computers while providing
file security and organization as well as transfer control.

1.2.6 Groupware Servers


 A groupware server is a software designed to enable users to collaborate, regardless of
location, via the Internet or a corporate intranet and to work together in a virtual atmosphere.

1.2.7 IRC Servers


 IRC Servers provide an option for those seeking real time discussion capabilities, Internet
Relay Chat consists of various separate networks (or “nets”) of servers that allow users to
connect to each other via an IRC network.

1.2.8 List Servers


 List servers offer a way to better manage mailing lists, whether they be interactive
discussions open to the public or one way lists that deliver announcements, newsletters, or
advertising.

1.2.9 Mail Servers


 Mail servers move and store mail over corporate networks (via LANs and WANs) and across
the Internet.
1.2.10 News Servers
 News servers act as a distribution and delivery source for the thousands of public news
groups currently accessible over the USENET news network.
1.2.11 Proxy Servers
 Proxy servers sit between a client program (typically a Web browser) and an external server
(typically another server on the Web) to filter requests, improve performance, and share
connections.
1.2.12 Web Servers
 A web server is a computer system (Hardware and software) that delivers (serves up) Web
pages. Every Web server has an IP address and possibly a domain name.
 For example, if you enter the URL http://www.stxaviers.com/index.html in your browser, this
sends a request to the server whose domain name is stxavier.com.
 The server then fetches the page named index.html and sends it to your browser.
 Any computer can be turned into a Web server by installing server software and connecting the
machine to the Internet.
 There are many Web server software applications, including public domain software from
NCSA and Apache, and commercial packages from Microsoft, Netscape and others.

1.3 Protocol
 A protocol is a program written as per mutually accepted standard that two computers use to
communicate with each other.
 Computers use protocols (protocol programs) to format consistently their messages so that
other computers can understand them, acknowledge the receipt of messages, indicate that
they are finished sending a message and so on.
 In the network when one computer requests for the service of another, it is called a client.
 In order to establish the needed connectivity, both the client machine and the server machine
must have a common protocol program. This is illustrated in Figure 1.3.

Client Machine Server Machine


Figure 1.3 The Client Server Communication

In short a protocol is an agreed upon format for transmitting data between two devices.

The protocol determines the following:


 the type of error checking to be used
 data compression method, if any
 how the sending device will indicate that it has finished sending a message
 how the receiving device will indicate that it has received a message
 There are a variety of standard protocols from which programmers can choose.
 Each has particular advantages and disadvantages; for example, some are simpler than others,
some are more reliable, and some are faster.
 From a user’s point of view, the only interesting aspect about protocols is that your computer or
device must support the right ones if you want to communicate with other computers.
 The protocol can be implemented either in hardware or in software.

Some standard protocols used in networks are listed below:


1. Simple Mail Transfer Protocol (SMTP)
2. Post Office Protocol version 3 (POP3)
3. Point to point Protocol/Serial Line Interface Protocol (POP/SL1P)
4. Transmission Control Protocol/Intemet Protocol (TCP/IP)
5. Hyper Text Transfer Protocol (HTTP)
6. File Transfer Protocol (FTP)
7. Internet Mail Access Protocol (IMAP)
8. Internet Relay Chat (IRC)
9. Network News Transfer Protocol (NNTP)
10. Telnet
11. Gopher
12. Lightweight Directory Access Protocol (LDAP)

1.3.1 Simple Mail Transfer Protocol


 Simple Mail Transfer Protocol is used for sending e-mail messages between servers.
 Most e-mail systems that send mail over the Internet use SMTP to send messages from one
server to another; the messages can then be retrieved with an e-mail client using either POP or
IMAP.
 In addition, SMTP is generally used to send messages from a mail client to a mail server.
 This is why you need to specify both the POP or IMAP server and the SMTP server when you
configure your e-mail application.

1.3.2 Post Office Protocol (POP)


 Post Office Protocol is a protocol used to retrieve email from a mail server.
 Most email applications (e mail client) use the POP protocol, although some can use the newer
protocol such as IMAP (Internet Message Access Protocol).
 There are two versions of POP. The first, called POP2, became a standard in the mid­80’s and
requires SMTP to send messages. The newer version, POP3, can be used with or without SMTP.
1.3.3 TCP/IP on the Internet
 TCP/IP is the widely accepted protocol used in the networks.
 It is a protocol suite that consists of several protocols including two primary protocols.
 Transmission Control Protocol (TCP) and Internet Protocol (IP).
 The TCP/IP Protocol (protocol program) works asynchronously to handle multiple message
traffic simultaneously from multiple sources to multiple destinations as shown in Figure 1.4.
TCP (TCP Protocol program) handles the data integrity.
 It makes sure data gets to the destination without errors.
 TCP is also responsible for disassembling and assembling the data.
 It divides large messages into smaller packets of at the most 15 KB size.
 Each of this packet is called a segment.
 TCP numbers these segments and hands over to the IP. IP is the Protocol (protocol program) that
controls how data moves around on the network.
 After TCP divides the message into segment, IP labels them with source and destination. These
packets are now called IP Datagrams.
 IP also takes care of sending the datagrams by determining the route. These datagrams may hop
several networks before reaching the destination.

Source Computer Destination Computer


Figure 1.4 TCP/IP Communication

 At the destination the IP verifies the labels and passes them to the TCP.
 The TCP (at the destination) checks if all the segments have been received.
 If any of the segments are missing it informs this to the source TCP and requests the segment to
be sent again. It is called retry.
 After verification, the TCP assembles the message from these data segments and supplies to the
destination program
Packet Switching (Routing)
 Routing (Packet Switching) refers to the job of transferring the data packets (IP datagrams) to an
appropriate computer.
 A special computer that does routing is called router.
 We have already seen that Internet is a network of networks.
 So when a packet of data (IP datagram) starts from a computer, it is submitted to the router of
the network to which the computer belongs to.
 The router verifies the IP address of the destination.
 The destination network may not be directly reached.
 The router finds the next network to which the datagram must be submitted and does it.
 Similarly the datagram passes several routers and finally reaches the final destination network.
 Every router uses routing tables and routing algorithms to accomplish the job.
 The routing algorithm will choose the next network to which the datagram may be routed
depending upon the data traffic and the shortest route.
 Datagrams of the same message may travel through different routes to reach the final
destination.
 But finally the TCP protocol takes care of verifying if all the datagrams have reached. For
example, suppose a Computer Cl in network A wants to communicate with a Computer C2 in
network F as shown in Figure 1.5.

 When a message has to be sent from A to F, the message is disassembled into IP datagrams.
 Some datagrams may travel in the path C1ACDFC2 whereas some may travel through Cl
ABEFC2. However, C2 verifies if all the datagrams have reached.
 Then it assembles the message and supplies to the application program in C2.

Tracing the Route (Traced Command)


 In Windows or Windows NT when we are connected to Internet we can see the route from our
computer to any Internet host.
 This is got by the tracert command in command prompt.
 In Windows NT, first open the DOS emd prompt by running emd command.
 In the DOS emd prompt type

tracert<domain>
For example, we can type tracert lsu.edu
Router
 A router is a special computer that manages the traffic from network to network. The router
determines the path of travel for a datagram in TCP/IP.
 Routers keep track of the next computer to which the datagram has to hop.
 They use routing tables and routing algorithms to do routing.
 In Windows NT. we can see the IP address of the router in our network by running the
WINIPCFG.EXE program.
 When we run the program click more info and then select PPP Adapter in the dropdown list.
 In the middle of the dialog box the IP address of the router is shown in the field Default
Gateway.
 This is the IP address of the router to which your computer will send a TCP/IP datagram when it
is addressed to a computer that is not on your local network. This is illustrated in Figure 1.6.

1.3.4 HyperText Transfer Protocol (HTTP )


 HyperText Transfer Protocol is the underlying protocol used by the World Wide Web.
 HTTP defines how messages are formatted and transmitted, and what action Web servers and
browsers should take in response to various commands.
 For example, when you enter a URL in your browser, this actually sends an HTTP command to
the Web server directing it to fetch and transmit the requested Web page.
 The other main standard that controls how the World Wide Web works is HTML, which covers
how Web pages are formatted and displayed.
 HTTP is called a stateless protocol because each command is executed independently, without
any knowledge of the commands that came before it.
 This is the main reason that it is difficult to implement Web sites that react intelligently to user
input. This shortcoming of HTTP is being addressed in a number of new technologies, including
ActiveX, Java, JavaScript and cookies.
1.3.5 File Transfer Protocol (FTP)
 File Transfer Protocol or FTP, is a protocol used to upload files from a workstation to a FTP
server or download files from a FTP server to a workstation.
 It is the way that files get transferred from one device to another in order for the files to be
available on the Internet.
 When ftp appears in a URL it means that the user is connecting to a file server and not a Web
server and that some form of file transfer is going to take place.
 Most FT P servers require the user to log on to the server in order to transfer files.
 In contrast. Hyper Text Transfer Protocol, or HTTP, is a protocol used to transfer files from a
Web server onto a browser in order to view a Web page that is on the Internet, Unlike FTP.
 Where entire files are transferred from one device to another and copied into memory, HTTP
only transfers the contents of a web page into a browser for viewing.
 FTP is a two way system as files are transferred back and forth between server and workstation.
HTTP is a one way system as files are transported only from the server onto the workstation’s
browser.
 When http appears in a URL it means that the user is connecting to a Web server and not a file
server.
 The files are transferred but not downloaded, therefore not copied into the memory of the
receiving device.

1.3.6 Wireless Application Protocol (WAP)


 Wireless Application Protocol defines a secure specification that allows users to access Internet
information instantly via handheld wireless devices such as mobile phones, pagers, two way radios,
smartphones and communicators.
 WAP supports most wireless networks.
 WAP is supported by all operating systems.
 Ones specifically engineered for handheld devices now include PalmOS, EPOC, Windows CE,
FLEXOS, OS/9, and JavaOS.
 WAPs that use displays and access the Internet run using microbrowsers. Microbrowsers are browsers
with small file sizes that can accommodate the low memory constraints of handheld devices and the low
bandwidth constraints of a wireless handheld network.
 Although WAP supports HTML and XML. The WML language (an XML application) is specifically
devised for small screens and one hand navigation without a keyboard.
 WML is scalable from two line text displays up through graphic screens found on items such as smart
phones and communicators. WAP also supports WML Script.
 It is similar to JavaScript, but makes mini• mal demands on memory and CPU power because it does not
contain many of the unnecessary functions found in other scripting languages.
 Because WAP is fairly new it is still an initiative hat was started by Unwired Planet, Motorola, Nokia,
and Ericsson.

1.3.7 Bluetooth
 Bluetooth refers to a short range radio technology aimed at simplifying communications among
Net devices and between devices and the Internet.
 It also aims to simplifying data synchronization between Net devices and other computers.
 Products with Bluetooth technology must be qualified and pass interoperability testing by the
Bluetooth Special Interest Group prior to release.

1.3.8 Simple Object Access Protocol (SOAP)


 Simple Object Access Protocol proposed by Microsoft provides a way for applications to
communicate with each other over the Internet, independent of platform.
 Unlike HOP, SOAP piggy backs a DOM onto HTTP (port 80) in order to penetrate server
firewalls, which are usually configured to accept port 80 and port 21 (FTP) requests.
 SOAP relies on XML to define the format of the information and then adds the necessary HTTP
headers to send it.

1.3.9 Internet Inter-ORB Protocol (HOP)


 Internet Inter ORB Protocol is a protocol developed by the Object Management Group
(OMG) to implement CORBA solutions over the World Wide Web.
 HOP enables browsers and servers to exchange integers, arrays, and more complex objects,
unlike HTTP, which only supports transmission of text.

1.4 Internet IP Address


 In the global network Internet, each node is identified with unique number called IP address.
The IP address of a machine is an array of four numbers separated by period, as shown below:
 18.10.200.14
 185.25.85.141
 Each number in the above array is an eight bit integer (That is it is between 0 and 255 and
called an Octet). There are three classes of networks in the Internet depending on the numbers
of hosts it can handle. They are
 Class A networks
 Class B networks
 Class C networks
 Class A networks can handle a large number of hosts. Class B networks are capable of handling
a moderate number of hosts.
 Class C networks can handle only a small number of hosts. The maximum number of hosts
handled by each network are tabulated in Table 1.4.1.
1.4.1 Class A Networks
 The first octet of a Class A network IP address represents the network ID and has a value from
1 to 126. So, there are only 126 Class A networks.
 However for each Class A network the second, third and the fourth octet represent the host ID.
 Which can be any number between 0 and 256 and hence can have 16,177,214 hosts.
(Note: 256 * 256 * 256 =16,177,216).
The general form of an IP address of a Class A network host is
N.H 1.H2.H3.
Where
 N ranges from 1 to 126
 Hl, H2, H3 are numbers from 0 to 255.

1.4.3 Class B Networks


 The first octet of a Class B network IP address is a value from 128 to 191. The general format of
a Class B network IP address is
Nl.N2.Hl.H2
Where
 N1 ranges from 128 to 191
 N2 ranges from 0 to 255
 Hl anil H2 may range from 0 to 255.
 N1 and N2 form the network ID and Hl and H2 represent the host ID. There can be up to 16,384
Class B networks on the Internet, each of which can have up to 65,534 hosts.
(Note: N1 takes one of the 64 values from 128 to 191 and N2 takes 0 to 255. 254 ♦ 254 = 65536)

1.4.3 Class C Networks


 Class C networks are designed to handle the situation where there would be very large number
of networks that contained a small number of networks which in tum contained a small number
of hosts.
 Small organizations having upto 254 hosts can go in for Class C networks. The general format
of the IP address is
N1.N2.N3.H
Where
 Nl ranges from 192 to 233
 N2. N3 may vary from 0 to 255
 H may vary from 2 to 255.
 There can be upto 2,097,092 Class C networks on the Internet, each of which can have upto 254
hosts. The following table 1.4.2 summarizes the facts on the IP address formats of various
Classes of networks on the Internet.

1.5 Domain Name


 A name that identifies one or more IP addresses. For example, the domain name
microsoft.com represents about a dozen IP addresses.
 Domain names are used in URLs to identify particular Web pages. For example.
Consider the URL
http://www.stxaviers.com/index.html
 The domain name is stxaviers.com. Every domain name has a suffix that indicates which top
level domain (TLD) it belongs to.
 There are only a limited number of such domains. For example:
■ gov—Government agencies
■ edu—Educational institutions
■ org—Organizations (nonprofit)
■ mil—Military
■ com —commercial business
■ net—Network organizations

■ ca—Canada

■ th—Thailand

 Because the internet is based on IP addresses, not domain names, every Web server requires a
Domain Name System (DNS) server to translate domain names into IP addresses as shown in
Figure 1.7.
Domain Name Server Internet Host
ISP
Figure 1.7 The Role of DNS

1.5.1 Uniform Resource Locator (URL)


 URL is the abbreviation of Uniform Resource Locator, the global address of documents and
other resources on the World Wide Web.
 The first part of the address indicates what protocol to use, and the second part specifies the IP
address or the domain name where the resource is located.
 For example, the two URLs below point to two different files at the domain
stxaviers.com.
 The first specifies an executable file that should be fetched using the FTP protocol; the second
specifies a Web page that should be fetched using the HTTP protocol:
http://www.stxaviers.com/nov2002result.exe

http://www.stxaviers.com/index.html

1.6 Internet Services


In this section we discuss some important services available through Internet.

1.6.1 Gopher Service


 The Internet Gopher protocol is designed primarily to act as a distributed document delivery
system. While documents (and services) reside on many servers.
 Gopher client software presents users with a hierarchy of items and directories much like a file
system.
 In fact, the Gopher interface is designed to resemble a file system since a file system is a good
model for locating documents and services.
 In essence, the Gopher protocol consists of a client connecting to a server and sending the server
a selector (a line of text, which may be empty) via a TCP connection. The server responds with
a block of text terminated with a period on a line by itself, and closes the connection.
 The server between transactions retains no state with a client. The simple nature of the protocol
stems from the need to implement servers and clients for the slow protocol.
1.6.2 Instant Messaging
 It is a type of communication service that enables you to create a private chat room with another
individual. Typically, the instant messaging system alerts you whenever somebody on your
private list is online.
 You can then initiate a chat session with that particular individual.
There are several competing instant messaging systems. Unfortunately, there's no standard.

1.6.3 Internet Relay Chat


 A virtual room where a chat session takes place is called a chat room.
 If two computers are connected through Internet the Internet Relay Chat (IRC) application
provides a platform for the users to chat.
 Technically, a chat room is really a channel, but the term room is used to promote the chat
metaphor.

1.6.4 Bulletin Board System (BBS)


 BBS is an electronic message center. Most bulletin boards serve specific interest groups.
 They allow you to dial in with a modem, review messages left by others, and leave your own
message if you want.
 Bulletin boards are a particularly good place to find free or inexpensive software products.

1.6.5 Usenet News Group Service


 A worldwide bulletin board system that can be accessed through the Internet or through many
online services is called a Usenet service.
 The Usenet contains more than 14,000 forums, called newsgroups that cover every imaginable
interest group.
 It is used daily by millions of people around the world.

1.7 Electronic Mail


 Electronic mail is the transmission of messages over communications networks.
 The messages can be notes entered from the keyboard or electronic files stored on disk.
 Most mainframes, minicomputers, and computer networks have an e-mail system.
 Some electronic mail systems are confined to a single computer system or network, but others
have gateways to other computer systems, enabling users to send electronic mail anywhere in the
world.
 Companies that are fully computerized make extensive use of e-mail because it is fast, flexible,
and reliable.
 Most e-mail systems include a rudimentary text editor for composing messages, but many allow
you to edit your messages using any editor you want.
 You then send the message to the recipient by specifying the recipient's address.
 You can also send the same message to several users at once.
 This is called broadcasting.
 Sent messages are stored in electronic mailboxes until the recipient fetches them.
 To see if you have any mail, you may have to check your electronic mailbox periodically,
although many systems alert you when mail is received.
 After reading your mail, you can store it in a text file, forward it to other users, or delete it.
 Copies of memos can be printed out on a printer if you want a paper copy.
 All online services and Internet Service Providers (ISPs) offer e-mail and also support gateways
so that you can exchange mail with users of other systems.
 Usually, it takes only a few seconds or minutes for mail to arrive at its destination.
 This is a particularly effective way to communicate with a group because you can broadcast a
message or document to everyone in the group at once.
 Although different e-mail systems use different formats, there are some emerging standards that
are making it possible for users on all systems to exchange messages.
 In the PC world, an important e-mail standard is MAPI.
 MAPI is the abbreviation of Messaging Application Programming Interface, a system built into
Microsoft Windows that enables different e-mail applications to work together to distribute mail.
 As long as both applications are MAPI enabled, they can share mail messages with each other.
The recent addition to Email is the Voice Email in which a Voice file is communicated.

1.8 World Wide Web


 Many people use the terms Internet and World Wide Web interchangeably, but in fact the two
terms are not synonymous.
 The Internet and the Web are two separate but related things.
 The Internet is a massive network of networks, a networking infrastructure.
 It connects millions of computers together globally, forming a network in which any computer
can communicate with any other computer as long as they are both connected to the Internet.
 Information that travels over the Internet does so via a variety of languages known as protocol.

1.8.1 Web Technologies


 The Web uses the HTTP protocol, only one of the languages spoken over the Internet, to
transmit data. Web services, which use HTTP to allow applications to communicate in order to
exchange business logic, use the Web to share information.
 The Web also utilizes browsers, such as Internet Explorer or Netscape, to access Web
documents called Web pages that are linked to each other via hyperlinks. Web documents also
contain graphics, sounds, text and video.
 The Web is just one of the ways that information can be disseminated over the Internet.
 The Internet, not the Web, is also used for e-mail, which relies on SMTP, Usenet news groups,
instant messaging and FTP.
 So the Web is just a portion of the Internet, albeit a large portion, but the two terms are not
synonymous and should not be confused.
 Web is a system of Internet servers that support specially formatted documents.
 The documents are formatted in a script called HTML (HyperText Markup Language) that
supports links to other documents, as well as graphics, audio, and video files.
 This means you can jump from one document to another simply by clicking on hot spots.
 Not all Internet servers are part of the World Wide Web.
 There are several applications called Web browsers that make it easy to access the World Wide
Web.
 Two of the most popular being Netscape Navigator and Microsoft’s Internet Explorer.
 In a web page information are presented using the following technologies:
■ HTML
■ Javascript
■ Java Applets
■ Java Server Pages (JSP)
■ Active Server Pages (ASP)
■ Java Servlets
 In the above list the browser machine executes the first three whereas the last three run in the server
machine.
 XML is a new technology, which is widely used in data formatting and communication. The web pages
also contain objects such as cookies and plugins, which are explained in the following sections.
1.8.2 Plug-in
 A hardware or software module that adds a specific feature or service to a larger system is
called a plugin.
 For example, there are number of plugins for the Netscape Navigator browser that enable it to
display different types of audio or video messages.
1.8.3 Cookie
 Cookie is a message given to a Web browser by a Web server.
 The browser stores the message in a text file (in the client machine itself) and uses each time the
browser requests a page from the server.
 The main purpose of cookies is to identify users and possibly prepare customized Web pages for
them.
 When you enter a Web site using cookies, you may be asked to fill out a form providing such
information as your name and interests.
 This information is packaged into a cookie and sent to your Web browser.
 The next time you go to the same Web site, your browser will send the cookie to the Web
servers.
 The server can use this information to present you with custom Web pages. So, for example,
instead of seeing just a generic welcome page you might see a welcome page with your name on
it.
 The name cookie derives from UNIX objects called magic cookies.
 These are tokens that are attached to a user or program and change depending on the areas
entered by the user or program.
 Cookies are messages that a Web server transmits to a Web browser so that the Web server can
keep track of the user’s activity on a specific Web site.
 The message that the Web server conveys to the browser is in the form of an HTTP header that
consists of a text only string.
 The text is entered into the memory of the browser.
 The browser in turn stores the cookie information on the hard drive so when the browser is
closed and reopened at a later date the cookie information is still available.
Web sites use cookies for several different reasons:
 To collect demographic information about who is visiting the Web site. Sites often use
this information to track how often visitors come to the site and how long they remain
on the site.
 To personalize the user’s experience on the Web site. Cookies can help store personal
information about you so that when you return to the site you have a more personalized
experience. When you visit a web site again and see your name mysteriously appear on
the screen, it is because, on a previous visit you gave your name to the site and it was
stored in a cookie. When you returned you would be greeted with a personal message. A
good example of this is the way some online shopping sites will make recommendations
to you based on previous purchases. The server keeps track of what you purchase and
what items you search for and stores that information in cookies.
 Web sites will often use cookies to keep track of what ads it lets you see and how often
you see ads.
 Cookies do not act maliciously on computer systems. They are merely text files that can be
deleted at any time.
 They are not plugins nor are they programs.
 Cookies cannot be used to spread viruses and they cannot access your hard drive. This does not
mean that cookies are not relevant to a user's privacy and anonymity on the Internet.
 Cookies cannot read your hard drive to find out information about you; however, any personal
information that you give to a Web site, including credit card information, will most likely be
stored in a cookie unless you have turned off the cookie feature in your browser. The cookie will
only contain information that you freely provide to a Web site.
Cookies have six parameters that can be passed to them:
 The name of the cookie.
 The value of the cookie.
 The expiration date of the cookie—this determines how long the cookie will
remain active in your browser.
 The path the cookie is valid for—this sets the URL path the cookie is valid in.
Web pages outside of that path cannot use the cookie.

 The domain the cookie is valid for—this takes the path parameter one step further.
This makes the cookie accessible to pages on any of the servers when a site uses
multiple servers in a domain.
 The need for a secure connection—this indicates that the cookie can only be
used under a secure server condition, such as a site using SSL.
Both Netscape and Microsoft Internet Explorer (IE) can be set to reject cookies if the user prefers.

1.9 Internet Security


 As the Internet connects millions of computers across the globe, the security and privacy are
two vital issues in this new era of Information Technology.
 This section introduces two widely used security technologies of the web. SSL and SHTTP.
1.9.1 Secure Sockets Layer (SSL) and Secure HTTP (S-HTTP)
 Secure Sockets Layer, is a protocol developed by Netscape for transmitting private documents
via the Internet.
 SSL works by using a public key to encrypt data that’s transferred over the SSL connection.
 Both Netscape Navigator and Internet Explorer support SSL, and many Web sites use the
protocol to obtain confidential user information, such as credit card numbers. By convention,
URLs that require an SSL connection start with https: instead of http:
 Another protocol for transmitting data securely over the World Wide Web is Secure HTTP (S-
HTTP).
 Whereas SSL creates a secure connection between a client and a server, over which any amount
of data can be sent securely, S-HTTP is designed to transmit individual messages securely.
 SSL and S-HTTP, therefore, can be seen as complementary rather than competing technologies.
The Internet Engineering Task Force (IETF) has approved both protocols as a standard.
1.9.2 Encryption
 The word encryption means translation of data into a secret code. Encryption is the most
effective way to achieve data security.
 To read an encrypted file, you must have access to a secret key or password that enables you to
decrypt it.
 Unencrypted data is called plain text: encrypted data is referred to as cipher text.
There are two main types of encryption. They are
■ Asymmetric encryption (also called public key encryption) and
■ Symmetric encryption.

1.9.3 Asymmetric Encryption (public-key encryption)


 Whitfield Diffie and Martin Hellman invented public key cryptography in 1976. For this reason,
it is sometime called Diffie Hellman encryption.
 This is a cryptographic system that uses two keys—a public key known to everyone and a private
or secret key known only to the recipient of the message.
 When A wants to send a secure message to B, he uses B’s public key to encrypt the message. B
then uses his private key to de• crypt it.
 An important element to the public key system is that the public and private keys are related in
such a way that only the public key can be used to encrypt messages and only the
corresponding private key can be used to decrypt them.
 Moreover, it is virtually impossible to deduce the private key if you know the public key.
 Public key systems, such as Pretty Good Privacy (PGP), are becoming popular for transmitting
information via the Internet.
 They are extremely secure and relatively simple to use.
 The only difficulty with public key systems is that you need to know the recipient’s public key to
encrypt a message for him or her.
 What’s needed, therefore, is a global registry of public keys, which is one of the promises of the
new LDAP technology.

1.9.4 Symmetric Encryption


In Symmetric encryption the same key is used to encrypt and decrypt the message.

1.10 Electronic Commerce (E-Commerce) and


Electronic Data Interchange (EDI)
 EDI stands for the transfer of data between different companies using networks, such as the
Internet.
 As more and more companies get connected to the Internet.
 EDI is becoming increasingly important as an easy mechanism for companies to buy, sell, and
trade information. ANSI has approved a set of EDI standards known as the X12 standards. E-
Commerce refers to transacting business online.
 This includes, for example, buying and selling products with digital cash and via Electronic Data
Interchange (EDI)
1.10.1 Digital Cash
 Digital cash refers to a system that allows a person to pay for goods or services by
transmitting a number from one computer to another.
 Like the serial numbers on real dollar bills, and rupee bills the digital cash numbers are
unique. Each one is issued by a bank and represents a specified sum of real money.
 One of the key features of digital cash is that, like real cash, it is anonymous and
reusable. That is, when a digital cash amount is sent from a buyer to a vendor, there is no
way to obtain information about the buyer.
 This is one of the key differences between digital cash and credit card systems. Another
key difference is that a digital cash certificate can be reused.
 Digital cash transactions are expected to become popular shortly.
 However, there are a number of competing protocols and it is unclear which ones will
become dominant.
 Most digital cash systems start with a participating bank that issues cash numbers or
other unique identifiers that carry a given value, such as five dollars.
 To obtain such a certificate, you must have an account at the bank; when you purchase
digital cash certificates, the money is withdrawn from your account. You transfer the
certificate to the vendor to pay for a product or service, and the vendor deposits the cash
number in any participating bank or retransmits it to another vendor. For large purchases,
the vendor can check the validity of a cash number by contacting the issuing bank.

1.10.2 Digital Signature


 A digital code that can be attached to an electronically transmitted message that uniquely
identifies the sender is called a digital signature.
 Like a written signature, the purpose of a digital signature is to guarantee that the
individual sending the message really is who he or she claims to be.
 Digital signatures are especially important for electronic commerce and are a key
component of most authentication schemes.
 To be effective, digital signatures must be unforgeable. There are a number of different
encryption techniques to guarantee this level of security.

-----------------------UNIT-I COMPLETE-------------------------
UNIT-II

Introduction to HTML: HTML Tags - HTML Documents - Headings -


Hyperlinks using Anchor Tag - Formatting Characters - Font - Images
and Pictures - Listing - Tables in HTML Tags – Frameset Definition -
Fame Definition- Nested framesets - HTML Forms - Elements of a form
use Tags.

Introduction to HTML
 Html is the basic tool for designing a web page.
 HTML is the acronym for Hypertext Markup Language.
 It is a documentation language to mark the headings, title, table and forms.
 IBM wanted to set a documentation system in which we can mark the title, headings, paragraphs
and font type selections in the 1980s.
 They came out with a set of markup system called it General Mark Up Language (GML). In
1986, International Standardizing Organization (ISO) took up this concept and standardized it as
Standard Generalized Mark Up Language (SGML).
 In 1989 Tim Berners Lee and his team in the European Laboratory for Particle Physics (CERR)
designed the present form of the documentation language and called it HTML.

2.1 HTML Tags


When a web page is to be developed, the following are to be planned:
 Content of the page
 Appearance of the page
The appearance of the web page is coded in HTML language using HTML tags.
2.1.1 HTML Tags and their Attributes
 An HTML tag is a word specifying the appearance of the content. The following are the salient
features of an HTML tag:
 A tag is enclosed between the < and > symbols. Examples are <head>, <hl>, <ol>

 Most of the tags have end tag. which begins with </. For example </hl> is the end tag
for <hl>.

 A tag may have some attributes. Attributes are the properties of the tag. For example, consider
the <hr> tag. This tag is for drawing the horizontal ruling (horizontal line).
 This tag contains the following attributes.

1. Size(thickness of the line)


2. Width
3. Alignment
These are represented as follows:
<hr size•10 width«2S% align = LEFT*

2.2 HTML Documents


Every html document begins with the <html> tag and ends with the corresponding end tag
</html>. A document has the following two sections.
1. Head
2. Body
The head section begins with the <head> tag and ends with </head>tag. In the head section title
is the most important item. The title begins with <title> and ends with </title>.

2.3 Headings
Headings can be created with tags hl, h2,...h6. Hl will make a bigger heading, h2 will make a
smaller one and h3 will make still a smaller heading and so on. For example, if you want the
name of your company (Innovative Educational Media Ltd.) to appear as a big heading, we type
as follows
<hl>Innovative Educational Media Ltd</hl>.

The output will be as shown in Figure 2.1


2.4 Hyperlink using Anchor Tag
 When a page is shown, some of its words may need further explanation. Such words are called
hot text or link and they appear in a different color.
 When the cursor is moved to the hot text a hand symbol appears.
 When we click it, another HTML file will be opened and that will have the required
explanation.
 A hot text is created with anchor tag <a>. For example, if a hot text United States of America is
to be created with a html document us.Html, we must type as <a href=’us.html*> United
States of America </a>.

 Here the anchor tag <a> has an attribute href. This attribute specifies the name of the document to be
opened.

For example, a HTML file travel. html is shown below. It contains details about the travel made.
<html>
<head>
<title>Travel in December 2002 </title>
</head>
<hl>Travel Details </hl>
<hr>
<br>
<h3>December 28, 2002 <a href**us.html*> United States of America </a> </
h3>Quarterly Meeting with Bank of America
<br><h3> December 29, 2002 <a href= 'Canada.html* >Canada </a></h3>
Meeting with Brach office Managers<br>
</body>
</HTML>
When this file is opened using an Internet browser we get the page shown in Figure 2.3.

Figure 2.3 First Web Page

In this page United States of America is a hot text. When this is clicked, it will open us .html.

2.5 Formatting Characters


 In a web page the characters can be made bold, italics, underline etc. by using some HTML
tags. There are two methods of formatting characters. They are.
1. Logical styles.
2. Physical styles.

2.5.1 Logical Styles


 The logical styles inform the browser what kind of text to present.
 The browser takes care of how to present it. For example consider the <em> tag.
 This tag tells that emphasis must be given.
 The browser takes care of how to present it so that it gets the emphasis required.
 Table 2.1 lists the logical style tags.

2.5.2 Physical Styles Format


 The physical styles format tags explicitly informs the browser how the characters must be shown,
bold, italics etc.
 The physical styles tags are shown in Table 2.2.
2.6 Font Tag
 The <font> tag is used to set a specific font and size. It usually has two attributes, namely face
and size.
For example, consider the following:
<font face=Times Roman size « 35>
Web Technology book by Dr. C. Xavier
</font>

2.7 Images and Pictures


 A picture or an image in the web page can be inserted using the <img> »ag.
 The <img> tag has several attributes to inform the source, height of the picture, width of the
picture alignment etc.
The following are its important attributes:
 src
 Height
 Width
 Align
 alt
 The src attribute specifies the source of the picture. It gives the file name of the picture file.
 The height and the width may be expressed in terms of either pixels or percentage or en units.
 The default is the pixels. For example consider the following:
<img src=*companylogo.gif• height=100 width=120>

The align attribute an be used to align the picture.

2.8 Listing
 This section introduces two more tags <ol> and <ul> that lists a set of items either with serial
numbers or with bullets.
 They are called Ordered and Unordered lists.

2.8.1 Unordered Lists


 The Unordered list is represented by <ul> tag and </ul> tag. <ul> is given at the beginning an
</ul> tag is given at the end. Each list item is given <li> tag.
 In the unordered list, every listed item has a circle or square as its bullet. The bullet can be any
one of the following symbols:
 Disc
 Circle
 Square
 The symbol that we want to include can be chosen using type attribute of <UL> tag.
 For example suppose we use <ul type = square> we shall get square symbol.
 If we use <ul type = circle> we shall get the circle.
 We shall get a disc as the bullet if we give the <ul> lag as <ul type » disc>.
The following is an example:
<html>
<head>
<title>
Unordered
List
</title>
</head>
<body>
<hl>Places Visited</hl>
<ul>
<li>United States of America
<li>Canada
<li>Brazil
<li>United Kingdom
</ul>
</body>
</html>
The output is shown in Figure 2.4.

Figure 2.4 Unordered List


2.8.2 Ordered Listing
The ordered list is represented by <ol> in the place of <ul>.
Consider the following:
<html>
<head>
<title>
Unordered
List
</title>
</head>
<body>
<hl>Places Visited</hl>
<ol>
<li>United States of America
<1i >Canada
<li>Brazil
<li>United Kingdom
</ol>
</body>
</html>

The output is shown in Figure 2.5.

Figure 2.5 Ordered List

2.8.3 The Start and Type Attributes


In an ordered list, the numbers begin from 1. It is possible to start the number from any desired
integer. For example, suppose we want to start from 16. Then we can represent the fact in START
attribute of the <ol> tag as follows:
<ol start = 16>

 Instead of numerals, we can have such as A, B, C, or a, b. c Etc or roman letters in the ordering of the
listed items.
 This is specified by the type attribute in <ol> tag. The symbols used with type attribute are shown in
Table 2.3.
2.9 Tables in HTML Tags
 In HTML the beginning of a table is marked by <table> tag and the end is marked by
</table> tag.
 If we want a border for our table, we must give the beginning tag as
<table border>
 If we want a bigger border we can also give numbers to represent the size of the border. For example,
<table border « 5>

Will give a bigger border.


 The caption for the table must be given with the <caption> tag.
 A row begins with <tr> tag. <th> tag specifies the heading row of the table.
 In a row, <ti> tag specifies the table item (cell).
 The following is an example.
<html>
<head>
<title>
Table showing the Places visited
</title>
</head>
<body>
<table bcrder»5>
<caption><b>Places Visited</bx/caption>
<tr>
<th>Date <th>Country <th>Purpose
<tr>
<td>Dec 28,2002<td>USA <td>Quarterly Review Meeting
<tr>
<td>Dec 29,2002<td>Canada <td>Branch Managers Meeting
</table>
</body>
</html>

The output is shown in Figure 2.6.

Figure 2.6 Table Showing Places Visited

2.10 Frameset Definition


 A set of frames are defined using the <frameset> tag which ends with </frameset> tag.
 The <frameset> tag has two attributes.
1. row or column frame
2. size of each frame.
The size of the frames are mentioned in any one of the following units:
1. Pixel unit
2. Percentage unit
3. Fraction unit
2.10.1 Pixel Unit
 The pixel unit simply represents the number of pixels in each frame. Commas must separate the
numbers.
For example, consider the following:
<frameset cols=* 150,70,70'>
</framoset>
 This definition creates three column wise frames with the first frame of 150 pixels width, second of
70 pixel width and the third also of 70 pixels width.

2.10.2 Percentage Unit


 The percentage unit divides the window according to the specified percentages. For example, consider
the frame set definition,
<frameset rows=70%, 30%>
</frameset>
 In the above definition two row wise frames are defined in the container.
 The first frame has 70% of the container and the second one has 30% of the container.
 If the total of the percentages is greater than 100 all percentages are scaled down.
 If the sum of the percentages is less than 100, the extra spaces are left out.

2.10.3 Fraction Unit


 Instead of using percentage unit, we can use fraction unit to represent the relative size of the
frames. Suppose we give the following:
< frameset cols=’4*,4*,*,*’>
</frameset>
 This defines four column wise frames.
 The first two frames have 4units size, and the third and fourth ones have one unit each. So, the
frame sizes are 4/10,4/l0,l/10 and 1/10 of the overall container size.

2.11 Frame Definition


The definition of the frame is given using the <frame> tag. The <frame> tag may have any of the
following attributes:

■ Source html address (src)

■ Name of the frame (name)

■ Margin width (marginwidth)

■ Scrolling button (scrolling)

■ Can it be resized (noresize)


Consider the following frameset definition. Two rowwise frames are defined.
<html>
<head>
<title>
Welcome to Commercial Bank of Singapore
</title>
</head>
<frameset rows=*45,55’>
<frame name»'fl’ src=*D:\servlets\Banking\Bankl,html">
<frame name«'f2• src='http:Wlocalhost:8080\servlet\BankSelfHelpServlet'>
</frameset>
</html>

The output appears as shown in Figure 3.1

Consider the following frameset definition. It has column wise frames.

<html>

<head>

<title>Foreign Exchange</title> </head>

<frameset cols=*52,4>
<frame name=*f1• src=•http:\\localhost:8080\forexl.jsp*>
<frame name="f2• src=*http:\\localhost:8080\servlet\Forex*>
</frameset>
</html>

The output appears as shown in Figure 3.2.

Figure 32 Foreign Exchange Window

2.12 Nested Framesets


 In this section we deal with nested framesets In the example shown here first the window is row
wise divided into two frames.
 The bottom frame is column wise divided further into two frames.
 The <no frame> tag is also used to communicate suitable message when the browser doesn't support
frames.
<html>
<head>
<title>Tutorial on Web Technology</title>
</head>
<frameset rows=*152,*'>
<frame name » 'banner* scrolling « 'no' noresize target » 'contents' src =
\'frameheader.html'>
<frameset cols='150,*'>
<frame name•'contents' target•'main' src« 'contents.html'>
<frame name•'main' src 'body.html'>
</frameset>

<noframes>
<body>
<p>This page uses frames, but your browser doesn't support them.</p>
</body>
<noframes>
<body>
<p>This page uses frames, but your browser doesn't support them.</p>
</body>
</noframes>
</frameset>
</html>

The output is shown in Figure 3.3


2.13 HTML Forms
 Using forms we can design a web page on which a user can communicate his wish, opinion, suggestion
etc.
 A form is defined with <form> tag and </form> tag. The form tag has three attributes. They are
 action
 method
 enctype

2.13.1 Action Attribute


 The forms are used to get the input from the user. The user input is submitted to the server.
 The action attribute informs the browser the location of the server program to which the form input has
to be submitted.
 The server program may be a cgiperl script, a Java Applet or any other server program like JSP, ASP
etc.

For example, if want a program \cgibin\comments.exe to be executed when the form is


submitted, then we must mention the following attribute value in the <form> tag.
action = '/cgibin/comments.exe'

 This means that comments.exe is a file that exists in a directory cgibin.


 The name of the executable program and its location of the directory depends upon the web server.
 We can also enter a complete URL and hostname. If we leave off the starting part of the URL, the
browser will submit the form to the server, which supplied the form.

2.13.2 Method Attribute


The method attribute has only two choices of values. They are
method='get'
method=*post*
 This denotes the protocol the server uses in implementing the forms features. Usually the value used for
method attribute is

method="post”

 This is the recommended protocol. With the post method, the information from the user is put into
the data stream of the HTTP, and the backend program can read the data as input through the
"standard input' data stream.

 In the case of method = 'get', the data received in the form are placed at the end of URL.
 If the form is very big and gets a number of input, the 'get' method causes the URL to be very
long. So, the method « 'get' option is often discouraged.

2.13.3 ENCTYPE Attribute


 This attribute is used to inform the server the way to handle the encryption process. Usually it is set to
application/x.www.form.urlencoded.
 That is, the value is given as enctype = 'application/x.www.form.urlencoded'.

2.14 Elements of a Form use tage


In a form there can be several elements to get the input form the use. They are
 Selection list box
 Input box
 Text Area

2.14.1 Selection List Box


 A selection list presents a list of options to the user. The user can select his choice from the list. The
selection list box is created with <select> tag. The definition ends with</select> tag.
 The <select> tag has three attributes. They are
 Name attribute
 Size attribute

 Multiple attribute
 The name attribute assigns a name for the variable, which will hold the selected choice.

For example consider the following:


<select name='nameBox'>
<option>Aparna</option>
<option*Nithya</option>
<option*Priya</option*>
</select*>
This creates a selection box with three choices. Apama, Nithya and Priya. It is possible to assign a value for
each option using value attribute in option tag.

This is illustrated below;

<select name=“nameBox“*
<option
value=“1‘>Aparna</option*

<option
value=“2’>Nithya</option*

<option
value=”3’Priya</option*

</select>
 In the dropdown list we normally select one of the items.
 There are certain cases in which the user can be given a freedom to select more than one of the options.
 This is provided by the multiple attribute in the select tag.
cselect name « townsvisited multiple « “multiple* *

2.14.2 Input Elements


The input of the user can be given in any of the following GUI elements
■ Checkbox
■ Radio button
■ Text field
■ Password field
■ Hidden field
■ Button
■ Submit Button
■ Reset Button
 The input box is defined using the c input tag.
 The type attribute defines whether it is a checkbox, radio button etc.
 The values are tabulated in Table 3.5.1
2.14.3 Text Field and Submit Button

Consider the following HTML document.

Figure 3.4 A Text Field and a Submit Button

2.14.4 Checkbox
The following is a HTML document that shows a form with several checkboxes.
<html>
<head>
</head>
<body>
<h3>Please select your computer configuration<br></h3>
<h4 >
<input types’checkbox"
name «=’computer ’ values*CPU Intel P4 1.8GHz ’ >Intel P4 1.8GHz<br>
<input types’checkbox*
name=’computer" values’HDD 40 G3’>With 40 GB HDD<br>
<input type­’checkbox"
name­’computer" value­*l5 inch color Monitor’>With Monitor<br>
<input types’checkbox’ .
name=’computer" value­’1.44MD FDD">With
FDD<br>

<input type­’checkbox"
name­’computer" value­’CD ROM Drive’>With CD ROM Drive<br>
<input type­’checkbox"
name=’computer" value­’Printer’>With Printer<br>
<input type­’text’ nameOrder" size=’50’>
<input type•"button" name­’test’ value"Order Please’>
</h3>
</body>
</html>

The output for the above program is shown in Figure 2.5.

Figure 2.5 Checkbox


2.14.5 Password Field
 The following HTML document shows a password field. Notice that when a user types the password,
the characters are no displayed.
 The asterisk symbol will be displayed.
<html>
<head>
<title>Authorisation Page</title>
</head>
<body>
<form name=*myform*> *
User Id :<input typetext name«idxbr>
Password :<input type=password
name=pwordxbr>

<input typesubmit value=Go>


</form>
</center>
</body>
</html>

The output is shown in Figure 2.6.

Figure 2.6 Password Field

Example 2.5.1 Changing the Password


 This example illustrates the form for changing the password.
 This shows three password fields, one for old password and two for the new password.
 The HTML document is shown below:
<html>
<head>
<title>Password Change Page1</title>
</head>
<body>
<center>
<h2>Changing Password</h2>
</center>
<form name=myform method=post >
<pre>
<center>
Type user name here<input type=text name=id><br>
Type old password here<input type=password name=oldxbr>
Type new password here<input type=password
name=newlxbr> Retype the new password<input
type^password name=new2xbr>
<input type=submit value=Change>
</center>
</pre>
</form>
</body>
</html>

The output is shown in Figure 2.7.

Figure 2.7 Changing the Password


2.14.5 Radio Button and Text Field
Consider the following HTML document.
<html>
<headxtitle>Foreign Exchangee/title>
</head>
<body>
<form name®*forexform*>
<pre>
Enter the value in Rupees
<input type text name®*rupees*>
<input type radio name® currency > USDollar
<input type radio name® currency> UKPound
<input type radio name® currency> Singapore Dollar
<input type radio name® currency> UAE Dhirams
</form>
</body>
</html>
The output is shown in Figure 2.8.

Figure 2.8 Foreign Exchange Form

Example 2.5.2 Factorial of a Number

The following HTML document shows two text fields and a button.
<html>
<head><title>Factorial</title>
</head>
<body>
<form>
<hr><br>
<hl align='center*><marquee> Factorial </marquee></hl>
<pre>
<center>
Enter the number : <input type^text name«a>
<br>
The Factorial is : cinput type=text name=b>
<br><br>
<input type=button value='Find the Factorial' >
</pre>
</form>
</body>
</html>

The output is shown in Figure 2.9.

Figure 2.9 Form with Button and Text Field


 This example illustrates how a banking self care web page be designed.
 The user must type the Account number and the PIN number (Personal Identification Number), The
account number can be typed in a text field.
 The PIN number is a secret code and hence has to be typed in a password field.
 The various services available to the customer are shown as radio buttons.
<html>
<head>
</head>
<body bgcolor bisque text black>
<form action=http:\\localhost:8080\servlet\BankSelfHelpServlet target•f2>
<i><b><h2>Self Care Customer Service</h2x/bx/i>
<table align=center>
<tr>
<td>Account Number</td>
<tdx input type text name=accno ></td>
<tdxtdxinput type radio name=service>Balance Enquiry</td>
</tr>
<tr>
<td>PIN Number </td>
<td><input type password name pin value•0 ></td>
<tdxtdxinput type radio name service>MiniStatement</td>
</tr>
</table>
<input type button value PROCEED >
<input type hidden name serviceRequest value«0>
</form>
</body>
</html>

The output is shown in Figure 2.10.

Figure 2.10 Banking Web Page


2.14.7 Text Area
 The Text Area is a multiline area in which the user can type the input.
 For example, the experience of a user with a product the suggestion for improvement of a course
etc can be got using text area.
 A text area can be created using <textarea> tag.
 The <textarea> tag has three attributes. They are,
1. Number of rows in the text area
2. Number of columns in the text area
3. Name of the variable which will attain the content typed in the text area and submit it to
the server
 The rows and the columns attribute tell the number of rows and the number of columns of the text field
visible at any instant. Notice that this is not a restriction for the text typed.
 The text area will have scroll bars for viewing the entire text typed.
 For example consider the following: 
<textareaname'remark'rows='5'columns='25‘> </textarea>

The following HTML code creates a text area as shown in Figure 3.11.
<h2>Type your remarks here and press Proceed button</h2>
<textarea name = "remark* rows « *5* columns =*25">
</textarea>
<input type=button value="PROCEED*>

Exercises

2.1 Design the following form:

2.2 Design the following form:

 The date of birth has three list boxes, for day, month and year.
 The date list contains the dates from 1 to 31.
 The month list contains JAN, FEBDEC. The year list contains the years from 1950 to 2000.

---------------------------------------UNIT-II COMPLETE------------------------------------
UNIT -III
JavaScript : Data Types - Variables - Operators - Conditional statements
using Javascript – Document Objects - Image Objects using Javascript -
Forms and Elements - Event Handling - Browser Object - Submit Event
and Data Validation -Parseint() Function - ParseFloat() Function -
Recursive Function.
JavaScript
 Though JavaScript is a free flow language it is vital to know the basic framework of the
language.
 These fundamental elements of the language are similar to that of any other language.
 But for the sake of completeness, this Chapter deals with variables, data types, operators,
expressions and statements.
3.1 Data Types
 Due to the use of JavaScript in interactive web design, the main focus of the language is not
processing of numeric data for precision.
 However the language supports Numeric. Boolean and String data.
 Apart from the above three types. Object is another important data type supported.
 As a open standard the Null Data and Undefined data types are also supported.

3.1.1 Numbers
 The integer and floating point numeric data are called numbers.
 A number can be positive, negative or zero. Integers can be represented in decimal, octal and
hexadecimal form.
 The octal integer begins with a zero and hexadecimal integer begins with Ox or oX.
 The following are some valid integers.
45 Decimal value 45
1 Decimal value 0
-25 Decimal value 25
-015 Octal value (—15)8
OX2A Hexadecimal value(2A)
 Floating point numbers can be represented either in decimal form or exponent form.
 The following are some valid floating point numbers.
0.78
-10.2
0.25e4
-O.8E3
3.1.2 Boolean
 JavaScript considers True or False values as Boolean values.
 In comparison 0 is considered as false and any nonzero value as True.
3.1.3 String
 A String is any list of characters given within single or double quotes.
3.1.4 Objects
 JavaScript is an Object Oriented language. It is possible to define an object of a class.
 For example an object of an Employer class can be created using new operator as follows:
x = new Employee(“Raman*,45);

3.1.5 Null and Undefined datatypes


 A null value is one that has no value and means nothing.
 A value that is undefined is a value held by a variable after it has been created.

3.2 Variables
 The name of the location where a data value is stored is called variable.
 For example, when we say age = 45. The value 45 is the data value.
 It is stored at a location called age.
So, age is the variable.
45Age
 In other words, the variable is the data reference.
 In JavaScript, no declaration is necessary to specify the type of data stored.
 However the scope of the variable is an important aspect to be discussed here.
 A variable may have either global scope or local scope.
 A variable by default is having global scope.
 If a variable has to be defined in local scope, define with var keyword.
3.2.1 Global Scope
 A variable having global scope can be accessed from any function on the page.
 If a value is simply assigned to a variable, it is of global scope.
age = 45;
 If the variable age is created as above, it means that it is having global scope.
3.2.2 Local Scope
 Temporary variables having scope only inside a function are said to have local scope. Local
Variables are defined using var statement.
 For example, consider the following:
function
sum(a,b) (
var total=0;
total + a+b;
return(total
>;
}
 In the above function, total is defined using var statement.
 So, it has local scope.
 This means that it cannot be referred from other functions of the JavaScript page.

3.3 Operators
 JavaScript permits almost all the common operators of any language.
 They are listed below:

3.3.1 Arithmetic Operators

3.3.2Boolean Operators
&& A
ii Or
! Not
3.3.3 String Concatenation

Concatenation
For example,

Rama' + 'Krishnan*gives
RamaKrishnana = 'Kalyana'
b='Raman’
c=a+b

In the above example, c gets the value 'KalyanaRaman'.

3.3.4 Relational Operators


2= Equal to
f=
Not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to

3.3.5 Assignment Operators

 Consider the following mathematical option:


X=2y+z+MX
 Here the value of 2y + z + 100 is evaluated and assigned to x.
 In the statement x = 2y + z + MX) the equal to ( = ) symbol is called the assignment operator.
 Table 4.1 gives the assignment operators in JavaScript Consider the statement x += 2y + z + 100.
 This statement is equivalent to the following statement: x=x+2y+z+MX
 That is, the value of x + 2y + z + 100 must be evaluated and assigned to the variable x. Let x = 10.
y = 20, and z=30 be the original values.
 After executing the statement x+=2y+z+100
 The values will become, x = 180, y = 20, z=30. So += is also considered as an
assignment operator. Table 4.1 gives a list of assignment operators:
3.3.6 Conditional Assignment Operator
The conditional operator checks a condition and then assigns a value to a variable. The general
syntax of the conditional assignment operator is shown below:
Variable « (condition) ? Value 1 : Value 2;
Where condition is a logical expression
Value 1 is the value assigned to the variable when the logical expression is true.
value 2 is the value assigned to the variable when the logical expression is false.
For example consider the following:
String result;
Result?(mark >= 40) ? ‘Pass' : 'Fail';
In this example the value "Pass” is assigned when mark is greater than or equal to 40. Other wise
“Fail” is assigned.
3.4 Conditional Statements
3.4.1 IF-ELSE Structure
 JavaScript also supports the conditional statement that checks a logical expression and decides
the further steps.The following is the general format of the If -Else structure:
if(condition)
{
statements
}
s1
else
{
statements s2

Example 3.4.1 Validation of Age


 In this document we validate the age of the user.
 Here we have a text field where the user has to enter his age and click the Submit button.
 Once the user clicks the submit button validate!) function is called.
 This function checks whether the age of the user is greater than I and less than or equal to
150 if so, it returns true otherwise an alert message is shown.

The HTML document is given below:


<html>
<head>
<script type**text/javascript'>
function validate!)
<
ageOfUser=document.biodata_form.age.val
ue if (ageOfUser>«l && ageOfUser
<
<«150)
return true
>
else
<
alert('The age you have submitted seems to be
incorrect Please reenter correctly")
return false

}
</8cript>
</head>
<body>
<form name«zsd*biodata_form* onsubmit«*return validate()*>
<h3>Enter your Age
please..</h3> cinput
type=*text* name=*age*>
<input type="submit” value=*Submit Age*>
</form>
</body>
</html>
The output is shown in Figure 4.1.

Figure 4.1 Age Validation

3.4.2 The Switch Statement


 The Switch structure of the JavaScript matches an expression with a specified case and executes
the statements defined for that case.
 The general format is shown below:
switch(expression)
{
case labell:
<
---------
-------
break;
}
case label2:
{
---------
---------
break;
}
case label3:
{
-------
-------
break;
}
------
------
default:
{
-----------
------
break;
}
}
The following example illustrates the use of switch structure.

Example 3.4.2 Color Generation


Figure 3.2 Color Form

3.4.3 Do...while Loop


 The general format of the do...while loop is shown below:
do
{
---------
- - - - - - - - --
---------

>
while! condition)

 The statements between do and while are executed repeatedly until the condition
becomes false.

3.4.4 While Loop


 The while loop is similar to the do loop except that the condition is tested at the entry itself.
While (condition)
{
-----------
---------
--------
}

3.4.5 For-in Loop

 The for-in loop is used to repeat a set of statements for each property of an object or each
element of an array.
 The following is the general format:
for (var v in object)
<
----------
---------
--------
>
If object referred above has n properties , the statements are executed n times with v assuming
these n values.

3.5 Document Object Model


 Java script handles the HTML documents and the related objects such as windows, forms and
screen in a specified hierarchy.
 This hierarchy is called the Document Object Model (DOM) are directly related to the browser.
 The properties of the objects covered in the DOM get their val• ues supplied by the browser.
 The DOM hierarchy is shown in Figure 5.2.
In a HTML document if two forms and three images are present they are referred as shown in
Figure 5.3
.
3.5 The Document Object
 The document object refers to the current HTML/Javascript document displayed by the
browser.
 It has several properties including the following:
document.bgcolor
document.background
document.font

 It is possible to dynamically change the properties of the document.


 For example, consider the following function:
function changecolor(c)
{
document.bgcolor = c
}

 The above function changes the background color to the specified color C.
 This function can be called at any specified event and the color changed.

Example 5.2.1 Document Object


 This example illustrates that document.
 Bgcolor refers to the background color of the document.
 In this document seven buttons are shown with the names Red, Green, Blue,
Orange, Violet, Indigo and Yellow.
 When the user clicks on a button the background color changes accordingly and an alert
message is also shown with the name of the color.
 The following is the function.


The output of the color document is shown in Figure 5.4.

Figure 5.4 Document Background Color

3.6 Image Object using javascript


Consider the following statements
document.images[0].width=300
document.images(0).height=350

 In the document the images are referred by the array images(O), images11,
...etc.. The above statements change the size of images [0] into width.300 and height350.
 If the images are given some names then we can use the name in the place of images [0].
For example, consider the following in a HTML document.
<img sre 'logol.gif* width = 100 height=200 >

The image is loaded from the file logol.gif. So, in a Javascript Program we can refer to this image
as document images [ 0 ]. The following statements can be used to change the width and
height to 300 and 350 respectively.
document.images[01.width << 300

document.images[0].height « 350

If we want to dynamically load a different picture we can write


document.images[0].src = 'newlogo.gif'
Example 5.3.1 Images in a Document

Consider the following HTML code:


<hl>Chief Executive Officer </hl>
<a href•'#'
onMouseOver = 'document.images[0].src=' 'ceonew.gif '
' onMouseOut = 'document.images[0] .src=' 'ceoold.gif'
' '
<img src='ceoold.gif ' width = 160 height=100 border » 1 >
< /a >
 In the above code we have only one image which shows the image from the source
ceoold.gif. This is referred as images [0].
 We change the src property of the image object while the mouse is moved over the image.
 We show a different picture of the CEO.
 When the mouse pointer moves out of the picture the old image is again loaded. The
output appears as shown in Figure 5.6.

Figure 5.6 Changing Image Properties Dynamicall


3.7 Forms and Elements
 This section introduces another important object of a document Forms.
 Forms play a major role in the interaction between the user and the browser.
 The user types the input in forms.
 A HTML document may consist of several forms.
 Each form may consist of several Elements, input objects.
 For example the following are some elements.
■ Button
■ Submit button
■ Radio button
■ Check box
■ Select list box
■ Text input field
■ Text Area
 In a form these elements are referred to as an array called elements (). For example consider
the form shown in Figure 5.7.

This form has seven elements. JavaScript represents them using an array elements [ ]. Table 5.4.1
shows the reference details of each of the elements.
 In a JavaScript program if we want to reset the value of Name input Text field with a
string “Type Your Name”, we will code as follows:
document.forms[01 elements[0].value=*Type Your

Name*; Consider the following code:


document.forms[0].elements(1].value = ^Address
Please* ;

This changes the value of String in the Text Area to 'Address Please* .
 A document may have several forms. They are referred to by the array forms [ ].
 For example, if a document has three forms they are referred by forms[0], forms[1]
and forms [ 2 ]. This is illustrated in the following example.

Example 5.4.1 Several Forms in a Document


Consider the following HTML document, which has three forms.
<html>
<head>
<title> Order form </title>
</head>
<body>
<form>
<h4> form[0] </h4>
<h2> Television Order </h2>
Type the screen size <input type « text>
<input type = button value » * OK *>
</form>
<hr>
<br>
<form>
<h4> formll] </h4>
<h2> Washing Machine Order </h2>
Type the capacity <input type text>
<input type » button value • • OK • >
</form>
<hrxbr>
<form>
<h4> form[2] </h4>
<h2> Refrigerator Order</h2>
Type the capacity <input type = text>
<br>
Select open or closed back
<select>
<option> open back </option>
<option> closed back </option>
</select>
<input type button value OK " >
</form>
</body>
</html>

In this document three forms are available as illustrated in Figure 5.8.

Figure 5.8 Three Forms in a Document


This document can be represented by the tree structure as shown in Figure 5.9.

Screen OK Button Capacity Text OK Button Capacity Text Select Box OK Button
size Text Field Field
Field
Figure 5.9 The Tree Representation of the Objects in the Document

The form are referred follow:


document.forms(0]
document.forms(1]
document.forms[2]

For example a text field for Television Screen Size in the first form is referred as
document.form[0).elements[0]

The OK button of Television order form is referred to as


document.forms[0 J.elements[1 1

Similarly the other objects in the form are represented as follows:


document.forms[11.elements[01 Capacity text field in washing machine order form.
document.forms[1).elements[1) Ok button of the washing machine order form.
document.forms[2].elements[0] Capacity text field in refrigerator order form.
document.forms[2].elements[11 Select box in refrigerator order form.
document.forms[2).elements[21 OK button in refrigerator order form.

Now, let us write a method alcrtTV as follows:


 We can call this method when the OK button of Television order form is clicked.
<input type « button onClick »”alertTVO”>

 Similarly functions alertRefrigerator () and alertwashingmachine () are also shown


in the following document.
The output is shown in Figure 5.10.

Figure 5.10 Three Forms in a Document

3.7.1 Naming the Objects


 The objects of the HTML documents can be assigned names using the attribute name.
 For example, consider the following:
< form name = tvform >
 In this case the form can be referenced as document.tvform.
 In a similar manner all the objects in the document can be given names.
 For example consider the following:
< img src =”logol.gif” name « complogo width « 100 height « 200 >

If we want to make the width as 300 and height as 350 we can write as follows:
document.complogo.width = 300
document.complogo.height = 350

If this image is the first image in the document, we can also refer to the image as images[ 0 ]
instead of its name. So, this can also be written as
document.images[0].width = 300
document.images(0].height = 350

The HTML document created in Example 5.3.1 shows the image of the CEO. The image can
be given a name CEO as shown below:
< img src « 'ceoold.gif* name » CEO width = 160 height = 100 border = 1 >

Now the name CEO can be used to modify the height and width as illustrated in the following
document.

Consider the HTML document illustrated in Example 5.4.1. Each object in the document can be
assigned a name. Let the three forms be given the names as shown in Table 5.4.2 :

Table 5.4.2 Naming the Forms

1 Television order form Tvform


2 Washing machine Wash
form form
3 Refrigerator form Ref
form

So, these forms can be referred as follows:


 In the Washing Machine Form these are two objects, one text field and the OK
button.
 They can be assigned names as shown in Table 5.4.3.

The portion of the html page for the Television Order Form is written as follows:

consider the statement size = document, tvform, tvsize.value


This assigns the value typed by the user in the text field.
Similarly the other objects can be assigned names as follows:

■ The capacity text field in Washing Machine order Form can be named washcapacity.
■ The capacity text field in Refrigerator Order Form can be named ref capacity.
■ The Select box in the Refrigerator Order Form can be named ref type.
The HTML document is rewritten with the above names as follows:
<html>
<head>
<title> Order form </title>
<script language*•JAVASCRIPT*>
<! —
function alertTV()
<
size=document.tvform.tvsize.value
alert('You want to order a television of size = ”+size)
}
3.7.2 Check Box Element
 This section illustrates the use of check box to select System configuration.
 The page designed here shows a Check Box, a Text box and Submit button.
 In this document the user selects the Check box in order to select the system
configuration.
 Once the user clicks order please button the selected configurations appears in the text
box.
The HTML document follows:
The output is shown in Figure 5.11

Figure 5.11 Check Box

3.7.3 Radio Button and Text Field


 In this section we discuss the handling of events in radio button and text box.
 The example foreign exchange also illustrates the naming of the form and its elements.
 This document shows a form with a text field and four radio buttons as shown in Figure 5.12.

Figure 5.12 Foreign Exchange Form


 This form is used to find the value of an amount of Indian rupees in any four of the currencies.
 For simplicity the unit value of the foreign currencies are assumed as in Table 5.4.4.

 The reader must note that this method of handling foreign exchange conversion is an inefficient
one as the values are dynamic.
 However, we use this method here because our objective here is to illustrate the elements of a
form.
The form is given the name Forexform.
< form name « forexform>>

The text input field is called rupees.


< input type « text name = “rupees” >

 After entering a value in this input text field, when the user clicks the radio button
“US Dollar” this value is converted into US Dollar and the value is shown in an alert
message.
The complete HTML/Javascript code is given below:
The output is shown in Figure 5.13.

Figure 5.13 Foreign Exchange


Example 5.4.3 City Selected
 This example illustrates the use of Radio button. In this document we have 4 Radio
buttons and a Text box.
 When the user clicks the Radio button, the corresponding value appears in the text
box.
The HTML document is given below:

The output is shown in Figure 5.14.


Figure 5.14 City Selection

3.7.4 Select Box


This section illustrates the use of select box to select a name and find the phone number, page
shows a Select Box and a Text box. When the user selects a name from the select box
corresponding phone number appears in the phone number Input box. This example is with
sample data shown in Table 5.4.5.

The phone numbers must be stored in an array as follows:

 When the above array is created, we can refer to the numbers as phone [0].
 phone [1], phone [2] etc. For example, phone [0 ] refers to the phone number of
Apama 6184723.
 We must now write a Javascript function getnumher (f)lo display the phone number.
The input parameter f is the form of this document.
 The form has format shown in Figure 5.15.

Figure 5.15 Telephone Directory Form

The components in the form are listed in Table 5.4.6.

 In the above function f.nameBox.selectedlndex returns the index of the name


selected.
 For example, if you select Apama it returns 0.
 This index value is stored in a variable i. Now the phone number required is phone (i).
 This value is assigned to the text box as
f. phoneNumber.value = phone [i]
The HTML document with the Javascript function is shown below:

The output is shown in Figure 5.16.


Figure 5.16 Telephone Directory

Example 5.4.6 Selecting Your State


 This example illustrates the use of Select box.
 In this document we have a Select box and a Text box.
 The Indian states are listed in the Select box. Once the user selects a state from select box,
the value appears in the text box. T
 he HTML document is given below:
The output is shown in Figure 5.1
Figure 5.17 Selection Box

3.8 Event Handling


 An event is an activity that happens on the web document.The following are some
examples of events.

■ The HTML document is loaded to the browser

■ A button on the web page is clicked.

■ A key is pressed.

■ A button (left/right) button of the mouse is clicked.

■ An option is selected on the selection box of a form.

■ A radio button is selected.

■ A Check box is set or reset.

■ Mouse is dragged.

■ Mouse is moved over an element.


 In general an event is a relationship between the user and the web document.
 Javascript defines the set of events and a mechanism to handle that.

3.8.1 Event Object


 Javascript considers every event as an object and hence with some properties.
 The properties of the event object contains the information (details) about the event Table
5.5.1 illustrates some events and the properties.
Table 5.5.1 Some Events and Their Properties

FZif user clicks the left button of the (X. Y) co-ordinate of the point of click with
mouse. reference to the screen.
ASCH value of the key pressed.
77ie user presses a key.

 Table 5.5.2 shows a list of events recognized by Javascript.


 Notice that the events are specific to the browser.
 So we use the symbol NS and IE to denote if they are recognized by Netscape and Internet
Explorer.

Table 5.5.2 Events Supported by Javascript

Event IE Target Cause Properties


NS
Abort NS image The user aborts the loading of the
IE image by clicking another link or
the stop button
Blur IE window User removes input focus from
NS frame Window .frame or form Type
all form elements
Click NS button The user clicks with the left Target
IE radio button button of the mouse Type
check box ClientX
submit button ClicntY
reset button SrcElement
<a> link
Change NS text field User changes value of field Target
IE text area Type
select list ClientX
ClientY
SrcElement
DblClick NS document The user double clicks with Target
IE area left button of mouse Type

(Con id.)
3.8.2 Double Click (dblclick) Event

A dblclick event occurs when the user double clicks the left button of the mouse. In the
following example, an alert message is thrown when the user double clicks anywhere in the
document.
<html>
<h4>Web Technology book by Dr. C. Xavier<br>
<h5> This is a sample page to illustrate Double click
event.<br><br> Double click in the document </h5>
<body ondblclick='alert(‘Hi..You have done a Double Click’)”>
</body>
</html>

The output is shown in Figure 5.18.

Figure 5.18 Double Click Event

3.8.3OnHelp Event
A Onhelp event occurs when the user presses the Fl key. Let us see an example to illustrate
this.
<html>
<h4>Web Technology book by Dr. C. Xavier<br> </h4>
<h5> This is a sample page to illustrate OnHelp... Press Fl key for help
<br><br> </h5>
<body>
<h5>Type the city code </h5>
<input type«”text” name=”Citycode”
onHelp=”alert('Citycode Chennai-CH \n Delhi-DL \n Mumbai-MB \n')”>
</body>
</html>

The output is shown in Figure 5.19.

Figure 5.19 On Help Even



3.8.4 Key press Event
 A keypress event occurs when the user continues pressing a key.
 Let us see an example to illustrate this event.
<html>
<h4>Web Technology book by Dr. C. Xavier<br>
<h5> This is a sample page to illustrate Keypress.<br><br> Press a key in the
document </h5>
<body onkeypressa* alert('Hi..you have pressed a Key')*
</body>
</html>

The output is shown in Figure 5.20.

Figure 5.20 Key Press Event

3.8.5 KeyUp Event


 A KeyUp event occurs when the user releases a keypress.
 The example shown below illustrates this event.
<html>
<h4>Web Technology book by Dr. C. Xavier<br>
<h5> This is a sample page to illustrate Key Up.<brxbr> Press any key and
release it in the document </h5>
<body onKeyUp="alert('Hi...You have done KeyUp event')*>
</body>
</html>

The output is shown in Figure 5.21.


Figure 521 Key Up Event

3.8.6 Key Down Event


 A KeyDown event occurs when the user initiates a key press.
 An example is shown below 
<html>
<h4>Web Technology book by Dr. C. Xavier<br>
<h5> This is a sample page to illustrate Key Down.<brxbr> Press any key in
the document </h5>

<body onKeyDown**alert(*Hi...You have done Key Down Event*)*>


</body>
</html>
The output is shown in Figure 5.22.
Figure 5.22 Key Down Event

3.8.7 Change Event


 When the user selects an item from a Select Box. a change event occurs.
 So we can call the onChange even handler in the select box definition.
 The definition of select box will appear as illustrated below:
< select name = onChange = >
 We rewrite the HTML document. given i i telephone directory example in section
5.4.4 to illustrate the change event.
 In the HTML page in section 5.4.4 we had a button "Get Number” and the phone number was
displayed only when the user clicks the button.
 So, we used the onClick event handler.
 How ever we can accomplish the same functionality without the button. When the user selects a
name.
 A change event occurs. So, we can call the onChange event handler in the select box itself.

The definition of select box will appear as follows:


< select name = nameBox onChange =getNumber(this. form)>

The revised HTML document is shown below:


PHONE NUMBER :<input type = text name = PhoneNumberxbr>
<br><brxhrxbrxbr>
</form>
</body>
</html>

The output is shown in Figure 5.23.

Figure 523 Change Even

3.8.8 Focus Method


 The method focus() is used to set the cursor focus to the desired object in the form.
 In the following example the method is used to focus on the Account text field or city text field
depending on the selection.
 In this document once the user clicks the Name search button the focus is set to Name field
similarly it is done for Account search and City search.
The HTML document is given below:

The output is shown in Figure 5.24.


Figure 524 Focus Method

3.8.9 The Select() Method


 The selectO method is used to select the text in a text field. This example illustrates the select
and focus on an object.
 In this document we have a text box and a submit button.
 The text box is initialized to St.Xavier’s College .
 On clicking the ‘Enter College’ button the setfocus () function is called.
 This function selects the value of text box and also sets focus to it.
The HTML document is given below:
<html>

<head>

<script type=*text/javascript*> function setfocus()

<

document.forms[0].college.select() document.forms[0].college.focus()

</script>

</head>

<body>

<h2>Please click the button and then type the name of the college</h2>

<form>
<input type*"text" name*"college* size*"30’ value*"St.Xavier's College">
<input type«"button" value»."Enter College" onclick*"setfocus () ">
</form>
</body>
</html>

The output is shown in Figure 5.25.

Figure 5.25 Select Method

3.9 Browser Object


 Javascript has the capability to identify the properties of the browser object.
 This example illustrates the retrieval of browser details like Browser name.
 Browser version. Platform etc.
The HTML document is given below:
The output is shown in Figure 5.26.

Figure 5.26 Browser Object


3.10 Submit Event and Data Validation
 This example illustrates Data validation when the submit button is pressed.
 In this document we have 3 Text boxes and a Submit button. The three Text boxes are Email-id,
Age and Name.
 The email-id Text box has to contain @ symbol.
 Age should be greater than one and less than or equal to 150 and Name shouldn't exceed 10
Characters.
 If the Email-id does not contain @ sym-bol an alert message is fired.
 Similarly for Age and Name the corresponding alert message is fired.
The HTML document is given below:
The output is shown in Figure 5.27 .

Figure 5.27 Data Validation on Submit


3.11 Parselnt() Function
 This function is used to convert a text input into integer.
 For example, if f is a form and age is a text input field, the following converts the value of
the text input field into an integer variable a.
a = parselnt(f.age.value)

Since Javascript is a free form language we can also write.


a = f.age.value
 This will also assign the integer value if typed correctly.
 If the user types a text value (not a number) the browser will assign the string value to a.
So, it is always safe to use the parselnt () function.

3.12 ParseFloat() Function


 This function returns the equivalent float value of the number.
 If weight is the name of a text input field in a form called f then the following converts the
weight typed into proper float value and assigns to the variable w.
w = parseFloat(f.weight.value)

Notice that Javascript is a free form language and so we can also write
w = f.weight.value

 However if the user types an invalid text value then w accepts the text value and w becomes a
string variable.
 So it is safe to use parseFloatO function whenever float value input is given.

3.13 Recursive Functions


A function is recursive if it calls itself. Factorial of a number is a classic example to illustrate
recursive functions. Factorial of a number n is l*2*3*...n.
That is,
Factorial (0) = 1 (This is by definition)
Factorial (1) = 1
Factorial (2) = 1*2 = 2
Factorial (3) s /*2*3=6
Factorial (4) s 24
Factorial (5) a 120

If one closely investigates this calculation the following fact can be found.
Factorial (n) = n* Factorial (n-1)
In other words, multiplying the factorial of (n•1) gets factorial of a number n by n. This
leads to the following definition.
Factorial (n) =1 if n=0 or n=l.
= n * Factorial (n-1) if n>l.
We can write this function in Javascript as follows:

We use the form shown in Figure 6.1 for this problem.

Figure 6.1 Factorial Form


This form has one text input field for the user to type the number. There is a button.
There is another text input field for displaying the result. They are listed below:
1. Input text field to input the number. The name of this field is a.
2. Input text field to output the factorial value. The name of this field is b.
3. A button to click after typing the number. When this button is clicked, a method
calc (this form) is called to calculate the factorial and display the result in b.
The Output is shown in Figure 6.2.

Figure 6.2 Factorial Output

--------------------------UNIT III COMPLETED----------------------------


UNIT-IV

Server Side Script with JSP: Client Responsibilities -


Server Responsibilities - Introduction to JSP – JSP
Architecture - JSP Servers - JSP Tags - Request Object -
Response Object - JSP Page.

Server Side Script with JSP


 While designing a HTML form we need to understand how the page is to be presented to
the Browser.
 Notice that the Web browser is the Client and the Web Server is the Server as illustrated in
Figure 7.1

4.1 Client Responsibilities


The Client has the following responsibilities:
 Presentation:
 Understands the HTML tags and presents the page to the user accordingly.

 DataValidation:
 Does the data validation as defined in the Javascript.
 For example if a field of a form is an input of age the client side Javascript validates
the age to have a meaningful value
 Service Request:
 The Client makes a request to the Server for appropriate service.
 The technologies involved in the client side operations are HTML and Javascript. In the place
of JavaScript.
 VBScript or JScript can also be used.

4.2 Server Responsibilities


 Server is the location of business intelligence.
 All the business processes are executed in the server.
 These business processes are programmed in the executable form using any of the following
technologies:
1. CGlPerl Scripts
2. Java Server Pages (JSP)
3. Active Server Pages (ASP)
4. Servlets
 In this chapter we deal with Java Server Pages (JSP).
 JSP is almost Java with a few tags. These are illustrated in this chapter.

4.3 Introduction to JSP


 Java Server Pages (JSP) technology provides a simplified, fast way to create web pages that display
dynamically generated content.
 The JSP specification, developed through an industrywide initiative led by Sun Microsystems, defines
the interaction between the server and the JSP page, and describes the format and syntax of the page.
 A JSP page is a page created by the web developer that includes JSP technology specific and
custom tags in combination with other static (HTML or XML) tags.
 A JSP page has the extension .jsp. This extension signals to the web server that the JSP engine will
process elements on this page.
 JSP pages use XML tags and scriptlets written in the Java programming language to encapsulate the logic
that generates the content for the page.
 It passes any formatting (HTML or XML) tags directly back to the response page.
 In this way, JSP pages separate the page logic from its design and display.
 JSP technology is part of the Java technology family.
 JSP pages are compiled into servlets and may call JavaBeans components (beans) or Enterprise
JavaBeans components (enterprise beans) to perform processing on the server.
 As such, JSP technology is a key component in a highly scalable architecture for web based applications.
JSP pages are not restricted to any specific platform or web server.
 The JSP specification represents a broad spectrum of industry input.
 A JSP engine interprets tags, and generates the content required for example, by calling a bean, accessing
a database with the JDBC API or including a file.
 It then sends the results back in the form of an HTML (or XML) page to the browser.
 The logic that generates the content is encapsulated in tags and beans processed on the server.
 Pages built using JSP technology are typically implemented using a translation phase that is performed
once, the first time the page is called.
 The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls
to the page have very fast response times.

4.4 JSP Architecture


 JSPs are built on top of SUN’s Servlet technology.
 JSPs are essentially as HTML page with special JSP tags embedded.
 These JSP tags can contain Java code.
 Figure 7.2 illustrates how a JSP request is processed by a Web browser.
 The following are the precise steps involved in the process.

4.4.1 Steps Required for a JSP Request

Client: Web Browser Web Server Machine


Figure 7.2 JSP Server

 The user goes to a web site made using JSP. The user goes to a JSP page (ending with
.jsp). The web browser makes the request via the Internet.
 The JSP request gels sent to the Web server.
 The Web server recognizes that the file required is special (.jsp). therefore passes the
JSP file to the JSP Servlet Engine.
 If the JSP file has been called the first time, the JSP file is parsed, otherwise go to step 7.
 The next step is to generate a special Servlet from the JSP file. AE the HTML required is converted to
print In statements.
 The Servlet source code is compiled into a class.
 The Servlet is instantiated, calling the init and service methods.
 HTML from the Servlet output is sent via the Internet.
 HTML results are displayed on the user's web browser.

4.5 JSP Servers


 There are many JSP capable web servers available, most of which can be downloaded for free
evaluation and/or development. Some of them are:
 Java Web Server
 WebLogic from BEA
 WebSphere from IBM
 Apache Web Server
 Blazix
 ServletExec
 JRun

4.5.1 Booting the Web Server


 The web server must be first started (booted) to get the JSP executed.
 In the case of Java Web Server 2.0 (used in preparation of this book), the web server is booted as follows:

o Open the command Prompt and go to the bin folder of the web server. C:\Java
Web Server 2.0\bin.

o Type the command http d and press enter This is illustrated in Figure 7.3
4.5.2 Placing the JSP File
The JSP file must be created and stored in the following folder
C:\JavaWebServer2.O\public_html
Consider the following JSP file.
<html>
<head>
<title>My first JSP page
</title>
</head>
<body>
<%”page language^java” %>
<h3>
<% out.printin(“Web Technology book by Dr. C. Xavier”); %>
</h3>
</body>
</html>
We must store this file as book, jsp in C:\javawebserver2.0\public_html folder.

4.5.3 Opening a JSP File

 In order to open the JSP file, open the Browser and type the following in the address
field.http: / /localhost: 8080/book. jsp. This is illustrated in Figure 7.4
Figure 7.4 The First JSP Page

Note:
If the Web Server is running on a different machine, http://localhost:8080 must be replaced by
the URL of the Web Server Machine.
Here is a modified version of our JSP from previous section, adding in a Scriptlet.
<%0 page import”java.util.” %>
<HTML>
<BODY>
<%System.out.printlnt “Web Technology Book by Dr. C. Xavier” );
java.util.Date d « new java.util.Date();System.out.println(d);%>
Hello! The Date and time now: <%« d %>
</BODY>
</HTML>

Note:
 If you run the above example, you will notice the output from the 'System.out printin” on the server log
and not in the Browser.
 By itself a scriptlet does not generate HTML.
 This is shown in Figure 7.5 and Figure 7.6. If a scriptlet wants to generate HTML, it can use a
variable called “out”.
 This variable does not need to be declared.
 It is already predefined for scriptlets, along with some other variables.
The following example shows how the scriptlet can generate HTML output.
<%@ page import**java.util.** %>
<HTML>
<BODY>
<%System.out.printlnt “Web Technology Book by Dr. C. Xavier”);
java.util.Date d « new java.util.Dated ;
System.out.println(d);%>
Hello! The Date and time now:
<%
out.println(d);
%> </BODY>
</HTML>

 We get the same output as the previous one.


 Here, instead of using an expression, we are generating the HTML directly by printing to the 'out’
variable.
 The ‘out’ variable is of type javax.servlet.jsp.JspWri ter.

4.6 JSP Tags


JSP supports four main tags. They are
1. Declaration tag
2. Expression tag
3. Directive tag
4. Scriptlet tag
5. Action tag

4.6.1 Declaration tag (<%! %>)


 This tag allows the developer to declare variables or methods.
 Before the declaration you must have <%! . At the end of the declaration, the developer must have
%>.
 Code placed in this tag must end in a semicolon (;).
 Declarations do not generate output so are used with JSP expressions or scriptiets.

Example
<%!
private int counter =0 ;
private String get Account I int accountNo);
%>

4.6.2 Expression Tag ( <%= %>)

 This tag allows the developer to embed any Java expression and is short for out
.printin ().
 A semicolon (; ) does not appear at the end of the code inside the tag. For example, to show the
current date and time.
Date: <%= new java.util.Date () %>

4.6.3 Directive Tag ( <%@ directive ... %>)


 A JSP directive gives special information about the page to the JSP Engine. There are three main types
of directives:
1. page-processing information for this page
2. Include-files to be included.
3. Tag library-tag library to be used in this page.
 Directives do not produce any visible output when the page is requested but change the
way the JSP Engine processes the page.
 For example, you can make session data unavailable to a page by setting a page directive
(session) to false.
4.6.3.2 Page Directive
 This directive has 11 optional attributes that provide the JSP Engine with special processing
information.

4.6.3.2 Include Directive


 This allows a JSP developer to include contents of a file inside another.
 Typically include files are used for navigation, tables, headers and footers that are common to multiple
pages.
 Two examples of using include files:
 This includes the html from privacy. html found in the include directory into the current jsp page.
<%0 include file = 'include/privacy.html' %>
Or to include a naviagation menu (jsp file) found in the current directory.
<%0 include file = 'navigation.jsp' %>

4.6.3.3 Tag Lib Directive


 A tag lib is a collection of custom tags that can be used by the page.
<%0 taglib uri tag library URI' prefix « 'tag Prefix' %>
 Custom tags were introduced in JSP 1.1 and allow JSP developers to hide
complex server side code from web designers.

4.6.4 JSP Scriptlet <% java code %>


 Scriptlet tag allows to write Java code into JSP file.
 JSP container moves statements in _jspservice() method while generating servlet from jsp.
 For each request of the client, service method of the JSP gets invoked hence the code inside the
Scriptlet executes for every request.
 A Scriptlet contains java code that is executed every time JSP is invoked.

Syntax

<% java code %>

Here <%%> tags are scriplets tag and within it, we can place java code.
4.6.5 Action
 JSP actions use the construct in XML syntax to control the behavior of the servlet engine.
 We can dynamically insert a file, reuse the beans components, forward user to another
page, etc. through JSP Actions like include and forward.
 Unlike directives, actions are re-evaluated each time the page is accessed.

Syntax:

<jsp:action_name attribute="value" />

 In this tutorial, you will learn about Actions. Actions are used for controlling the behavior
of servlet engine.

There are 11 types of Standard Action Tags as following:

4.6.5.1 jsp:useBean:

 This action name is used when we want to use beans in the JSP page.
 With this tag, we can easily invoke a bean.

Syntax

<jsp:useBean id="" class="" />

4.6.5.2 jsp:include

 It also used to insert a jsp file into another file, just like include directive.
 It is added during request processing phase

Syntax

<jsp:include page="page URL" flush="true/false">

4.6.5.3 jsp:setProperty

 This property is used to set the property of the bean.


 We need to define a bean before setting the property.

Syntax:

<jsp:setproperty name="" property="" >

4.6.5.4 jsp:getProperty

 This property is used to get the property of the bean.


 It converts into a string and finally inserts into the output.
Syntax:

<jsp:getAttribute name="" property="" >

4.6.5.5 jsp:forward:

 It is used to forward the request to another jsp or any static page.


 Here the request can be forwarded with no parameters or with parameters.

Syntax:

<jsp:forward page="value">

4.6.5.6 jsp:plugin:

 It is used to introduce Java components into jsp, i.e., the java components can be either an
applet or bean.
 It detects the browser and adds <object> or <embed> tags into the file.

Syntax:

<jsp:plugin type="applet/bean" code="objectcode" codebase="objectcodebase">

4.6.5.7 jsp:param:

 This is child object of the plugin object described above


 It must contain one or more actions to provide additional parameters.

Syntax:

<jsp:params>
<jsp:param name="val" value="val"/ >
</jsp:params>

4.6.5.8 jsp:body

 This tag is used to define the XML dynamically i.e., the elements can generate during request
time than compilation time.
 It actually defines the XML, which is generated dynamically element body.

Syntax:

<jsp:body></jsp:body>

4.6.5.9 jsp:attribute

 This tag is used to define the XML dynamically i.e. the elements can be generated during request
time than compilation time
 It actually defines the attribute of XML which will be generated dynamically.
Syntax:

<jsp:attribute></jsp:attribute>

4.6.5.10 jsp:text

 It is used to template text in JSP pages.


 Its body does not contain any other elements, and it contains only text and EL expressions.

Syntax:

<jsp:text>template text</jsp:text>

4.6.5.11 output:

 It specifies the XML declaration or the DOCTYPE declaration of jsp


 The XML declaration and DOCTYPE are declared by the output

Syntax:

<jsp:output doctype-root-element="" doctype-system="">

4.7 Request Object


 A request in serverside processing refers to the transaction between a browser and the
server.
 When someone clicks or enters a URL, the browser sends a request to the server for that
URL and shows the data returned.
 A request object contains the following data with it.
 Browser information
 The file (URL) the browser wants from the server,
 If the request is coming from pressing a SUBMIT button of a form, the information the user has entered in the
form fields.
The request object is of type javax.servlet.http.HttpServletRequest. All the methods of this class can be
used on the request. Let us see a few usages here.

 In this example the JSP request variable is used to obtain information from the request as
sent by the browser.
<% String agestring = request.getParameter('age'); %>
Age of the person » <%= ageString %>
 This code scriptlet is storing the parameter age in the string agestring.
 In this example we illustrate the use of getParameterO method of the request object. Consider the
following HTML form, which has a text field for typing the name.
<html>
<head>
</head>
<body>
<formname='phoneEnquiry' action='http://prof2:8080/PhoneDirectory.jsp' cinput
type='text' name='name'>
Cinput type='submit' value='Find Phone Number*>
</form>
</body>
</html>
 The user can type the name of the person whose phone number is to be found.
 Notice that the name of the text field is “name”.
 When the user types the name and presses the submit button “Find Phone Number" the browser
submits the request to the Web Server to service the request with the help of the JSP page
PhoneDirectory JSP.
 Now we can send the name given and the phone number ph to the browser as
follows:
out.printIn('<center>'”namegiven”'<br>');
out.printin('Name :'”namegiven” '<br>');
out.printIn('Phone :’ph+'<br>');
 For simplicity we have not fully dealt with the case when the name doesn’t match with
the five known names.
 The complete JSP PhoneDirectory. jsp is shown below:
<html>
<head>
<title>Phone Directory</title>
</head>
<body bgcolor=bisque text«black>
<hrxh2>
<pre>
<%
int ph=0;
String namegiven=request. get Parameter ('name');
String[]name « {'Aparna', 'Uma', 'Anitha', 'Kamal',
'Rajini'};
int[]phone={26549876, 24356786, 27856456, 21345244, 27856432};
for (int i«0;i<5;i*+)
if (namegiven.equals(name[i]))
{
ph=phone[i];
}
out.printin('<center>””namegiven<br>');
out.printin('Name :'>namegiven>'<br>');
out.printin('Phone :'+ph+'<br>'};
%>
</h2>
</pre>
<br><hr>
</body>
</html>
The output is shown in Figure 4.10 for the input name Uma.
The following JSP fragment contains mixed template text and scriptlets.
<% if (Math.random() < 0.5) { %>
Tossing the coin Result: <B>Head</B>
<% ) else { %>
Tossing the coin Result: <B>Tail</B>
<% > %>
This will get converted to as follows:
if (Math.random() < 0.5)
out.printIn('Tossing the coin Result:<B>Head</B>);
else
out.println(“Tossing the coin Result: <B>Tail</B> “);
)

4.8 Response Object


 The response object can be used to affect the response being sent to the browser.
 For instance, you can call response.sendRedirect( anotherUrl ); to send aresponse to the browser that
it should load a different URL.
 This response will actually go all the way to the browser.
 The browser will then send a different request, to 'anotherUrl'.
 This is a little different from some other JSP mechanisms we will come across, for including another page or
forwarding the browser to another page.

4.8.1 Sending e-mail from JSP


 JSP enables the server to generate and send Email.
 To be able to send e-mail. JSP need access to an SMTP server.
 SMTP stands for Simple Mail Transfer Protocol.
 Most of the email on the Internet is sent using SMTP servers.
 Once you have the SMTP server information, you are ready to send email out from your JSP pages.
 Following is a small sample that uses the Blazix Tag library to send an email with an
attachment.

Example 4.8.1 Email Generation


Consider the following HTML page.
<html>
<body bgcolor»breeze>
<form method=post action='sendmail.jsp'>
<h3>
 Now let us write the target JSP. sendMail. jap.
 Assume that your SMTP Mail server is xaviersmtp.com, and [email protected] is your
Email ID.
 In this example I have used the blx tags. The following is the JSP page sendmail, jsp referred
in the HTML form.
<%@ taglib prefix=*blx* uri=*/blx.tld* %>
<HTML>
<BODY>
<%
String email « request.getParameter( 'email' );
%>
<% if ( email = = null II email .equals
(‘’))
{%> Please enter an email address.
<% }
else
{ %>
<blx:email host”xaviersmtp.com ‘from”[email protected]”>
<blx:emailTo><%= emai1 %></blx:emailTo
Thank you for registering with us. You registered
the following name: <%« request.getParameter(
•unamef )

%>

 Your registration was received at <%= new java.util.Date() %> We shall send you
the copy shortly.

 Thank you for your interest. Please find attached the Content pages of the book.

<blx:emailAttach file=’C:\\contents.txt’
contentType+”text/plain”name”'contents.txt/>
</blx:email>
<!— Also write out some HTML —>
 Thank you.A confirmationemail has been sent to <%* email %> <% } %>

</BODY>
</HTML>

4.9 JSP Page


 The JSP Page retrieves data from the database and displays in the choice boxes.
 The algorithm is shown below:

4.9.1 Algorithm for Creating the JSP Page


1. Set the language as Java.
2. Define the JDBC : ODBC Driver and create the driver object.
3. Create a Connection object that connects the forex database table.
4. Read all the records of the table and create Resultset object rs.
5. From the Resultset object retrieve the Country, Currency and store them in String arrays
countryName [ ] and currency [ ].

6. Create a Form with appropriate background color, font settings, four choice boxes and
one Text Field for Amount. Load the Choice boxes with the values countryName [ ] and
currency[] as follows:

6.1 Load the Choice box fromCountry with the values in countryName!).

6.2 Load the Choice box fromCurrency with the values in currency!).

6.3 Load the Choice box toCountry with the values in countryName [ ].

6.4 Load the Choice box toCurrency with the values in currency I ].

7. Based on the user selection the values of fromCountry and toCountry are passed to the
Servlet as hidden variables from and to along with the amt (fromAmount).

----------------------------------------UNIT-IV COMPLETE-------------------------------------------
UNIT – V

JSP with JDBC: Creating ODBC Data Source Name - Introduction to JDBC -
Telephone Directory with JDBC - Servlet Environment and Role - Protocol Support -
HTML Support - Servelt Life Cycle -- HTML to Servlet Communication.

JSP with JDBC


In the previous chapters we have studied how the web application is divided into the Presentation
layer (HTML), Clientside data validation layer (Javascript) and business Processing layer (JSP).
The business logic is implemented using Java language and runs on the server. Most of the business
processes involve database access. The data are normally stored in databases and hence the JSP
pages go through the JDBC (Java Database connectivity) technology to accomplish the business
process. There are usually two layers in the business process:

1. Application layer

2. Database access

The architecture diagram of a typical web application is shown in Figure 5.1

Figure 5.1 A Simple Web Application Architecture

5.1 Creating ODBC Data Source Name

Consider a MS Access Database with name forex.mdb. Assume that it has the structure a shown
in Figure 5.2.
Figure 5.2 Table Forex

Assume that we want to create a Data Source of this database with


Name of ODBC Data Source: forex.
We do the following:
1. In Windows NT or Windows 2000 open the Control Panel from start menu as follows:
Start Settings Control Panel
2. As shown in control panel, select Administrative Tools and open it by double clicking appears.
3. In Administrative Tool Window Select Data Sources (ODBC) and open it by double click ing.
ODBC Data Source Administrator window appears.
4. In ODBC Data Source Administrator window Click Add button. Create New Data Source window
appears.
Create DSN Name

1. Go to control panel

2. Go to Administrative tools

3. Select Data Source(ODBC)


4. Add new DSN name, select add

5. Select Access driver from the list, click on finish

5 In the Create new Data Source Window select Microsoft Access Driver and click Finish. The
ODBC Microsoft Access setup window appears. In this window type the name of the Data Source
(forex) and click select button. Now the Select Database window appears. Now select the database
forex.mdb and click OK. Now the ODBC Microsoft Access Setup window appears showing the
database selected.
6. Give a DSN name, click ok

Figure 5.3 ODBC Microsoft Access setup

Figure 5.4 Select Database window


Figure 5.5 Setup Complete

 Now Click OK in the ODBC Microsoft Access Setup window.


 The ODBC Data Source Administrator window appears showing the new data source forex.
Click OK to finish the process.
 Now the data source forex has been created with the database.
 So we can create the JDBC connectivity using the following statements:

Class.forName("sun.jdbc.odbc.jdbcOdbcDriver");
con =DriverManager.getConnection (“jdbc:odbc:forex","","");

5.2 Introduction to JDBC


 The JDBC technology from Sun Microsystems has base classes (Java Foundation classes) to
connect to any database and process the data.
 A typical JDBC connectivity application does the flowing tasks:
 Creating a database connection and opening it.
 Executing the SQL statement and getting the result set.
 Processing the result set and implementing the business logic.
 processing the connection.
5.3 Telephone Directory with JDBC
 In this section we develop a small web application that works as a Telephone directory.
 A database table has the name and telephone numbers.

Telephone Directory

 We have a HTML page that has a Input Text field and a Submit button.

 When the user enters the name of the person and clicks the submit button the HTML page
submits a request to a JSP page.

 The JSP page called phone.jsp receives the request, extracts the name from the request object,
opens the database table and gets the phone number and sends it to the browser.

5.3.1 JSP Page


 The JSP page opens the database and supplies the telephone number to the browser.
 The following are the activities done by the JSP.

1. Extract the name of the person from the request object. This is done as follows:
String s= request.getParameter ("n");
Here the name n is got from the request object and stored as a String object s.
2. Create the JDBC Connection to the ODBC data source phonedir3. (phonedir3 is a odbc data
source which had already been created). The JDBC Connection is established using the
following Java code:
Class. forName("sun.jdbc.odbc.jdbcOdbcDriver");
cn=DriverManager.getConnection
"jdbc:odbc:phonedir3","","");
3. Create an appropriate SQL statement as a PreparedStatement object. In our case the SQL query must
be "Select * from phone where name=?". In this the filler (?) must be filled by the content of s created
in step 1. We write the Java code as follows:
ps-cn.prepareStatement("select * from phone where name=?"); ps.setString (1,);

Java Servlet
In designing an Internet based application, the intermediate server runs a program to offer useful
middle-ware services between the client and the server. They are called Servlets in Java.

5.4 Servlet Environment and Role

 A servlet is a JavaTM component that can be plugged into a Java-enabled web server to provide
custom services.
 These services can include:
 New features
 Runtime changes to content
 Runtime changes to presentation
 New standard protocols (such as FTP)
 New custom protocols
 Servlets are designed to work within a request/response-processing model.
 In a request/ response model, a client sends a request message to a server and the server
responds by sending back a reply message.
 Requests can come in the form of an

 I HTTP URL
 FTP URL or
 a custom protocol.

 The request and the corresponding response reflect the state of the client and the server at the
time of the request.
 Normally, the state of the client/server connection cannot be maintained across different
request/response pairs.
 However, session information is maintainable with servlets through various means.
 The Java Servlet API includes several Java interfaces and fully defines the link between a
hosting server and servlets.
 The Servlet API is defined as an extension to the standard JDK. JDK extensions are packaged
under javax--the root of the Java extension library tree.
 The Java Servlet API contains the following packages:
 Package javax.servlet
 Package javax.servlet.http
 Servlets are a powerful addition to the Java environment.
 They are fast, safe, reliable, and 100% pure Java. Because servlets plug into an existing server,
they leverage a lot of existing code and technology.
 The server handles the network connections, protocol negotiation, class loading, and more; all
of this work does not need to be replicated! And, because servlets are located at the middle tier,
they are positioned to add a lot of value and flexibility to a system.
5.6 Protocol Support

 The Servlet API provides a tight link between a server and servlets.
 This allows servlets to add new protocol support to a server.
 We will see how HTTP support is provided for you in the API packages.
 Essentially, any protocol that follows a request response-computing model can be implemented
by a servlet. This could include:
 SMTP
 POP
 FTP
 Servlet support is currently available in several web servers, and will probably start appearing
in other types of application servers in the near future.
 You will use a web server to host the servlets in this class and only deal with the HTTP
protocol.
 Because HTTP is one of the most common protocols, and because HTML can provide such a
rich presentation of information, servlets probably contribute the most to building HTTP based
systems.

5.7 HTML Support


 HTML can provide a rich presentation of information because of its flexibility and the range of
content that it can support.
 Servlets can play a role in creating HTML content. In fact, servlet support for HTML is so
common, the javax.servlet.http package is dedicated to support HTTP protocol and HTML
generation.
 Complex web sites often need to provide HTML pages that are tailored for each visitor, or even
for each hit.
 Servlets can be written to process HTML pages and customize them as they are sent to a client.
 This can be as simple as on the fly substitutions or it can be as complex as compiling a
grammar-based description of a page and generating custom HTML.

Inline HTML Generation

 Some web servers, such as the Java Web Server (JWS), allow servlet tags to be embedded
directly into HTML files.
 When the server encounters such a tag, it calls the servlet while it is sending the HTML file to
the client.
 This allows a servlet to insert its contribution directly into the outgoing HTML stream.

5.8 Servelt Life Cycle


The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.

5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes
in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes
the destroy() method, it shifts to the end state.

5.8.1 Servlet class is loaded


 The classloader is responsible to load the servlet class.
 The servlet class is loaded when the first request for the servlet is received by the web container.

5.8.2 Servlet instance is created


 The web container creates the instance of a servlet after loading the servlet class.
 The servlet instance is created only once in the servlet life cycle.

5.8.3 init method is invoked


 The web container calls the init method only once after creating the servlet instance.
 The init method is used to initialize the servlet.
 It is the life cycle method of the javax.servlet.Servlet interface.
 Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException

5.8.4 service method is invoked

 The web container calls the service method each time when request for the servlet is received.
 If servlet is not initialized, it follows the first three steps as described above then calls the service
method.
 If servlet is initialized, it calls the service method.
 Notice that servlet is initialized only once.
 The syntax of the service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException

5.8.5 destroy method is invoked

 The web container calls the destroy method before removing the servlet instance from the
service.
 It gives the servlet an opportunity to clean up any resource for example memory, thread etc.
 The syntax of the destroy method of the Servlet interface is given below:
public void destroy()

5.9 HTML to Servlet Communication


 A web resource application is a combination of static as well as dynamic web resource programs, images,
etc.
 A static web resource resides in server and is executed in client side web browser, e.g., HTML.
 A dynamic web resource program resides in server, is executed in context of server and gives response
back to the client, e.g., servlet, JSP.
 In web application, static web resource takes data from client side and takes it to the dynamic web
resource as per request.
 The dynamic web resource processes the data and sends the response back to client in the form of
response.

 In HTML to servlet communication, when we open the browser window, the browser page is empty.

 First, we enter the HTML (static web resource) that resides in the server.

 After the HTML page is downloaded from the server to the client side browser, the client will be able to
enter the data in the HTML form.
 After submission of the data, request is generated to dynamic web resource.

 Hence, we generate request for the server twice in order to get HTML to servlet communication.

 So far we have sent request to servlet program from browser window by typing request URL in the
browser window in this process to send data along with request we need to add query string to the
request URL explicitly. But this work can be done only by technical people.

 Non technical end users like civil engineer, chemical engineer, kids can't do this work so they need a
graphical user interface to generous request with or without data For that purpose we can use either
Html form page or hyperlink to generous with or without data.

The form page generated request carries form data as request parameters along with request.

5.9.1 Hyperlink based web page to servlet communication

 In this section, we will learn about HTML to servlet communication by using Hyperlink. For
establishing this type of interaction, we have to pass the URL pattern of the servlet as a value of "href
attribute" of the "action tag".
 It is to be noted that when we are using hyperlink, the request is submitted to the servlet using "http get
method".
 Hyperlink are favorable for either of inter or intra linking between the pages, but not for
communication between active resources.
 In other words, only static data can be passed from HTML to servlet and not the dynamic data.

Example 1: <a href="/Srvl">Click Here to go to servlet program</a>


Example 2: <a href="/Srv? UName=Dinesh and Pass=java"> Login </ a>

In second example, the static data UName=King and Pass=Queen will be send to servlet.
 Generally the hyperlink generated request is blank request that means it can not carry any data along
with the request.
 html files of web application must be placed parallel to WEB-INF folder in deployment directory
structure of web application there is no need of configure then in web.xml file.
Example Application (hyperlink-based HTML to servlet program communication)
• WishSrv servlet program generates the wish message based on the server machine current time.
• .html-based web page are always static pages, whereas servlet and JSP program based web pages can be
static or dynamic pages.
Step 1: Prepare the deployment directory structure of web application.
Step 2: Develop the source code of above servlet program or webApplication
• Place servlet program request URL with URL pattern as the value of href attribute.
ABC.HTML
<!-- Web page having hyper links -->
<a href=http://localhost:2020/WishApp/wurl>GET WISHING
</a>

WishSrv.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import Java.util.*;
public class wishsrv extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException ,
IOException
{
//get the printwriter object
printWriter pw=res.getWriter();
res.setContentType("text/html");
//set the mime type response
Calendar cl=Calendar.getInstance();
//give curent date and time
//get cuurent hour of day
int h=cl.get(Calendar.HOUR_OF_DAY);
if(h<=12)
pw.println("<center><font color='red' size=6> GOOD MORNING </FONT>
</CENTER>")' ;
else if (h>17)
pw.println("<center><font color='red' size=6> GOOD AFTERNOON </FONT>
</CENTER>") ;
else
pw.println(.,"<center><font color='red' size=6> GOOD NIGHT </FONT></CENTER>") ;
pw.println (“<center><font color='red' size=6> <a href=' http://localhost :2020/ Wishapp/home.html'>
HOME</a></FONT></CENTER>");
pw,close() ;
}//end of service
}/ / end of class
web.xml
<web-app>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>wishSrv</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/wurl</url-pattern>
</servlet-mapping>
</web-app>

Explanation of the above Program


In this program our aim is to click on a link so that it points to a servlet program and we have to
include that link within the HTML page by using the href attribute of HTML. Within this hrcf tag
we pass the URL pattern of the servlet program.
ABC.html:
First we design the HTML page that is displayed on the browser window. In the HTML program we use
the href attribute, and within this we pass the URL pattern of the servlet program as follows:
<a hrer=http://loclahost :2020!WishApp/WurbGETWISHING
When we click on the GETWISHING link at that time the request goes to the servlet program.
WishSrv.java:
• In the above program first one needs to import all the packages like javax.
servlet. * I j avax.servlet.http. * | java.io.* and java.util. *. Our class WishServ extends from the
HttpServlet class within this class the life cycle method, i.e, service(_,_) is overridden.
• printWriter pw;res.getWriter();
With the help of the PrintWriter class the response print on the browser window.
• res.setContentType(“text/html");
With the help of the setContentType(" _ ")of the ServletResponse interface set the format of the
browser window.
• Calendar cl=Calendar.getlnstance( );
Here we use the Calendar class which is present within the java.util package that is why java.util
package is imported. getInstance( ) is a static method of the Calendar class. Hence this method is
invoked through the class name, i.e., "Calendar class". The return type of the getInstance() is the
object of the Calendar class. So by mentioning" Calendar cl=Calendm·.getInstance( );" we can
create the object of the Calendar class. This getInstance( ) gives the current date and time.
• int h=cl.get(Calendar.HOUR_OF_DAY);
In order to get the current hour of the day we use the constant of the Calendar class, i.e.,
HOUR_OF_DAY which is invoked through the class name. Then by using the get( ) of the
Calendar class we retrieve the current hour of the day and assign it to the variable "h" of int type.
• if(h<=12)
By using the if conditional statement, i.e., if we compare that if(h<=12) if this condition is satisfied
then control enter into the if block and print the message "GOOD MORNING" on the browser
window otherwise the control goes to the elseif block. If the condition of the elseif block is not
satisfied then at last the control moves to the else block and print the "GOOD NIGHT" message
and also print the message "HOME". As in this case within the href attribute we pass the URL
pattern of the home.htm!. When we click on HOME, the home page is opened.
• pw.close();
Then by calling the close() of the PrintWriter class close the PrintWriter stream class.
Step 3: Compile the source files of all servlet programs.
Step 4: Configure all the four servlet programs in web.xml file having four different URL patterns.
Step 5: Start the server (Tomcat)
Step 6: Deploy the web application.
Copy WishApp folder to Tomcat_home \ webapps folder.

-----------------------------UNIT V COMPLETE------------------------------

You might also like