Internet and Web Technology

You might also like

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

UNIT- 1: Internet Basics

UNIT STRUCTURE
1.0 Objective
1.1 Concept of Internet
1.2 Evolution of internet
1.3 Basic concepts
1.4 Communication on the Internet
1.5 Internet Domains
1.6 Internet Server Identities
1.7 Establishing Connectivity on Internet
1.8 Client IP Address
1.9 TCP/IP and its Services
1.10 Web Server
1.11 Web Client
1.12 Domain Registration
1.13 Summary
1.14 Question for Exercise
1.15 Suggested Readings

1.0 Objective
Defense Advanced Research Project Agency (DARPA) of US initiated a research activity that
eventually developed as a system for global data commmunication service known as the Internet.
The internet, today, is being operated as a joint effort of many different organizations. In this
unit, you will learn the basic concepts related to internet as well as the various mechanisms and
technologies involved in the deployment of the internet. Upon completion of this unit, the
readers shall be aware of the basic terms and terminologies, involved devices and mechnaisms
and the applications of the Internet.

1.1 Concept of Internet


The Internet is “the global system of interconnected computer networks that use the Internet
protocol suite (TCP/IP) to link devices worldwide.” It has changed the way we do our daily
chores. The usual tasks that we perform like sending an email, looking up train schedules, social
networking, paying a utility bill is possible due to the Internet. The strucure of internat has
become quite complex and it cannot be reperented as it is changing instanteniously. Every now
and then some resources are being added while some are being romvwd. Internet comprises of
various networks that include public, private, government, business, and academic sectors linked
together using different electronic technologies.It interconnects global networks with local and
vise-versa. The resources of Internet range in both information(including digital documents like
image, video, text etc.) and services (including informatio sharing, email, video conferencing)
domains.

Though the terms Internet and World Wide Web are used interchangeably in lay man terms they
are not the same. It is common practice to say "going on the Internet" whenever we open any
web page on a browser. However, the World Wide Web or the Web is one of the most popular
Internet services available. The Web is a collection of interconnected documents (web pages)
and other web resources, linked by hyperlinks and URLs. It uses HTTP as an underlying
protocol for information transfer which is one of the several other protocols available in
networking theory.

1.2 Evolution of Internet


The Defence Department of US, in 1969, funded a research project for developing a robust
network that should be resilient to even bombing. The main objective was to develop a network
that should be secure and robust enough to withstand even a nuclear attack. This project was
named as the ARPANET. The idea was to have a distributed network in order to avoid attacks on
the central authority. This led to the development of Local Area Network (Local Area Network)
and workstations equipped with the ability to connect to the Ethernet. These local area networks
were eventually connected to the ARPANET. The distributed aspect of the ARPANET catalysed
the rapid evolution of the ARPANET over the next decade. Initially, ARPANET used National
Control Protocol (NCP) as the standard set of rules defining the communication between the
computers connected to ARPANET. However, owing to the rapid development of the information
technology, NCP was replaced by the Transmission Control Protocol/Internet Protocol (TCP/IP).
The TCP protocol fragments the messages into packet streams at the source and performs
reassembly of these packets at the destination. The transmission of these packets from source to
destination is handled by the IP. The IP protocol takes care of the addressing conventions and
ensures the delivery of the packet at the destination across multiple nodes or even multiple
networks. The agile nature of the TCP/IP protocol in handling the communication across multiple
heterogeneous networks attracted the other networks to connect to the ARPANET and employ
TCP/IP as their underlying communication protocol. Eventually, the ARPANET developed into a
large network of networks and is now called as ‘Internet’.

1.3 Basic Concept

1.3.1 What is the Internet?

The Internet is a global collection of computer networks that are linked together by devices
called routers and use a common set of protocols for data transmission known as TCP/IP
(transmission control protocol / Internet protocol). The primary purpose of the Internet is to
facilitate the sharing of information. There are many different tools used on the Internet to make
this possible. Some of the more common tools include email, list servers, newsgroups, telnet,
gopher, FTP, and the World Wide Web. Probably the most popular of all Internet tools is the
World Wide Web.

1.3.2 What is the World Wide Web (WWW)?

WWW stands for World Wide Web. A technical definition of the World Wide Web is − All the
resources and users on the Internet that are using the Hypertext Transfer Protocol HTTP. The
World Wide Web is the universe of network-accessible information, an embodiment of human
knowledge. The World Wide Web is a way of exchanging information between computers on the
Internet, tying them together into a vast collection of interactive multimedia resources. It is a
hypertext interface to internet information resources.
Internet and Web is not the same thing: Web uses internet to pass over the information.

1.3.3 Basic WWW Concepts


The World Wide Web is a way of exchanging information between computers on the Internet,
tying them together into a vast collection of interactive multimedia resources. It is a hypertext
interface to internet information resources.

1.3.3.1 HTTP

HTTP is the short form for Hypertext Transfer Protocol. An example of the standard URL is
http://www.google.com. The prefix http in the URL designates the protocol being used for
communication. The HTTP protocol is used to access hypertext documents on the World Wide
Web.

1.3.3.2 URL

URL refers to Uniform Resource Locator. URLs are used as the address of the documents
available on the World Wide Web. A URL is the fundamental identifier of any resource available
on the web e. g., hypertext pages, images, and sound files. The standard format of a URL has
been specified as –
protocol://hostname/other_information

A protocol is, basically, a specification of the flow of information in a network. The protocol
required for accessing the resources available on the web is called Hyper Text Transfer Protocol
(HTTP). Other protocols supported by the web browsers include telnet, FTP, Gopher, etc. The
name of the protocol is followed by a colon, two forward slashes, and then the hostname. The
hostname refers to the computer having the requested resource. Hostname is followed by a single
forward slash and links to subdirectories or any particular file. The path to the directory holding
the requested file or resource may contain single forward slashes.

1.3.3.3 Website

Website refers to a collection of web pages usually written in markup language. For example:
www.google.com refers to the website of Google having ‘com’ as the domain name. Websites
can be understood as a location on the World Wide Web that holds the resources which people
can request when required. The first or the initial page of any website is known as the home page
of that particular website.

1.3.3.4 Web Server

Websites are usually hosted on a computer which is known as a Web server. These servers
should require constant connectivity with the internet so that the resources stored by them can be
accessed from anywhere in the world. A web server is provided with a unique address which is
required to access the contents of the server. The unique address is the identifier for the server
and is termed as IP Address. These IP Addresses comprise of a series of four numbers separated
by dots or periods. Each number lies between the range of 0 – 255, for example: 192.168.1.1. IP
address of the web server is also required when the URL of the website hosted on that server is
registered on the World Wide Web.

1.3.3.5 Web Browser

Web Browser is a software required to access the resources available on the World Wide Web.
Hence, in order to access any website web browser is required. Examples of web browsers are:
Microsoft Internet Explorer, Google Chrome, Mozilla Firefox, Netscape Navigator, etc.
Navigating through the pages of a website is termed as web browsing or surfing.

1.3.3.6 ISP

ISP is the short form for Internet Service Provider. They are basically the organizations
responsible for providing internet connections to the subscribers. Several ISPs also provide space
on their web servers for hosting website of the subscribers.

1.3.3.7 HTML

HTML refers to Hyper Text Markup Language. It is the development language of the websites
available on the web. HTML can be understood as a subset of SGML (Standard Generalized
Mark-Up Language).

1.3.3.8 Hyperlink

Hyperlinks can be understood as the access points to other resources of the same or different
websites. A hyperlink, sometimes referred to as a link, is a clickable element in an electronic
document used to navigate through the linked resources. Typically, you click the hyperlink to
access the linked resource. Hyperlinks can be in the form of clickable textual links, icons,
buttons, etc.

1.3.3.9 DNS

DNS is the short form for Domain Name System. It is used to provide a mapping between the
name of the requested website and its IP address. Usually, user remembers the name or URL of a
website. When user enters this URL in the web browser, a request is sent to DNS for resolving
the entered URL in terms of its IP address. It is the IP address which will be used to locate the
requested resource on the web. The mapping of the URL and the IP address a website is usually
built during the registration of the domain name.

1.3.3.10 W3C

W3C (World Wide Web Consortium) is an international organization comprising of full-time


staff, member organizations, and the public for the development of Web standards. The inventor
of W3C is Tim Berners-Lee while CEO Jeffrey Jaffe is the CEO of W3C. The main aim of the
W3C community is to streamline the development of the open standards for the web. The
mission of W3C's is to shape the Web to its full potential. W3C is also one of the main standards
body for HTTP and HTML.

1.3.3.11 CLIENTS AND SERVERS


A host machine that requests for a resource on the Internet is treated as client. The machine
and/or software that manages and replies these requests are called as servers. There are different
types of clients like email client, web client, FTP client the corresponding servers are Email
server, web server and FTP server.

1.3.4 IP Addressing
IP addresses refer to the unique identifier associated with each computer on the internet. These
addresses are also called logical address and are used to uniquely identify the communicating
entities on the internet. IP addresses are provided and managed by the Internet Protocol at the
network layer of the OSI model. IP addresses can be of two types: IPv4 and IPv6.
IPv4 uses a 32-bit address having the address space equal to 232. An address space refers to the
total number of addresses that can be used by the protocol. Figure 1.2 shows the format of an
IPv4 address. Two types of notations have been used to represent an IPv4 addresses:
Binary notation: In this notation, the IPv4 address is represented as sequence of 32 bits divided
into 4 octets. Each octet refers to eight bits or 1 byte. Thus, IPv4 addresses are sometimes
referred to as 4-byte address. Eg: 01110101 10001010 000011101 00000010
Dotted-Decimal notation: In order to facilitate easy reading of the IP addresses, they are
sometimes written as a sequence of decimal numbers with each byte separated by a period or dot
(.). Eg: 192.168.1.10.
These IPv4 addresses employ the concept of classes. The strategy to classify the address space
into classes is known as classful addressing. This mechanism splits the address space into 5
classes: A, B, C, D, and E. Examining the first few bits of the binary notation or the first byte of
the dotted-decimal notation of the IPv4 address can help in identifying the class to which the
address belongs. Table 1.1 shows the different classes of IP.
In classful addressing, an IPv4 address is composed of two parts: network id and host id. The
length of these parts vary with respect to the corresponding class. This concept is applicable only
for the addresses of class A, B, and C. For the addresses belonging to class A, the first byte
corresponds to network id while the remaining 3 bytes refer to host id. Similarly, for class B, the
first two bytes refer to network id while the remaining two bytes refer to host id. Finally, for
class C, the first three bytes refer to network id while the remaining one byte indicates host id.
It is the responsibility of the Internet Service Provider (ISP) to assign the IP addresses to the
computers communicating on the internet so as to identify the country or region from which a
computer is connecting to the WEB. The assignment of an IP address may be wither dynamic or
static.
Static assignment of IP addresses corresponds to the manual configuration of IP address on the
computers. However, a dynamic assignment employs a DHCP server that has been configured to
automatically provide IP addresses to the connected hosts.
Class Range Binary Notation Dotted Decimal Notation
From To (Range of First Byte)
Class A 1.0.0.0 127.255.255.255 0xxxxxxx xxxxxxxx 0-127
xxxxxxxx xxxxxxxx
Class B 128.0.0.0 191.255.255.255 10xxxxxx xxxxxxxx 128-191
xxxxxxxx xxxxxxxx
Class C 192.0.0.0 192.255.255.255 110xxxxx xxxxxxxx 192-223
xxxxxxxx xxxxxxxx
Class D 224.0.0.0 224.255.255.255 1110xxxx xxxxxxxx 224-239
xxxxxxxx xxxxxxxx
Class E 240.0.0.0 240.255.255.255 1111xxxx xxxxxxxx 240-255
xxxxxxxx xxxxxxxx
Table 1.1: IP address classes
A Router has more than one IP address because router connects two or more different networks.
But A computer or host can only have one and a unique ip address. A routers function is to
inspect incoming packet and determine whether it belongs to local network or to a Remote
Network, if a local packet is determined then there is no need of routing and if a Remote packet
is determined then it will route that packet according to the routing table otherwise the packet
will be discarded. Figure 1.1 shows the format of an IPv4 Address.

Figure 1.1: IPv4 Address Format

1.4 Communication on the Internet


TCP/IP is the only protocol used to send data all around the Internet. TCP/IP is actually two
individual sections, (TCP) a set of communication protocols and (IP) a unique address. Every
machine connected to the Internet must have an address by which it can be located on the
Internet. This is called the IP address of the machine. For the Internet to function smoothly, no
two machines can have the same IP address. Hence each machine connected to the Internet must
have a unique IP address, which identifies that machine.

The Internet is a worldwide network of networks. As the Internet grew over the years it became
increasingly important to have a governing body, which allocated unique IP addresses to
organizations linked to the Internet. An international body called InterNIC, located in the USA,
is responsible for registering and assigning unique IP addresses to organizations wishing to
manage networks, which will be part of the Internet. A unique IP address therefore points to an
actual computer connected via a gateway to the Internet. This computer is known as a Domain
i.e. a place where information is available. This is a Physical Domain on the Internet.
Conceptually, a Server, which has a permanent IP address (i.e. a Physical Domain), can provide
the following:
• A gateway to other computers to access the Internet
• Information for Internet clients to read
• A physical location on which several Virtual Domains can be hosted
In many cases, when a Web Site provides Internet clients information to read, the site is mounted
as a Virtual Domain on an Internet Server, which is its (host) Physical Domain.
Virtual Domains are identified by a name (e.g. www.microsoft.com). Just like a Physical
Domain needs to have a unique IP address, Virtual Domain Names also need to be unique on the
Internet. All Virtual Domain Names must be registered with InterNIC. One Internet Server may
host several virtual domains. Virtual domains can be conceptualized as sub directories on an
Internet server’s hard disk drive. The information that Internet clients wish to read would be
Files within the sub directory.

When an Internet client connects to an Internet server some software running on the Internet
server must respond to the Internet client’s request for information. The software that runs on an
Internet server and responds to an Internet client’s request for information is called Web Server
software.
An Internet Web server responds to an Internet client’s request for information by going to a
specific sub directory on its hard disk and forwarding a pre-determined file to the Internet client
for the first time. Further, the Web server forwards files to the client depending upon their
corresponding requests. Traditionally, this sub directory on the Internet server is ‘wwwroot’ and
the file automatically picked up and passed to the Internet client for the first time is traditionally
called ‘index.html’.

1.4.1 Ways to Communicate


Growth of mankind began with the advent of communication. We share information, when we
are communicating. Sharing of information can be done locally or remotely. Between
individuals, generally face to face communication is considered as local communication,
whereas communication which takes place over distance comes under remote communication.
The term telecommunication, which includes telephony, telegraphy, and television, means
communication at a distance (tele is Greek for "far").
Data is the information presented in whatever form is agreed upon by the parties creating and
using the data. The exchange of data between two devices via some form of transmission
medium (i.e. wire cable etc.) is known as data communications. To occur data communication,
the communicating devices must be part of a communication system which made up by
combining hardware (physical equipment) and software (programs). A data communication
system is effective if it has the following four fundamental characteristics.
• Delivery: Data must be delivered to the right destination by the system. The Data must be
received only by the intended device or user.
• Accuracy. The accurate data must be delivered by the system. Data which have been
changed during transmission and left uncorrected are unfeasible.
• Timeliness. The delivery of data must be on time by the system. If the data is not
delivered on time then that data is useless. In the case of video and audio, timely delivery
refers to delivering data in the same order as they are produced, and without significant
delay. This kind of delivery is known as real-time transmission.
• Jitter. The variation in the packet arrival time is referred to Jitter. It is the uneven delay in
the delivery of audio or video packets. For example, let us assume that video packets are
sent every 3D ms. If some of the packets arrive with 3D-ms delay and others with 4D-ms
delay, an uneven quality in the video is the result.
There are several ways to communicate over the internet. Some of them are as following.
1.4.1.1 Email
Electronic mail (E-mail) is one of the most famous internet services. In earlier days of the
internet, electronic mail sent short and consist only text messages. People could exchange
messages in a fast way. Now-a-days in e-mail, messages can consist text, audio, images and
video. It provides facility to send one message to one or more recipients. Users can compose,
read and send messages through E-mail.
1.4.1.2 Instant Messaging
To send real time messages from one user to another, Instant Messaging or IM is used. One user
types a message that is conveyed over a network and received by the other user. A specific
program (i.e. Yahoo Messenger or Windows Live Messenger etc.) is used for Instant messaging
between two or more people
1.4.1.4 Social Networking
Social networking is an important way of communication. Users can connect and communicate
to each other using it. Users can make new friends, find users of similar interest and reconnect
with old friends on Social networking websites or applications. Firstly, users need to create a
profile on these websites and customize the privacy policy according to their needs (i.e. who can
see his/her photos, send friend request or post on his/her timeline etc.). Facebook, Myspace,
Twitter, Instagram etc. are the popular social networking applications.
1.4.1.5 Forums
An online discussion site where people can do conversations in the form of posted messages is
known as an Internet Forum or Message Board. In Forums, they have a specific set of jargons
associated with them. For example: a single conversation is known as a “thread” or topic. A
discussion forum has a hierarchical or tree-like structure. In a forum, there can be a number of
sub forms, each of them may contain various topics. Any new discussion within a forum’s topic
is known as thread and as many people as want can reply. It depends on the Forum’s setting that
users can be anonymous or need to register with the forum and to post messages, they need to
log in. Most of the Forums allows users to read existing messages without log in.
1.4.1.6 Audio Conferencing
Audio conferencing is used to connect multiple called parties which are located at different
locations on a single audio conference call. Two or more people can be involved in an audio
conference call at the same time. Audio conference call can be conducted either through the
internet or telephone line. Devices (i.e. phones or computers) which allows sounds to be sent and
received are used for audio conferencing. Audio conferencing needs speakers and microphones
both. For listening purpose, only speakers are needed. But for speaking purpose microphones are
also required.
1.4.1.7 Video Conferencing
People are allowed to communicate with one another in real time interactive audio/video.
Videoconferencing is an example of real time interactive audio/video in which people are
allowed to communicate visually and orally.
In videoconferencing, system is full-motion, two-way, video/audio system which allows two or
more humans to communicate with each other which is located at different places.
Videoconferencing is usually used in business meetings, distance learning and web-based
courses. To make video conferencing success, participants should be able to see, hear and use
meeting tools anyway either they are in the same room or across the other side of the world. Live
broadcast of lectures and seminars are provided by colleges and universities to some of their
students who are not able to travel to class sites. In business meetings, videoconferencing is
useful for employee training, group work or to introduce a new product or service.

1.5 Internet Domains


Machines on the internet are uniquely identified using their corresponding IP addresses.
Similarly, the names assigned to the computers must be unique to avoid ambiguity. A
Namespace refers to the mapping between the names of the machine and their corresponding IP
address. Namespaces can be organized in two ways:
Flat Name Space: This indicates the direct mapping of the IP address to the complete name of
the machine. Names are simply a series of characters having no specific structure.
Hierarchical Name Space: In this name space, every name is composed of several parts. The first
component may refer to the nature of organization, second may indicate name of organization,
third may denote the department in the organization, and henceforth.
Hierarchical name space requires domain name space which is an inverted tree structure with
each level corresponding to a component of the name space. The complete tree shall have only
128 levels, where level 0 refers to the root. Figure 1.2 shows the structure of DNS.

Figure 1.2: Domain Name Space


A domain refers to a sub tree of the domain name space, as shown in Figure 1.3. The domain
name of the root of the sub tree will be the name of the domain. A domain can be further
subdivided into subdomains.
Figure 1.3: Domains
In the context of the Internet, the domain name space (tree) can be classified as:
i. Generic domains
ii. Country domains
iii. Inverse domains
Generic Domains: Generic domains identify the registered hosts as per their general
capabilities. Each node of a such a tree refers to a domain which serves as the index for the
domain name space database. Figure 1.4 shows structure of Generic Domains

Figure 1.4: Generic Domains


Country Domains: Country Domains employ abbreviations of the country. The abbreviations
are limited to two characters, e.g. In for India. Further labels may refer to the specific
organization or other national designations. Consider the following country domain:
anza.cup.ca.us. This refers to De Anza College in Cupertino, California, United States.
Inverse Domains: The inverse domain maps the IP address of the machine to its corresponding
name. Consider, a client requesting some resource from a server. The server may have a list of
authenticated clients. However, the request received from the client has only the IP address of
the client. In such cases, it is required to resolve the IP address to the name of the client so that
the server can verify it with the list of authenticated clients it has.

1.6 Internet Server Identities


In U.S.A registrations are made by InterNIC which is a quasi-government body which issues
unique IP addresses to the internet server. An authority in other countries to provide IP addresses
is also provided by InterNIC. Similarly, in case of India NCST (National Centre of Software
Technology) is given the authority to issue the permanent IP addresses. NCST is also a quasi
government body. This clearly shows that the internet server is situated within India.

Registering A Virtual Domain with InterNIC


Virtual domain usually asks for information like Billing Contact Information, Personal Details,
Administrative Contact Information and Technical Contact Information, and further more. When
a virtual domain name is registered by the company with InterNIC, a unique IP is to be
identified. Generally, the IP address of the Internet server which is unique in nature, is specified
and the Virtual Domain will host it. The registered database of the InterNIC will be scanned to
check the uniqueness of the IP address. The uniqueness of the name will ensure the company or
individual to get information for its acceptance for the name. A period of 30 days is provided to
the company or individual for completing the registration and payment for the registered name.
This registration is valid for a period of 2 years. After completion of 2 years it has to be renewed
by InterNIC on request else the validity of name lapses. In case the name is not unique the
request for registration is rejected and information is given to the company or the individual that
the name is rejected due to duplicity.

1.7 Establishing Connectivity on Internet


The TCP/IP is used as a communication protocol between client and server over the internet.
TCP/IP which is termed as Transmission Control Protocol/ Internet Protocol. It is a
connectionless protocol. This depicts that the TCP/IP is an independent protocol which is
completely working independent of its physical media. VSat, Ethernet, Fiber Optics, VHF/UHF
radio frequencies and the Infrared comprises of the network and can be a heterogeneous mix of
above networking technologies, but TCP/IP behaves transparently to all. The data is broken
down into the datagram which guarantee the correct destination. Here we present some of the
networking technologis:

1.7.1 Telephone Line


Since most new computers are equipped with analog modems, the most common method of
connecting to the internet is represented by them for the first time and most computer users are
familiar to them. The analog data transmitted over the telephone lines is converted into digital by
the modem which is known as modulator/demodulator, the process or reading is called
demodulation while the process of transmitting is called modulation. As we are using analog
phone lines so they are known as analog model as the name depicts use of analog signal.
The offered speed was 14.4 kilobits per second (Kbps), 28.8 Kbps and 33.6 Kbps, and as per
latest information it is 56 Kbps, which is build up in almost every machine. These low-speed
modems are regarded as inconvenient by individuals and small businesses who are surfing the
web with increasing frequency. The importance part to know about the speed is-Fast modem
itself does not allow to connect at a fast speed. For example, 56kbps speed is achieved by 56kbps
modem. Connection speed varies with amount of traffic present on the line which is caused by
number of users in the network.
1.7.2 Leased Line
The telephone company gives the leased line on rent to the customer which is called direct
connection for accessing the internet.
Speed: T-carrier Level (T1) line is a common option, enabling the transmission of data at a speed
of 1.544Mbps. T-1 line has 24 channels each consisting of 64kbps support. Voice or data traffic
can flow through the channel. Most telephone companies allow only fractional T-1 access, they
can consume only a fraction of the channel this is another type of leased line. For T-3 672
individual channels consisting of 64 kbps speed is made up which is also another type of leased
line.

1.7.3 ISDN
A standard telephone line which works over ISDN requires fully digital signal over copper wire.
So, digital to analog conversion is not required this is in the manner of the working of analog
channel. Two lines called B-lines are offered by most of the telephone companies. It offers the
user the flexibility to use different lines for voice and data, or both lines can be used for higher
data rates of 128kbps. B-ISDN offers transmission rates of 1.5mbps. It requires fibre optics
cable.
Speed: At the time of introduction approximately a decade ago, very significant speed advantage
was offered by ISDN over regular modems, which were further limited to 14.4 Kbps or slower.
At earlier time most of these connections did not exist. It was used by people who required faster
internet access and could not use the leased line. The connection range was approximately from
64kbps to 128kbps. But the speed of ISDN does not come close to that of options such as cable
of xDSL.

1.7.4 VSAT
VSAT (Very Small Aperture Terminal) is a satellite communications system that serves home
and business users. A VSAT user requires a box that interfaces between outside antenna with a
transceiver and the user's computer. A signal is send or received by the transmitter from the
satellite. The earth station is used to send and receive the satellite. Each end user is
interconnected with the hub station via the satellite in a star topology. For one end user to
communicate with another, each transmission has to first go to the hub station which retransmits
it via the satellite to the other end user's VSAT. VSAT handles data, voice, and video signals.
VSAT is signed up by user both by home users who uses a large service such as DirectPC and by
operating a leased line of their own by private companies such as VSAT systems. A number of
advantages over the terrestrial system is provided For private applications, companies can have
total control of their own communication system without dependence on other companies.
Business and home users also get higher speed reception than if using ordinary telephone service
or ISDN.

1.7.5 RF link
A radio frequency (RF) signal refers to a wireless electromagnetic signal used as a form of
communication, if one is discussing wireless electronics. Radio waves are a form of
electromagnetic radiation with identified radio frequencies that range from 3kHz to 300 GHz.
Frequency refers to the rate of oscillation (of the radio waves.) RF propagation occurs at the
speed of light and does not need a medium like air in order to travel. RF waves occur naturally
from sun flares, lightning, and from stars in space that radiate RF waves as they age. Humankind
communicates with artificially created radio waves that oscillate at various chosen frequencies.
RF communication is used in many industries including television broadcasting, radar systems,
computer and mobile platform networks, remote control, remote metering/monitoring, and many
more.
Wireless RF can be a fantastic option for providing high-speed links (up to 100Mb) between
offices in a multisite organisation. It is also a very effective solution in providing broadband
speeds to remote locations or where cabling isn’t easy or available.
This technology will permit linking of company sites together for faster server/email/file access,
or even CCTV access. Wireless RF can also be used for a company’s primary internet
connection.
The benefits of this system are obvious to those customers who suffer because of their remote
location or that have a demand for significant traffic between satellite offices.

1.8 Client IP Address


An IP address which is called the Internet Protocol address is assigned as a numerical label to
every device that are on a network, for communication it uses the internet protocol. The two
principle functions served by IP address are i) network or host interface identification ii) location
addressing.

1.8.1Client IP Addresses Assignment


A permanent IP address is not necessarily required by the computers (Internet Clients) that only
read offered information. A client requires a unique IP address when it log on to the internet. The
internet server is addressed by the IP, for an accurate reply. The client is connected to the
internet via ISP (Internet Server provider), then a temporary assignment of unique IP address is
made to the client device. VSNL (Videsh Sanchar Nigam Limited) has been a major provider in
India for a very long time. When a client starts the internet connection via VSNL, a dynamic IP
is allocated to the client and then the client successfully login.

1.8.2 ISP’s Task of Assigning IP Addresses


ISP’s purchase a block of unique IP addresses from internationally recognized networking
bodies. Thus, whenever a client logs into the Internet via an ISP’s Server, one of these unique IP
addresses is temporarily assigned to the computer, which logs in. The maximum number of
computers that can log into an ISP Server and access the Internet is therefore limited to the block
of unique IP addresses purchased by that ISP from the international networking body.
1.8.3 Getting a Temporary IP Address
For a client being a windows machine, for getting an IP address dynamically from DHNS server
of the ISP which is VSNL IP as discussed above. A dial-up line and a modem is used by the
client for getting logged in. When a client has logged in, the client machine is allocated an IP
address from the block of assigned IP addresses, for a logged in device. Once we log on to the
internet a unique IP address is assigned, other computers on any network can easily
communicate by knowing the client IP address i.e. the visibility of all the clients are now open to
one another, by having a unique IP through the server.

1.8.4 Resolving Domain Names


When a browser software is used to communicate with any IP address, the Server’s domain name
is used to send out broadcast through the client. This request is first intercepted by the ISP. The
request is then routed to a root server of InterNIC. The domain name is usually mapped to root
server in the InterNIC host file. Finally, the ISP server receives this host file. This IP address is
then passed back to the client’s browser. A request is broadcasted from the client’s browser to
connect using its IP address directly to the Internet Server. When the internet server receives this
request, it sets up a link between the client and the server. The client is connected to the virtual
domain by the software used for communication between the client and the server.
The first HTML page is delivered to the client once a client is connected to the appropriate
domain which is frequently Index.html or Index.htm and we can begin the browsing of the
specific domain. For instance, if any other client is connected via same IP through the same ISP
a cache of IP address will be maintained with ISP. The internet server unique IP address is
already maintained by the ISP. Hence the call is routed to appropriate internet server.

1.8.5 Internet Address Structure


For the client browser the keyed structure of an Internet Server is displayed as:
http://www.microsoft.com where http protocol is used for communication, www depicts World
Wide Web, Microsoft is used as the registered domain name of the internet server and com is
used for the commercial services provided to the client. For speeding up the access, 127.57.13.1
can be directly used as IP instead of miscrosoft.com, which is the domain name.

1.9 TCP/IP and its Services


The entire internet protocol suite -- a set of rules and procedures -- is commonly referred to as
TCP/IP, though others are included in the suite. TCP/IP specifies how data is exchanged over the
internet by providing end-to-end communications that identify how it should be broken into
packets, addressed, transmitted, routed and received at the destination. TCP/IP requires little
central management, and it is designed to make networks reliable, with the ability to recover
automatically from the failure of any device on the network.
The two main protocols in the internet protocol suite serve specific functions. TCP defines how
applications can create channels of communication across a network. It also manages how a
message is assembled into smaller packets before they are then transmitted over the internet and
reassembled in the right order at the destination address.
IP defines how to address and route each packet to make sure it reaches the right destination.
Each gateway computer on the network checks this IP address to determine where to forward the
message

1.9.1 How TCP/IP works


TCP/IP uses the client/server model of communication in which a user machine (a client) is
provided a service (like sending a webpage) by another computer (a server) in the network.
Collectively, the TCP/IP suite of protocols is classified as stateful, which means each client
request is considered new because it is irrelevant to previous requests. Being stateless frees up
network paths so they can be used continuously.
The transport layer itself, however, is stateful. It transmits a single message, and its connection
remains in place until all the packets in a message have been received and reassembled at the
destination. Figure 1.5 represents the TCP/IP Protocol Suite.

1.9.2 TCP/IP model

Figure 1.5: TCP/IP Protocol Suite


1.9.2.1 The Network Interface layer
The Network Interface layer (also called the Network Access layer) is responsible for placing
TCP/IP packets on the network medium and receiving TCP/IP packets off the network medium.
TCP/IP was designed to be independent of the network access method, frame format, and
medium. In this way, TCP/IP can be used to connect different network types. These include LAN
technologies such as Ethernet and Token Ring and WAN technologies such as X.25 and Frame
Relay. Independence from any specific network technology gives TCP/IP the ability to be
adapted to new technologies such as Asynchronous Transfer Mode (ATM).
The Network Interface layer encompasses the Data Link and Physical layers of the OSI model.
Note that the Internet layer does not take advantage of sequencing and acknowledgment services
that might be present in the Data-Link layer. An unreliable Network Interface layer is assumed,
and reliable communications through session establishment and the sequencing and
acknowledgment of packets is the responsibility of the Transport layer.
1.9.2.2 Network Layer
The network layer is responsible for addressing, packaging, and routing functions. The core
protocols of the Internet layer are IP, IGMP, ICMP and ARP. The Internet Protocol (IP) is a
routable protocol responsible for IP addressing, routing, and the fragmentation and reassembly of
packets. The Address Resolution Protocol (ARP) is responsible for the resolution of the Internet
layer address to the Network Interface layer address such as a hardware address.
The Internet Control Message Protocol (ICMP) is responsible for providing diagnostic functions
and reporting errors due to the unsuccessful delivery of IP packets. The Internet Group
Management Protocol (IGMP) is responsible for the management of IP multicast groups. The
Internet layer is analogous to the Network layer of the OSI model.
1.9.2.3 Transport Layer
The Transport layer (also known as the Host-to-Host Transport layer) is responsible for
providing the Application layer with session and datagram communication services. The core
protocols of the Transport layer are Transmission Control Protocol (TCP) and the User Datagram
Protocol (UDP). TCP provides a one-to-one, connection-oriented, reliable communications
service. TCP is responsible for the establishment of a TCP connection, the sequencing and
acknowledgment of packets sent, and the recovery of packets lost during transmission. UDP
provides a one-to-one or one-to-many, connectionless, unreliable communications service. UDP
is used when the amount of data to be transferred is small (such as the data that would fit into a
single packet), when the overhead of establishing a TCP connection is not desired or when the
applications or upper layer protocols provide reliable delivery.
The Transport layer encompasses the responsibilities of the OSI Transport layer and some of the
responsibilities of the OSI Session layer.
1.9.2.4 Application Layer

The TCP/IP model does not have session or presentation layers. No need for them was
perceived, so they were not included. Experience with the OSI model has proven this view
correct: they are of little use to most applications. On top of the transport layer is the application
layer. It contains all the higher-level protocols. The early ones included virtual terminal
(TELNET), file transfer (FTP), and electronic mail (SMTP). The virtual terminal protocol allows
a user on one machine to log onto a distant machine and work there. The file transfer protocol
provides a way to move data efficiently from one machine to another. Electronic mail was
originally just a kind of file transfer, but later a specialized protocol (SMTP) was developed for
it. Many other protocols have been added to these over the years that includes Domain Name
System (DNS) for mapping host names onto their network addresses, NNTP, the protocol for
moving USENET news articles around, and HTTP, the protocol for fetching pages on the World
Wide Web, and many others.

1.9.3 Services of TCP/IP


TCP/IP is a hierarchical protocol made up of interactive modules, each of which provides a
specific functionality. The modules are not necessarily interdependent. The OSI model specifies
which functions belong to each of its layers. The layers of the TCP/IP protocol suite contain
relatively independent protocols that can be mixed and matched depending on the needs of the
system. The term hierarchical means that each upper-level protocol is supported by one or more
lower-level protocols.
At the transport layer, TCP/IP defines three protocols: Transmission Control Protocol (TCP),
User Datagram Protocol (UDP), and Stream Control Transmission Protocol (SCTP). At the
network layer, the main protocol defined by TCP/IP is the Internetworking Protocol (IP); there
are also some other protocols that support data movement in this layer. The application layer in
TCP/IP is equivalent to the combined session, presentation, and application layers in the OSI
model. Many protocols are defined at this layer, some which are described below.
1.9.3.1 Simple Network Management Protocol (SNMP)
It is an Internet Standard protocol for collecting and organizing information about managed
devices on IP networks and for modifying that information to change device behavior. Devices
that typically support SNMP include cable modems, routers, switches, servers, workstations,
printers, and more. The main goal of SNMP is network monitoring for network management
tasks. A management information base(MIB) is maintained that contains entries in the form of
variables that describe the system status and configuration. Managing applications can query and
sometimes even manipulate these variables. It can monitor devices manufactured by different
companies working on different physical networks. It specifies the format of message that is
exchanged between manager and agents. SNMP frees management tasks from the physical
characteristics of devices from the network technologies they use. An important task of SNMP is
monitoring or managing a group of agents that is devices through an administrative device also
known as managers. Each managed system executes a software component called
an agent which reports information via SNMP to the manager. A network management on the
Internet consists of three key components SMI (Structure of Management Information), MIB
(Management Information Base) and SNMP. A typical example of SNMP is shown in Figure
1.6:

Figure 1.6 Working of SNMP


A managed device is a network node that implements an SNMP interface that allows
unidirectional (read-only) or bidirectional (read and write) access to node-specific information.
Managed devices exchange node-specific information with the NMSs. The types of devices that
can be called as managed devices or network elements are switches, routers, cable modems,
hubs, bridges, IP video cameras, access servers, computer hosts etc. An agent is a network-
management software module that resides on a managed device. An agent has local knowledge
of management information and translates that information to or from an SNMP-specific form.
A network management station executes applications that monitor and control managed devices.
NMSs provide the bulk of the processing and memory resources required for network
management. One or more NMSs may exist on any managed network.
1.9.3.2 File Transfer Protocol (FTP)
It is the standard network protocol used for the transfer of computer files between a client and
server on a computer network. FTP uses two connections for a pair of client-server machine; one
is completely dedicated for data flow while the other is dedicated for control information. FTP
users may authenticate themselves with a clear-text sign-in protocol, normally in the form of a
username and password. Anonymous connection is also possible with suitable server
configuration. For secure transmission that protects the username and password, and encrypts the
content, FTP is often secured with SSL/TLS. The first FTP client applications were command-
line programs developed before operating systems had graphical user interfaces, and are still
shipped with most Windows, Unix, and Linux operating systems. Many FTP clients and
automation utilities have been developed for desktops, servers, mobile devices, and hardware,
and FTP has been incorporated into productivity applications, such as web page editors.
1.9.3.3 Domain Name System (DNS)
The essence of this protocol is in linking URLs with IP address and vise-versa. It is
a hierarchical decentralized naming system for computers, services, or other resources connected
to the Internet or a private network. It associates various information with domain
names assigned to each of the participating entities. The major responsibility of this protocol lies
in identifying the unique IP address for a URL that users or humans can remember easily. IP
addresses are needed for locating and identifying computer services and devices with the
underlying network protocols. By providing a worldwide, distributed directory service, the
Domain Name System is an essential component of the functionality on the Internet that has
been in use since 1985. An authoritative name server is designated for each domain. DNS
outsources the responsibility of assigning domain names and mapping these names to
corresponding Internet resources to the authoritative servers. Network administrators may
delegate authority over sub-domains of their allocated name space to other name servers. This
distribution of responsibilities facilitates distributed and fault tolerant service and avoids a single
large central database. The Domain Name System also specifies the technical functionality of
the database service that is at its core. It defines the DNS protocol, a detailed specification of the
data structures and data communication exchanges used in the DNS, as part of the Internet
Protocol Suite. Historically, other directory services preceding DNS were not scalable to large or
global directories as they were originally based on text files, prominently the hosts file.

1.9.4 Advantages of TCP/IP


TCP/IP is compatible with all operating systems, so it can communicate with any other system.
The internet protocol suite is also compatible with all types of computer hardware and networks.
Hence, this is the only protocol used for communication over Internet.
1.9.4.1 Standardization
Although computers are capable of exchanging data with each other using several data transfer
methods, communication by its very definition requires the transferred information to be
understood on the receiving end. A communication protocol is like a language; it enables
computers to communicate with each other so that the receiving computer understands the data
sent to it. TCP/IP standardizes this communication process by offering one universal protocol for
all the computers over the Internet to use in their communication with each other.
1.9.4.2 Interoperability
Just as in human communication, computers may use several different languages to
communicate with each other. Some protocols may be more suitable for use in certain private
networks than TCP/IP. However, TCP/IP enables such networks to be connected to the Internet.
Furthermore, it lets computers and devices with different hardware architectures and running
different operating systems communicate with each other. This means a computer running
Windows can connect to a web server running Linux to browse the website hosted there. It is
quite similar to the use of English as an international language today.

1.9.4.3 Addressing
TCP/IP assigns each computer on the network a unique address called its IP address. Thus, every
computer on the network is uniquely identifiable and information could be sent to it by simply
addressing its IP address. The present implementation of IP addressing is known as IPv4, while a
newer implementation supporting a much larger number of unique addresses called IPv6 is being
developed to replace IPv4.

1.9.4.4 Connection
Communication with TCP/IP starts with a connection being established between the two
computers. This is achieved in a systematic manner, called the three-way TCP handshake. The
computer initiating the communication sends a connection request packet to the other computer.
If the computer is the one with the correct IP address, it sends a packet back. If the first computer
receives that packet, it sends another one to the second computer, the reception of which by the
latter establishes a connection. The information is then exchanged using this established
connection, reducing the risk of the data being compromised.

1.10 Web Servers


Web servers are dedicated computers that uses HTTP to serve Web pages. Web server has an IP
address and a domain name. As by entering URL http://www.webopedia.com/index.html in
browser, it requests to the Web server having domain name, “webopedia.com”. The server in
response, fetches the page named index.html to the browser.
Any computer can act as web server after installing server software on it. There are many Web
server softwares, like public domain software and commercial packages.
1.10.1 Web Server Working
Web server responds to the client's request in either of the two ways:
• Attaching the file with the requested URL and sending it to the client.
• Response generation by invoking script and communicating with database
The figure below explains the working of a Web server.

Figure 1.7 Working of Web Server

1.10.2 Web Server Architecture


Web Server Architecture follows two approaches:
1. Concurrent Approach - It can handle multiple client's requests at the same time. This can be
achieved by following methods:
• Multi-process – The incoming request is distributed among multiple single-threaded child
processes generated from a single process called parent process.
• Multi-threaded - Unlike Multi-process, it creates multiple threaded process.
• Hybrid method - Multiple processes are created and multiple threads are initiated by each
process. Each thread handles one connection. It results in less load on system resources.
Leading Web servers include Apache, nginx from NGNIX, Microsoft's Internet Information
Server (IIS), IBM's family of Domino servers, Novell's NetWare server, Google Web Server
(GWS).
2. Single-Process-Event-Driven Approach - It uses a single event-driven server process to
perform concurrent processing of multiple HTTP requests. It maps a single thread to multiple
connections. The thread handles all events occurring from I/O operations of these connections
and requests. New events are queued and the thread executes loop-dequeuing events from the
queue, process the event, then waits for new events to be pushed.
1.11 Web Client
A web client is a program capable of communicating with Web servers, requesting and receiving
information from them, and processing it for display or other uses. Web browser is a kind of
Web client. The browser at the client computer requests the Web server and the Web server
responds the results on the client's computer or other Internet-enabled device that supports a
browser. A web page can be requested by just entering a URL into address bar.
Web browser supports text, video, audio, animation etc. files. It is browser's responsibility to
interpret commands contained in the web page.
Earlier the web browsers only supported texts but now graphical or voice-based web browsers
are also available. The most common web browser available today are:

Browser Vendor

Internet Explorer Microsoft

Google Chrome Google

Mozilla Firefox Mozilla

Netscape Communications
Netscape Navigator
Corp.

Opera Opera Software

Safari Apple

Table 1.2 Common web browsers available

1.11.1 Web Browser Architecture


There are a number of web browsers available in the market. The capability and structure of the
browser varies depending upon implementation. The most basic components are listed below:
• Controller/Dispatcher – The working is similar to that of control unit in CPU. It takes
input from the keyboard or mouse, translate it and make other services to work based on
input it receives.
• Interpreter – After collecting the information from the controller, it executes the
instruction line by line. Some interpreters are mandatory (HTML) while some are
optional (Java).
• Client Programs – It describes the specific protocols have been designed to access a
particular service.
Figure 1.8 Architecture of a web browser

1.12 Domain Registration


The Internet Corporation for Assigned Names and Numbers (ICANN) is the non-profit
organization that is responsible for the assignment of both IP addresses and domain names. It
also procures other tasks like managing root server and TLD name system management. ICANN
has contractual agreements with both registries and registrars that provide the foundation for the
WHOIS system.
Domain registration is the process of registering a domain name, which identifies one or more IP
addresses with a name that is easier to remember and use in URLs to identify particular Web
pages. The person or organization who registers the domain name is called as Domain name
registrant. The process of registration initializes with applying online to domain registrar or their
resellers. The domain name registrant is bound by the terms and conditions of the registrar with
which it registers its domain name, for instance adhering to a certain code of conduct or
indemnifying the registrar and registry against any legal or civil action taken as a result of use of
the domain name. Some of the responsibilities of domain name registrants that are included in
the terms and conditions are submission of accurate data, payment of registration fees and timely
update of the submitted data.
For domain name to be reachable on the Internet, domain name registrants additionally need to
have their domain names listed on name servers. In case the registrar does not offer this service
or if the domain name registrant has not opted for the same, he/she has to host his/her own name
server.
In some cases, a person or organization who does not wish to have their information listed in
WHOIS may contract with a proxy service provider to register domain names on their behalf. In
this case, the service provider is the domain name registrant, not the end customer.
ICANN accredits certain organizations that are called as Registrars. These organizations are also
certified by the registries to sell domain names. They are bound by the Registrar Accreditation
Agreement (RAA) with ICANN, and by their agreements with the registries. The responsibilities
for registrar that are imposed by the RAA include:
• maintaining WHOIS data
• submitting data to registries
• facilitating public WHOIS queries
• ensuring domain name registrants details are escrowed
• complying with RAA conditions relating to the conclusion of the domain name
registration period
Resellers are the organizations that are affiliated or under contract with registrars. Along with
registration they offer other services like web hosting, email mailboxes etc. Resellers are not
accredited by ICANN, but are bound by their agreements with the registrar(s) whose services
they sell. However, the registrar for whom they are re-selling will still be the sponsor for the
domain name registration and accountable for the domain names sold by the reseller.
While registrars are contracted to conduct the day-to-day business of selling domain name
registrations, registries are responsible for maintaining the registry for each TLD. The
responsibilities of the registries include accepting registration requests (whether from registrars
or directly from domain name registrants), maintaining a database of the necessary domain name
registration data and providing name servers to publish the zone file data (i.e. information about
the location of a domain name) throughout the Internet. A detailed figure representing the
registration process is shown below.

Figure 1.9: Domain Registration Process


1.13 Summary
Internet can be viewed as global system of interconnected networks used for sharing resources
between computing systems. Internet Standard ensures that hardware and software produced by
different vendors can work together. Having a standard makes it much easier to develop software
and hardware that link different networks because software and hardware can be developed one
layer at a time. The most fundamental of the Internet Standards are the ones defining the Internet
Protocol. For transmitting digital data over analog telephone lines modems are used. With the
evolution of technology, certain different types of modems such as analog, digital cable (ADSL)
and ISDN have been developed. Computers connected to the internet are identified using unique
identifiers known as IP address. These addresses are mapped to the names of the computers by
the DNS. The name-address mapping is required whenever some data needs to be transmitted
between one computer to another. Many technologies exist for connecting to the internet, such as
telephone lines, VSAT, RF, etc. The organizations providing the internet services to the users are
known as Internet Service Provider (ISP). Internet has a wide range of applications that can be
utilized by the users such as, emails, video conferencing, etc.

1.14 Questions for Exercise


1. What is Internet? What do you understand by Internet Standards?
2. What are the ways to communicate on Internet?
3. What is TCP/IP? Differentiate Between TCP/IP and OSI Reference model?
4. Explain the TCP/IP model layers and its services?
5. Explain Internet Domain? What is Internet Server Identities?
6. What is Web Server and Web client?
7. What is IP Address? Define classes of IP Address.
8. What is Domain Registration? Explain the steps to register a Domain.

1.15 Suggested Readings


• Behrouz A. Forouzan. 2012. Data Communications and Networking, Fifth Edition. New
York: the McGraw-Hill Companies Inc.
• William Stallings. 2007. Data and Computer Communications Eighth Edition. New
Jersey: Person Education,Inc.
• Douglas E. Comer.2003. The Internet Book. Singapore: Pearson Education Pte. Ltd.
UNIT- 2: Introduction to HTML
UNIT STRUCTURE
2.0 Objective
2.1 HTML
2.2 HTML tags
2.3 Commonly used HTML commands
2.4 Title and footers
2.5 Text formatting
2.6 Text Style
2.7 Lists
2.8 Adding Graphics to HTML documents
2.9 Tables
2.10 Linking Documents
2.11 Frames
2.12 Summary
2.13 Questions for Exercise
2.14 Suggested Readings

2.0 Objective
HTML, an acronym for Hyper Text Markup Language, specifies how the structure of a webpage
will be with the help of various markups. The following unit explains the core concepts of
HTML such as its structure, elements, attributes and core events. It also sheds light on block-
level elements and text-level elements. With the help of this unit, the reader will be able to
understand the basic elements used in HTML and their usage in the formatting of a webpage.

2.1 HTML
HTML, an acronym for Hyper Text Markup Language, specifies how the structure of a webpage
will be with the help of various markups. It is a structured markup language that is used to create
Web pages. Markup languages like HTML bundle together codes which are elements that are
used to represent the structure and format of a document. A user agent, usually a Web browser
which renders (delivers) the document, interprets the meaning of these codes to decipher
(making it into simpler human readable text) how to structure or display a document. The HTML
elements are made up of alphanumeric tokens surrounded by angle brackets, for example, <B>,
<HTML>, <IMG> and <HR> .
Almost all elements possess a pair of tags i.e. a start tag and an end tag. The start tag is a
mnemonic symbol for the element enclosed in ‘<’ ’>’, also known as angle brackets, for
instance, the symbol associated with bolding text is B and the start tag for this purpose is <B>.
An end tag is the same as that for a start tag, but with an exception that there exists a forward
slash preceding the text symbol of start tag: </B>. The instruction applied by an element
modifies whatever content is present between the starting and ending tags:
This is an example of a simple HTML document.
Example:

<! DOCTYPE html>


<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>It is the First Heading</h1>
<p>It is the first paragraph.</p>
</body>
</html>
Output:

2.2 HTML tags


Since HTML is a markup language, therefore, it uses certain tags for formatting the content. The
tags are used with angle braces as in <Tag Name>. Leaving few tags, most tags require to be
supplemented with closing tags</Tag Name>. As for example, the closing tag of
<html> is </html> and the closing tag of <body> is </body>.
HTML document uses the following tags provided in Table 2.1.
Tags Description

<! DOCTYPE…> It represents the document type and HTML


version.
<html> The HTML document itself begins with
<html> and ends with </html>
<head> This tag defines the header of document and it
can keep other HTML tags like <title>
<title> The <title> tag is used inside the <head> tag to
represent document title
<body> It represents the document’s body which keeps
other HTML tags like <h1>
<h1> It defines the heading

<p> This tag represents a paragraph

Table 2.1 HTML Tags


2.2.1 The <!DOCTYPE> Declaration
The <!DOCTYPE> declaration tag is implemented to detect the HTML version used in the
document. The contemporary HTML version is 5 which uses the following declaration:
<!DOCTYPE html>
There are several declaration types which are used in HTML documents on the basis of HTML
version being used. More details will be observed on this during elaboration of <!DOCTYPE...>
tag and the remaining HTML tags.
2.2.2 Heading Tags
HTML documents begin using a heading. Different sizes can be applied for using headings.
HTML features mainly six heading levels using the elements <h1>, <h2>, <h3>, <h3>, <h5>,
and <h6>. The web browser inserts one line before and after a heading for fulfilling the purpose
of displaying it. Here is an illustrated example.
Example:
<!DOCTYPE html>
<html>
<head>
<title> Example of a Heading</title>
</head>
<body>
<h1> Example of heading 1</h1>
<h2> Example of heading 2</h2>
<h3> Example of heading 3</h3>
<h4> Example of heading 4</h4>
<h5> Example of heading 5</h5>
<h6> Example of heading 6</h6>
</body>
</html>
Output:

Sample of Heading 1
Sample of Heading 2
Sample of Heading 3

Sample of Heading 4
Sample of Heading 5

Sample of Heading 6

2.3 Commonly used HTML Commands


2.3.1 HEADERS
In HTML, up to six levels of headers are used in any documents, h1 to h6. Header 1 (h1) is the
largest header and they get successively smaller through header 6 (h6). Below is an example of
<h1> header and how it usually appears in a relation. For rest of the headers we can refer to
section 2.2.2 of this book. Here is an example of a <h1> tag.

Example:

<h1>Example of a header 1 tag</h1>

Output:

EXAMPLE OF A HEADER 1 TAG

2.3.2 PARAGRAPHS
The <p> tag provides a means to structure our text into different paragraphs. Each paragraph
should write in between an opening <p> and a closing </p> tag as shown below in the example.

Example:

<p> it breaks the current line with a trailing blank line

<br>it breaks the current line with no trailing blank line

For our and others convenience, it is better to put few blank lines between paragraphs to edit in
future or on demand.
2.3.3 PREFORMATTED TEXT
The preformatted text tag <pre> used to display the same text in our document as it is written in
HTML script. The font-width, their spaces, lines and tabs of our source document remain as is it.
In simple words, the browser shows our text as we typed it in. Through monospace font, the text
is rendered where the same amount of space is occupied by all characters. Visually, preformatted
text looks like a courier font. This is an example of preformatted tag.

Example:

<pre>this is a preformatted text tag example</pre>

Output:

this is a preformatted text tag example

2.3.4 BOLDFACE, UNDERLINE AND ITALICS


We can use bold, italic and underline <b>, <i> and <u> tags respectively in HTML editor to
highlight the text in a HTML document. The text in-between <b> </b> tags text will be bold and
similarly we can apply other two italic and underline. The HTML links do not require extra tag
because these are already underlined. The potential for confusion and the archaic nature of
underlining in general make it a poor marker for emphasis.
When using these tags, we usually cannot (and probably should not) have text that is both
boldface and italics; the last tag encountered is usually the tag that is displayed. For example, if
we had a boldface tag followed immediately by an italic tag, the tagged word would appear in
italics. This is an example.

Example:

<b>boldface</b>
<u> underline</u>
<i>italic</i>

Output:

boldface
underline

italic

2.3.5 LISTS

In HTML, we can give number, unnumbered and lists to the different text using the simple tags.
We can also use nested lists with a list. HTML editor automatically takes the space between the
bullet or list number in a text, we do not need to mention it. Neither (as yet) do we have control
over what type of bullet will be used as each browser is different.

Unnumbered lists:
<ul> tag is use to unnumbered any list followed by the actual list items, which are marked with
the <li> tag. The list is ended with the ending tag </ul>.

For example, here is an unnumbered list with three items:

Example disc bullets:

<!DOCTYPE html>
<html>
<body>
<h2>Disc bullet with Unordered list </h2>
<ul style="list-style-type:disc">
<li>Ram</li>
<li>Shyam</li>
<li>Mahesh</li>
</ul>
</body>
</html>
Output disc:

• Ram
• Shyam
• Mahesh

This is an example of a circle bullet.

Example circle bullets:

<!DOCTYPE html>
<html>
<body>
<h2>Circle bullets with Unordered list </h2>
<ul style="list-style-type:circle">
<li>Ram</li>
<li>Shyam</li>
<li>Mahesh</li>
</ul>
</body>
</html>

Output:

o Ram
o Shyam
o Mahesh

This is an example of a square bullet.

Example square bullet:

<!DOCTYPE html>
<html>
<body>
<h2> Square Bullets with Unordered list </h2>
<ul style="list-style-type:square">
<li>Ram</li>
<li>Shyam</li>
<li>Mahesh</li>
</ul>
</body>
</html>
Output:

▪ Ram
▪ Shyam
▪ Mahesh

Numbered lists
Similar example given here using a numbered list format:

Example Numbers:

<!DOCTYPE html>
<html>
<body>
<h2>Numbers are used for Ordered List</h2>
<ol type="1">
<li>Ram</li>
<li>Shyam</li>
<li>Mahesh</li>
</ol>
</body>
</html>

Output:

1. Ram
2. Shyam
3. Mahesh

This is an example of an uppercase letter use in list.

Example Uppercase Letters:

<!DOCTYPE html>
<html>
<body>
<h2>Letters are used for Ordered List </h2>
<ol type="A">
<li>Ram</li>
<li>Shyam</li>
<li>Mahesh</li>
</ol>
</body>
</html>

Output:
A. Ram
B. Shyam
C. Mahesh

This is an example of a lowercase letter use in list.

Example Lowercase Letter:

<!DOCTYPE html>
<html>
<body>
<h2> Lowercase Letters are used for Ordered List </h2>
<ol type="a">
<li>Ram</li>
<li>Shyam</li>
<li>Mahesh</li>
</ol>
</body>
</html>

Output:

a. Ram
b. Shyam
c. Mahesh
This is an example of roman letters.
Example Roman letters:
<!DOCTYPE html>
<html>
<body>
<h2> Roman Numbers are used for Ordered List </h2>
<ol type="I">
<li>Ram</li>
<li>Shyam</li>
<li>Mahesh</li>
</ol>
</body>
</html>

Output:

I. Ram
II. Shyam
III. Mahesh
2.3.6 BLOCKQUOTE
For a long quotation in the text, we can use a < blockquote > tag and the text enclosed within this
tag indicates an extended quotation. Blockquote texts are generally rendered by the browser as
indented text. It looks like this:

<blockquote>...</blockquote>

2.3.7 HORIZONTAL LINE


We can insert a horizontal rule tag <hr> to separate a paragraph into different sections. A
horizontal rule line is displayed as shown below:

This is an example of a horizontal line

This is an example of a horizontal line

2.4 Title and footers


Title definition and Usage

The <title> is an important tag which required to shown the title of the HTML documents and it
only contains text and other tags containing in the title are ignored. The title is displayed in the
browser’s toolbar. It also shows the favorite pages title which we added during browsing and in
search-engine results title.

This is an illustrative example of title tag.

Example:
<!DOCTYPE html>
<html>
<head>
<title> First HTML script for web page </title>
</head>
<body>
First HTML script for web page
</body>
</html>
Output:
Footer definition and Usage

The <footer> tag in HTML represents a footer for a document or section. A <footer> element
generally contains information about its author, copyright data or links to other related
documents. You can have several <footer> elements in one document.

This is an example of a footer.

Example:

<!DOCTYPE html>
<html>
<body>
<footer>
<p>Posted by: xyz</p>
<p>Contact information: <a href="mailto:xyz@yahoo.com">xyz@yahoo.com</a>.</p>
</footer>
<p><strong>Note:</strong> The footer tag is supported only from Internet Explorer 9 and later
versions.</p>
</body>
</html>

Output:

2.5 Text Formatting


The text formatting tags are used to change the appearance of some text so that it looks different
from normal text in web pages. Several formatting tags are consists in HTML to format the text,
like <i>, <em> etc.
The following HTML tags can be used to display special types of text:
• <ins> - Inserted text
• <del> - Deleted text
• <i> - Italic text
• <b> - Bold text
• <small> - Small text
• <em> - Emphasized text
• <strong> - Important text
• <mark> - Marked text
• <sub> - Subscript text
• <sup> - Superscript text

2.5.1 HTML <b> and <strong> Elements


The HTML <b> tag displays bold text, without any extra importance.

Example:

<!DOCTYPE html>
<html>
<body>
<p> Example of a simple text.</p>
<p><b> Example of a bold text.</b></p>
</body>
</html>

Output:

Example of a simple text

Example of a bold text.

2.5.2 HTML <i> and <em> Elements

The HTML <i> tag represents italic text, without any extra importance.

<!DOCTYPE html>
<html>
<body>
<p>Example of a simple text.</p>
<p><i>Example of a italic text.</i></p>
</body>
</html>

Output:

Example of a simple text.

Example of italic text.

2.5.3HTML <small> Element


The HTML <small> tag defines smaller text:

Example:
<!DOCTYPE html>
<html>
<body>
<h2>HTML <small>Small</small> Formatting</h2>
</body>
</html>

Output:

2.5.4 HTML <mark> Element

The HTML <mark> tag defines marked or highlighted text:

Example:

<!DOCTYPE html>
<html>
<body>
<h2>HTML <mark>Marked</mark> Formatting</h2>
</body>
</html>

Output:

The HTML <del> tag used to highlight the deleted (removed) text.

Example:
<!DOCTYPE html>
<html>
<body>
<p>The del tag defines deleted (removed) text.</p>
<p>I like to play <del>Cricket</del> Football.</p>
</body>
</html>

Output:
2.6 Text Style
The appearance of an HTML page can be changed with the style attribute.
The syntax of the HTML style attribute is given below:

<tagname style="property:value;">

The property is a CSS property (Cascading Style Sheet, used for enhancing the look of any
document). The value is a CSS value.

2.6.1 HTML Background Color

We can set the background color of any HTML page by using the background-color property.
The below example shows how to set the background color of a page to powder blue:

Example:

<!DOCTYPE html>
<html>
<body style="background-color:powderblue ;">
<h1>Example of Background Color changing.</h1>
<p>Example of Background Color changing.</p></body>
</html>

Output:

2.6.2 HTML Text Color


The text color of an HTML page can be change by using color property which is shown below
with an example.

Example:

<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue;">Example of Blue color text.</h1>
<p style="color:red;">Example of Red color text.</p>
</body>
</html>

Output:

Example of Blue color text.

Example of Red color text.

2.6.3 HTML Text Size

The size of the font in a HTML document can be set according to our requirement by using font-
size property and it is illustrated below with a simple example:

Example:

<!DOCTYPE html>
<html>
<body>
<h1 style="font-size:300%;">The font size is very large.</h1>
<p style="font-size:160%;">The font size is big.</p>
<p style="font-size:60%;">The font size is small.</p>
</body>
</html>

Output:
2.6.4 HTML Text Alignment

For alignment of the text of HTML pages, there are four text-align property (left, center, right
and justify) that are frequently used. It defines the horizontal text alignment for an HTML
element. The example given below shows the method for center alignment text:

Example:

<!DOCTYPE html>
<html>
<body>

<h1 style="text-align:center;">Centered Heading</h1>


<p style="text-align:center;">Centered paragraph.</p>

</body>
</html>

Output:

2.6.5 Changing a paragraph's background color


Here is an example of background color
Example:

<p style = "background-color: green">


The background color of the Paragraph is Green.
</p>

Output:

The background color of the Paragraph is Green.

2.6.6 Changing foreground and background color


Here is an example of foreground and background color
Example:

<p style = "color: blue";


“background-color: green”>
<p style “text-color: blue”; The text is Blue on a Green background color>
</p>
Output:

The text is Blue on a Green background color

2.6.7 Changing Font Family


Here is an example of comic sans family

Example:

<p style = "font-family: Comic Sans MS, Cursive">


This paragraph is in Comic Sans
</p>

Output:

This paragraph is in Comic Sans


2.6.8 Changing Font Size
Here is an example for font size 30.

Example:

<p style = "font-size: 30pt">


This paragraph is in 30 pts
</p>

Output:

This paragraph is in 30 pts


2.7 Adding Graphics to HTML Document

In the beginning, graphics was not supported by the web pages only texts are used. But later on
images and other types of multimedia files are embedded with web pages. The graphics are
embedded in a HTML pages using a simple tag which is represented by <IMG>. We can also
embed the images inside other elements such as anchors. When embedded inside an anchor, then
the user left clicks on the image, they will go to the designated link (rather, their browser will
load a file from the designated link). The <IMG> element has no ending tag. The syntax of
embedding an image is follows:

<img src=”tree.jpg”>
Here, src attributes defines a path pointing to the image from where we want to embed.
IMG Attributes

Sr. IMG Attributes Function of attributes


No.
1. ALT="Home" Image not found massage shows.
2. ALIGN="TOP" Set image alignment like left, right, top, bottom etc.
3. VSPACE=3 Upper and lower space in pixels of an image between texts.
4. HSPACE=5 Left and right space in pixels of an image between texts.
5. BORDER=10 Set a border around the image with a specific width.
6. HEIGHT=33 Set image height based on the browser height.
7. WIDTH=115 Set image width based on the browser height.
8. ISMAP It represents image map and user can point and click different
parts of the image to load other web pages.
9. USEMAP Specifies the client side image map file to be used.

Table 2.1 Image Attributes


The line break element, <BR> and the horizontal rule element <HR> may be placed inside the
<IMG> element.
An example of adding an image source.
Example:

<img src=”funny dog.jpg” alt=”funny dog sitting”.>

Output:

2.8 Tables

2.8.1 Defining an HTML Table with Border

An HTML <table> tags are used to create different table in our web pages. Each table row is
defined with the <tr> tag. A table header is defined with the <th> tag. By default, table headings
are bold and centered. A table data/cell is defined with the <td> tag. This is an example of
HTML table with border where border width is 1.

Example:
<!DOCTYPE html>
<html>
<Body>
<table border="1">
<tr>
<th>Student Name</th>
<th>Subject</th>
<th>Marks</th>
</tr>
<tr>
<td>Ram</td>
<td>HTML</td>
<td>87</td>
</tr>
<tr>
<td>Shyam</td>
<td>HTML</td>
<td>73</td>
</tr>
</table>
<Body>
</html>

Output:

2.8.2 Html Table Tags:

Tag Description
<table> Displays a table
<th> Represents a header cell in a table
<tr> A row in a table
<td> A cell in a table
<col> Specifies column properties for each
column within a <colgroup> element
<caption> A table caption
<colgroup> Specifies a group of one or more
columns in a table for formatting
<thead> Groups the header content in a table
<tbody> Groups the body content in a table
<tfoot> Groups the footer content in a table

Table 2.2 Table Tags

2.8.3 HTML Table without Border


If we want to create table without border, it will be created by not defining border size. This is an
example of a table without border.

Example:

<html>
<body>
<table style="width:100%">
<tr>
<th>Student Name</th>
<th>Subject</th>
<th>Marks</th>
</tr>
<tr>
<td>Ram</td>
<td>HTML</td>
<td>87</td>
</tr>
<tr>
<td>Shyam</td>
<td>HTML</td>
<td>73</td>
</tr>
<tr>
<td>Ghanshyam</td>
<td>HTML</td>
<td>67</td>
</tr>
</table>
</body>
</html>

Output:
2.8.4 HTML Table - Adding Cell Padding
To manage the spaces between the cell of a table and its border, we use Cell padding tags. If we
do not mention a padding, the table cells will be displayed without padding. This is an example
of a cell padding.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 20px;
}
</style>
</head>
<body>
<table style="width:100%">
<tr>
<th>Student Name</th>
<th>Subject</th>
<th>Marks</th>
</tr>
<tr>
<td>Ram</td>
<td>HTML</td>
<td>87</td>
</tr>
<tr>
<td>Shyam</td>
<td>HTML</td>
<td>73</td>
</tr>
<tr>
<td>Ghanshyam</td>
<td>HTML</td>
<td>67</td>
</tr>
</table>
<p>Try to change the padding to 15px.</p>
</body>
</html>

Output:

2.9 Linking Documents


HTML Links – Hyperlinks

In a web page, several links are used to directly access the other pages or other parts of a given
page. These links are also known as hyperlinks which allows user to switch between different
web pages. When we move the mouse over a link, the mouse arrow will turn into a little hand.

Note: A link does not have to be text. It can be an image or any other HTML element.

Other tags
• <a> tag is an anchor tag which represents a link to reach the new linked document.
• href attribute is used to link the address of the web pages by url.
• target attribute to define where to open the linked document
• <img> tag (inside <a>) to use an image as a link
• id atribute (id="value") to show a bookmarks in web page
• href attribute (href="#value") to link to the bookmarks
<a href="/html/default.asp">HTML tutorial</a>

This is an example of a hyperlink.

Example:

<!DOCTYPE html>
<html>
<body>
<p><a href="https://www.google.com">Visit google website</a></p>
</body>
</html>

Output:

2.10 Frames
In HTML pages, frames allow multiple views to the user and we can browse window into
multiple sections with a separate HTML document. A browser contains many frames in a
window which is known as a frameset. The window frames are divided into rows and columns
in similar way as table are organized.

Disadvantages of Frames

Due to some major drawbacks of frame in window, it is never recommended to use frames in
our webpages −

• In smaller screen, frames do not cop-up properly because their screen is not big enough
to be divided up.
• Sometimes our page will be displayed differently on different computers due to different
screen resolution.
• The browser's back button might not work as the user hopes.
• There are still few browsers that do not support frame technology.

Creating Frames

To use frames on a page we use <frameset> tag instead of <body> tag. The <frameset> tag
defines how to divide the window into frames. The rows attribute of <frameset> tag defines
horizontal frames and cols attribute defines vertical frames. Each frame is indicated by <frame>
tag and it defines which HTML document shall open into the frame.

2.11 Summary
HTML is a structured programming language (Structured programming is paradigm aimed at
improving the clarity, quality, and development time of a computer program) which provides a
set of rules for correct application of elements. The browser renders (display) the HTML code
for correct representation and orientation of content. At times, the rules laid down in HTML are
interpreted differently by browser which provides the programmers an opportunity to exploit this
vulnerability. HTML is essentially a tag-based language. The documents start with the
<! DOCTYPE> tag. The entire document is encapsulated within <HTML> (opening and closing)
tags. The document is further divided into header and body sections specified by <HEAD> and
<BODY> tags, respectively. The header section is used to provide the descriptive information
related to the web document and needs to contain the <TITLE> tag to define the title of the page.
The body section of the web document contains information regarding placement of various
elements of the document. Block-level elements, text-level elements, and special-character
entities are used to structure it. Some tags are used for providing certain logic and the others are
for physical representation. The HTML elements discussed so far are of basic nature and are
widely used over all systems. They are utilized to customize the document presentation.
However, a complete look of the web document cannot be achieved simply using these basic
tags.

2.12 Questions for Exercise


1. Define HTML Tag and list a few basic tags used in HTML.
2. What is a list? Why do we use them?
3. What are the different types of lists used?
4. Why bold and italic tags are used? Illustrate using suitable example.
5. How do we create frames? What are the disadvantages of using frames?
6. Show with an example the use of different heading types.
7. How to assign different colors in a HTML document?

2.13 Suggested Readings


• Behrouz A. Forouzan. 2012. Data Communications And Networking, Fifth Edition.
New York: the McGraw-Hill Companies Inc.
• William Stallings. 2007. Data And Computer Communications Eighth Edition. New
Jersey: Person Education,Inc.
• Douglas E. Comer.2003. The Internet Book. Singapore: Pearson Education Pte. Ltd.
• M.Srinivasan. 2012. Web Technology Theory and Practice. India: Dorling Kindersley
Pvt.Ltd.
• Raj Kamal. 2006. Internet and Web Technologies. India: The Tata McGraw-Hill
Publishing Company Limited.
Unit: 3 JavaScript
Unit Structure
3.0 Objective
3.1 JavaScript in Web Pages
3.2 Advantages of JavaScript
3.3 Disadvantages of JavaScript
3.4 Data Types & Literals
3.5 Variable
3.6 Type Casting
3.7 Operator
3.8 Control Structure
3.9 Conditional Statement
3.10 Array
3.11 Function
3.12 Summary
3.13 Questions for Exercise
3.14 Suggested Reading

3.0 Objective
JavaScript is an object-oriented programming language. It is used to create dynamic HTML
webpages. It provides open and cross platform. In this unit, you will study about the various data
types, variables, operators, which are used in JavaScript. You will also gain understanding of
looping in control structure and conditional statements like if-else. In the later sections, you will
be introduced with the concepts of functions in JavaScript.

3.1 JavaScript in Web Pages


JavaScript is a dynamic programming language for use in HTML pages. An interpreter, which is
built into the user’s web browser (not on the server), runs the JavaScript programs. An HTML
page can be dynamically modified by JavaScript. User input can be validated and reacted by
JavaScript. Cookies can be created by using JavaScript. No communication with the server is
required for JavaScript user interaction. In 1995, JavaScript was introduced in Netscape 2.0 for
the first time with the name LiveScript. The general-purpose core of the language has been
embedded in Netscape, Internet Explorer, and other web browsers.

In JavaScript, interaction with server is less. Because user input can be validated before sending
to the server so load on the server would be less. It provides feedback to visitors immediately. It
increases the interactivity and it can have rich interfaces by including items like drag and drop
components and sliders.
JavaScript has some limitations such as the reading and writing of files are not allowed by client-
side JavaScript. Networking applications does not use JavaScript. Multithreading or
multiprocessor capabilities are not present in JavaScript.

3.2 Advantages of JavaScript


Providing programming capability at both the server and the client ends of a Web connection
was the original goal of JavaScript. Since then, various application areas can use JavaScript as it
has grown into a full-fledged programming language. Client-side JavaScript can serve as an
alternative for some of what is done with server-side programming, in which computational
capability resides on the server and is requested by the client. Because client-side JavaScript is
embedded in XHTML documents (either physically or logically) and is interpreted by the
browser. Other clients can be benefited by transferring load from the often-overloaded server to
the often underloaded client. However, all server-side computing cannot be replaced by client-
side Java. In particular, client-side JavaScript does not support file operations, database access,
and networking, whereas server-side software supports all of these functionalities. JavaScript can
suitably describe the interactions with users through form elements, like buttons and menus.
JavaScript can easily detect the button clicks and mouse movements. They can be used to trigger
computations and provide feedback to the user. For example, when a user moves the mouse
cursor from a text box then JavaScript can detect that movement. It checks the appropriateness of
the text box’s value (which presumably was just filled by the user).
Interaction with users even without form can possible and easy to program in JavaScript. These
interactions These interactions, which take place in dialog windows, include getting input from
the user and allowing the user to make choices through buttons. Generation of new content is
also simple in the browser which display it. The Document Object Model (DOM), permits
JavaScript scripts to access and modify the CSS properties and content of the elements of a
displayed XHTML document. It also allows to make formally static documents highly dynamic.

3.3 Disadvantages of JavaScript


JavaScript has several disadvantages also. In JavaScript, execution of code is done on the users'
computer, in some cases it can be exploited for malicious purposes. Some people disable
JavaScript due to this reason. Another disadvantage of JavaScript is different interpretation of it
by different browsers. However, server-side scripts will always generate the same output, client-
side scripts can be a little unpredictable. Don't be overly concerned by this though - as long as
you test your script in all the major browsers you should be safe.

3.4 Data Types & Literals

3.4.1 Data Types


The set of data types a programming language support is one of the most fundamental
characteristics. The data types are the values which can be manipulated in a program.
JavaScript has three primitive data types:
i. Numbers: It contains the integer, floating numbers etc.
Example: 432, 540.25 etc.
ii. Strings: It is string of alphabets.
Example: "This is a text string" etc.
iii. Boolean: It contains only two values either true or false.

Two trivial data types are defined in JavaScript: null and undefined, each of them
defines only a single value. Along with these primitive data types, JavaScript supports a
composite data type known as object.

Note: Floating-point values are used to represent all numbers in JavaScript. There is none of the
difference between integer and floating-point values.

3.4.2 Literals
A fixed value in any source code is known as Literal. Atomic values for integers, floating point
numbers and strings and generally for Booleans and characters are treated as literals.

Numeric Literals
All numeric literals are values of type Number. The Number type values are represented
internally in double-precision floating-point form. Because of this single numeric data type,
numeric values in JavaScript are often called numbers. Numeric literals can have either integer
or floating-point values in a script. Stings of digits are Integer literals. Decimal points,
exponents, or both can be considered as floating-point literals. An uppercase or lowercase 2 and
a possibly signed integer literal are specified as Exponents.
Valid numeric literals are as following:
53 5.3 .53 53. 5E3 5e3 .5e3 5.e3 5.3E-3
Integer literals can be written in hexadecimal form by preceding their first digit with either 0x or
0X. (The first character is zero, not “oh”.)
String Literals
A string literal is a sequence of zero or more characters delimited by either single quotes (‘) or
double quotes (“). Characters which are specified with escape sequences (i.e. /n or /t) can be
included in string literals. An actual single-quote character in a single literal which is delimited
by single quotes, then the embedded single quote must be preceded by a backslash:

‘You\’re the prettiest girl I\’ve ever seen’

A double quote can be embedded in a double-quoted string literal by preceding it with a


backslash. An actual backslash character in any string literal must be itself backslashed, as in the
following example:
“E:\\movies”
There is no difference between single-quoted and double-quoted literal strings. The null string (a
string with no characters) can be denoted with either ‘‘or ““. All string literals are primitive
values.

Boolean Literals
Boolean literals are logical values that have only one of two values, true or false. The values as
yes or no, on or off, or 1 or 0 can be considered as Boolean literals. They are used to test whether
a condition is true or false. The value true evaluates to 1 and false evaluates to 0, when using
numeric comparison and equality operators.
Example:
output1 = true
or
if (output2 == false) {do something;}

3.5 Variable
In JavaScript, variables are present like several programming languages have. It can be
considered as named containers. These containers accommodate the data and then container can
be used to refer data by naming it.
Variable must be declared before using it in a JavaScript program. The declaration of variable is
as follows.

script type="text/javascript">
<!--
var cost;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows:
<script type="text/javascript">
<!--
var cost, name;
//-->
</script>

Variable initialization stores a value in a variable. Variable initialization can be done at the time
of creation or when it is needed.
For instance, variable named cost might be created and assign the value 400.20 to it later. Here a
value can be assigned at the time of initialization for the variable name as shown in below.
<script type="text/javascript">
<!--
var name = "Ram";
var cost;
cost = 400.20;
//-->
</script>

Note: For declaration or initialization purpose var keyword is used, variable name is defined
only once in a document.
3.5.1 Variable Scope
A section of a program in which a variable is defined is called scope of that variable. In
JavaScript two types of variables are present.

• Global Variables: It can be defined anywhere in JavaScript code. Because it has global
scope.
• Local Variables: It will be defined in a function and any changes or manipulation will
affects it only within a function.

Precedence is given to local variables over a global variable with the same name. Global variable
will be hidden if a local variable is declared with the same name as a global variable. It can be
easily understand by the following example.

<script type="text/javascript">
<!--
varVar1 = "global"; // Declare a global variable
function findscope( ) {
varVar1 = "local"; // Declare a local variable
document.write(Var1);
}
//-->
</script>

The result will be produced by above example.


Local

3.5.2 JavaScript Variable Names


The following rule should follow, while naming variables in JavaScript.
• Any of the JavaScript reserved keywords should not be used as a variable name.
• For example, break or Boolean variable names are not valid.
• A letter or an underscore character must be used in beginning of JavaScript variable
names. Numeral (0-9) should not be used to start a JavaScript variable name. For
example, 123 test is not valid but _123 test is a valid one.
• Variable names are case-sensitive. Like, Money and money are two different variables.

3.6 Type Casting


The conversion from a data type to another is known as Type casting. If a specific value is of a
different type then it can be accessed using type casting. There are two types of type casting.
They are explained as following:

3.6.1 Implicit Type Casting:


Various implicit type castings are performed by the JavaScript interpreter. Such conversions are
known as coercions. Generally, when a value of one type is used in a position which needs a
value of a different type, JavaScript attempts to the value to the required type. Primitive string
and number values are involved in the most common examples of these conversions.

If operand of a + operator is a string, the operator is interpreted as a string catenation operator. If


the other operand is not a string, it is considered a string.
For example, consider the following expression:
“January” + 1994
In this expression, the left operand is a string so, the operator is considered as a catenation
operator. That’s why the right operand is implicitly converted to a string. Therefore, the
expression evaluates to “January 1994”
The number 1994 in the following expression is also coerced to a string: 1994 + “January”.
Now consider the following expression:
10 * “5”
In this expression, the operator is one that is used only with numbers. This forces a numeric
context on the right operand. Therefore, JavaScript attempts to convert it to a number. In this
example, the conversion succeeds, and the value of the expression is 50. If the second operand
were a string that could not be converted to a number, such as “August”, the conversion would
produce NaN, which would then be the value of the expression.

3.6.2 Explicit type Casting:


Type casting can be forced in many different ways, primarily between strings and numbers.
String constructor can be used to convert strings to numbers which contains numbers, as shown
in the following code:
var str_value = String(value);
This conversion could also be done with the toString method, which has the advantage that it can
be given a parameter to specify the base of the resulting number (although the base of the
number to be converted is taken to be decimal).
An example of such a conversion is
var num = 7;
var str_value = num.toString();
var str_value_binary = num.toString(2);
The first conversion gives the result “7” and the second gives “111”.
Catenation of a number with empty string can convert it into a string. There are various ways to
explicitly convert strings into numbers. Number constructor is one way for this type of
conversion. It is shown in following statement:
var number = Number(aString);
The same conversion could be specified by subtracting zero from the string, as in the following
statement:
var number = aString - 0;
Both of these conversions have the following restriction:
Any character cannot follow the number in the string except a space. For example, the
conversion will not work, if the number happens to be followed by a comma.
JavaScript has two predefined string functions that do not have this problem. The two,
parseInt and parseFloat, are not String methods, so they are not called through String objects;
however, they operate on the strings given as parameters. The parseInt function searches its
string parameter for an integer literal. If one is found at the beginning of the string, it is
converted to a number and returned. If the string does not begin with a valid integer literal, NaN
is returned. The parseFloat function is similar to parseInt, but it searches for a floating-point
literal, which could have a decimal point, an exponent, or both. In both parseInt and parseFloat,
the numeric literal could be followed by any non-digit character without causing any problems.

3.7 Operator
Operators are symbols that are used to perform operations on operands. For example, there is an
expression8-2 is equal to 6. In this example, operands are 8 and 2 and operator is ‘-’.
The following type of operators is supported by JavaScript.
• Arithmetic Operators
• Comparison Operators
• Bitwise Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators

All the operators are explained as following.

3.7.1 Arithmetic Operators


The following arithmetic operators are supported by JavaScript:
Suppose value of variables a, and b is 3 and 6 respectively.

S. No. Operator Description Example


1 Addition (+) Add two operands a+ b=9
2 Subtraction (-) Subtract second operands from the first a-b= -3
3 Multiplication (*) Multiply two operands a*b=18
4 Division (/) The denominator divides the numerator b/a=2
The remainder of an integer division is given as
5 Modulus (%) b%a=0
output.
6 Increment (++) An integer value is increased by one. a++=4
7 Decrement (--) An integer value is decreased by one. b--=5
Table 3.1: Arithmetic Operators

Note: Addition operator (+) can be used for both Numeric and Strings. e.g. "s" + 5 will produce
result as "s5".

3.7.2 Comparison Operators


These operators are used to compare the value of operands. The following comparison operators
are supported by JavaScript:
Suppose value of variables a, and b is 3 and 6 respectively.

S. Operator Description Example


No.
Compares the
1 Equal(==) (a==b) is false
It also checks that value of two
2 Not Equal (! =) operands is equal or not, if (a != b) is true
both operands doesn’t have
equal value of operands than
this condition becomes true.

3 Greater than (>) This condition becomes true, if (a > b) is false.


left operand’s value is greater
than right operand’s value.
This condition becomes true, if
4 Less than (<) left operand’s value is less than (a < b) is true.
right operand’s value.
This condition becomes true, if
5 Greater than or Equal to left operand’s value is greater (a >= b) is false.
(>=) than or equal to right operand’s
value.
This condition becomes true, if
6 Less than or Equal to (<=) left operand’s value is less than (a <= b) is true.
or equal to right operand’s
value.
Table 3.2: Comparison Operators
3.7.3 Logical Operators
These operators are used to perform logical operations between operands. The following logical
operators are present in JavaScript:
Suppose value of variables a, and b is 3 and 6 respectively.

S. No. Operator Description Example


This condition will have true
1 Logical AND (&&) value if both the operands don’t (a&& b) is true.
have zero values.
This condition will have true
2 Logical OR (||) value if any of the two operands (a || b) is true.
don’t have zero values.
The logical state of its operand
3 Logical NOT (!) is reversed by it. The Logical ! (a || b) is false.
NOT operator will make a
condition true, if it is false.
Table 3.3: Logical Operator
3.7.4 Bitwise Operators

The following bitwise operators are supported by JavaScript:


Suppose value of variables a, and b is 3 and 6 respectively.

S. Operator Description Example


No.

1 Bitwise AND (&) A Boolean AND operation is (a& b) is 2.


performed on each bit of its
integer arguments by this
operator.

2 Bitwise OR (|) A Boolean OR operation is (a | b) is 9.


performed on each bit of its
integer arguments by this
operator.
3 Bitwise XOR (^) A Boolean exclusive OR (a ^ b) is 5.
operation is performed on each
bit of its integer arguments by
this operator. Exclusive OR
implies that either operand one
is true or operand two is true,
but not both.

4 Bitwise Not (~) This is a unary operator and it (~B) is -1.


reverses all the bits in the
operand.

5 Left Shift (<<) Binary left shift operator. The (B << A) is 48.
left operands value is moved
left by the number of bits
specified by the right operand.

6 Right Shift (>>) Binary Right Shift Operator. (B >> 1) is 3.


The left operand’s value is
moved right by the number of
bits specified by the right
operand.

7 Right shift with Zero This operator is similar to the (A >>> 1) is 1.


(>>>) Right Shift (>>) operator,
except that the bits shifted in
the left are always zero.
Table 3.4: Bitwise Operators

3.7.5 Assignment Operators


The following assignment operators are supported in JavaScript:

S. No. Operator Description Example


Simple Assignment (=) Value of the right side operand The value of a+ b is
1 is assigned to the left side assigned to c in
operand expression c = a + b.

Add and Assignment (+=) The value of right operand is C += A is same as


2 added to the left operand and C=C+A
later the outputis assigned to the
left operand.
Subtract and Assignment The value of right operand is C -= A is same as
3 (-=) subtracted from the left operand C=C-A
and later the output is assigned
to the left operand.
Multiply and Assignment The value of right operand is C *= A is same as C
4 (*=) multiplied with the left operand = C * A.
and later the output is assigned
to the left operand.
Divide and Assignment The value of left operand is C /= A is same as
5 (/=) divided by the right operand and C=C/A
later the output is assigned to the
left operand.
Modules and Assignment Two operands are used to take C %= A is same as C
6 (%=) modulus and later the output is =C%A
assigned to the left operand.
Table 3.5: Assignment Operators

Note: Same logic is applied to Bitwise operators, so they will become <<=, >>=, >>=, &=, |=
and ^=.
3.7.6 Miscellaneous Operators
Two operators, which are quite useful in JavaScript, are discussed here:
i. The Conditional Operator (? :)
ii. The typeof Operator

Conditional Operator (? :)
Conditional operator is used to evaluate an expression that either it is true or false value and later
one of the two given statements is executed depending upon the output of the evaluation.

S.No. Operator Description

1 ? : (Conditional) If Condition is true? Then value X : Otherwise


value Y

Table 3.6: Conditional Operator

Example:
The following code can be used to understand the working of the Conditional Operator in
JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var x = 2;
var y = 3;
var newline = "<br />";
document.write ("((x > y)? 20 : 30) => ");
output = (x > y) ? 20 : 30;
document.write(output);
document.write(newline);
document.write ("((x < y)? 20 : 30) => ");
output = (x < y) ? 20 : 30;
document.write(output);
document.write(newline);
//-->
</script>
<p> Use the different values of variables and then try...</p>
</body>
</html>

Output:
((x > y) ? 20 : 30) => 30
((x < y) ? 20 : 30) => 20
Use the different values of variables and then try...

3.8 Control Structure


In a program, if an activity needs to perform repeatedly in such circumstances, loop statements
are needed to minimize the number of lines. In JavaScript all the necessary loops are used which
we all are familiar with in C or C++.

3.8.1 The while Loop


The while statement creates a loop that executes a statement or code block repeatedly, until an
expression is true. Once the expression turns out to be false, the loop ends.

Syntax
The syntax of the while loop in JavaScript is as follows:

while (expression)
{
Statement(s) to be executed for true expression
}

Example
The following example can be used to implement while loop.

<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Initialize Loop ");
while (count < 5){
document.write("Current Count : " + count + "<br />");
count++;
}
document.write("Loop terminated!");
//-->
</script>
<p> Use the different values of variables and then try...</ p>
</body>
</html>

Output

Initialize Loop Current Count: 0


Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
Loop terminated!
Use the different values of variables and then try...

3.8.2 The do...while Loop


The do...while loop is like the while loop aside from that the condition check occurs toward the
finish of the loop. It implies that the loop will always be executed at least once, even if the
condition is false.

Syntax
The syntax for do-while loop in JavaScript is as follows:

do{
Statement(s) to be executed;
} while (expression);

Note: At the end of the do...while loop, the semicolon must be used.

Example
The following example shows the implementation a do-while loop in JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var count = 0;
document.write("Initialize Loop" + "<br />");
do{
document.write("Current Count : " + count + "<br />");
count++;
}while (count < 5);
document.write ("Loop terminated!");
//-->
</script>
<p> Use the different values of variables and then try...</p>
</body>
</html>

Output

Initialize Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop terminated!
Use the different values of variables and then try...

3.8.3 for Loop


The most reduced form of looping is ‘For’ loop. It has three parts which mentioned below:
• Loop initialization: A starting value is used to initialize the counter. Before the loop
begins, the initialization statement is executed.
• Comparison statement: A given condition is tested here. If the condition is true, then the
statement inside the loop will be executed, otherwise the control will come out of the
loop.
• Iteration statement: In this part, counter increases and decreases.

All the three parts can be put in a single line separated by semicolons.

Syntax
The syntax of for loop is JavaScript is as follows:

for (initialization; test condition; iteration statement){


Statement(s) to be executed if test condition is true
}

Example
The following example tells working of for loop in JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var count;
document.write("Initializing Loop" + "<br />");
for(count = 0; count < 5; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
document.write("Loop terminated!");
//-->
</script>
<p> Use the different values of variables and then try...</p>
</body>
</html>

Output

Initializing Loop
Current Count: 0
Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
Loop terminated!
Use the different values of variables and then try...

3.9 Conditional Statement


When you write a program, you may experience a situation where you have to choose a path out
of a given set of paths. In such cases, conditional statements are used to make correct decisions
and perform right actions that enable the code.
Different actions based on different conditions can be performed using conditional statements in
JavaScript. The if..else statement is explained following.

The following forms of if..else statement is supported in JavaScript:


• if statement
• if...else statement
• Nested if...else statement

3.9.1 If Statement
The fundamental control statement of JavaScript is ‘If’ statement. It permits JavaScript to make
decisions and execute statements conditionally.

Syntax
if statement has following syntax:

if (expr){
Statement(s) to be executed if expr 1 is true
}

Evaluation of JavaScript’s expression is done here. The given statements will execute, if the
expression is true. Any of the statement will not execute if the expression is false. Usually,
comparison operators are used for making decisions by if statement.

Example
The following example shows the working of if statement in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var distance = 5;
if( distance> 3 ){
document.write("<b>Use the vehicle</b>");
}
//-->
</script>
<p> Use the different values of variables and then try again...</p>
</body>
</html>

Output

Use the vehicle


Use the different values of variables and then try again...

3.9.2 if...else Statement


The next form of control statement is the ‘if...else’ statement. Execution of statements is done in
more restricted way in JavaScript by “if…else”.

Syntax
The syntax of an if-else statement is as follows:

if (expr)
{Statement(s) to be executed if expr is true
}
else
{Statement(s) to be executed if expr is not true
}

Evaluation of JavaScript expression is done here. If the expression is true, than the ‘if’ block
statement(s) will be executed. Otherwise, the else block statement(s) will be executed.

Example
The following program shows the implementation of the if-else statement in JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var distance = 2;
if( age > 3 ){
document.write("<b>Use the vehicle</b>");
}else{
document.write("<b>Don’t use the vehicle</b>");
}
//-->
</script>
<p> Use the different values of variables and then try again...</p>
</body>
</html>

Output

Don’t use the vehicle


Use the different values of variables and then try again...

3.9.3 Nested if..else Statement


An advanced form of if…else is the ‘Nested if...else’ statement. JavaScript is allowed to make a
right decision out of many conditions.

Syntax
A Nested if-else statement has the following syntax:

if (expr 1){
Statement(s) to be executed if expr 1 is true
}else if (expr 2){
Statement(s) to be executed if expr 2 is true
}else if (expr 3){
Statement(s) to be executed if expr 3 is true
}else{
Statement(s) to be executed if no expr is true
}

Statement(s) are executed based on the true condition. Else block is executed when no condition
is true.

Example
The following program shows the implement of an if-else-if statement in JavaScript.

<html>
<body>
<script type="text/javascript">
<!--
var branch = "cse";
if( branch == "me" ){
document.write("<b>Mechanical</b>");
}else if( branch == "cse" ){
document.write("<b>Computer Science</b>");
}else if( branch == "ee" ){
document.write("<b>Electrical</b>");
}else{
document.write("<b>Civil</b>");
}
//-->
</script>
<p> Use the different values of variables and then try again...</p>
</body>
</html>

Output

Computer Science
Use the different values of variables and then try again...

3.10 Array
JavaScript arrays stores multiple values in a single variable.

Example
var books = ["C", "Python", "JavaScript"];

• An array is a special variable. More than one value can be held by an array at a time.
• If a list of items (i.e. a list of books) is stored books in a single variable then it could look
like this:
var book1 = "C";
var book2 = "Python";
var book3 = "JavaScript";
• Here we have to store very less number of items, if we need to store more number of
items or we want to loop through and find a specific item value, then there is need of
array.
• In array, we can store many values under a single name, and index number is referred to
access the values.

3.10.1 Array Operations


The following operations can be performed on an array.

Create an Array

JavaScript Array can be created by using an array literal.

Syntax:
var arrname = [item1, item2, ...];

Example
var books = ["C", "Python", "JavaScript"];

Using the JavaScript Keyword new


An array is created in the following example, and values assigned to it:

Example
var cars = new Array("C", "Python", "JavaScript");

Exactly same is done in the previous examples. There is no need to use new Array ().
The first one (the array literal method) is better to use for simplicity, readability and execution
speed.

Accessing the Elements of an Array

The index number is used to refer an array element.


The following statement shows that how the value of the first element can be accessed in books:
var b1 = books[0];

• The first element in books is modified by the following statement:


books[0] = "Perl";

Example
var books = ["C", "Python", "JavaScript"];
document.getElementById("demo").innerHTML = books[0];

• Array indexes start with 0.

Accessing the Complete Array

The array name can be referred to access the complete array in JavaScript.

Example
var books = ["C", "Python", "JavaScript"];
document.getElementById("demo").innerHTML = books;

3.10.2Array as Objects
Arrays are a special type of objects. For arrays, “objects” is returned by the typeof operator in
JavaScript. But, arrays are the best way to explain JavaScript arrays.
Numbers are used by arrays for access its "elements". In this example, student[0] returns Mark:

Array:
var student = ["Mark", "Juke", 23];

Objects use names to access its "members". In this example, student.fName returns Mark:

Object:
var student = {fName:"Mark", lName:"Juke", age:32};

Array Elements as Objects


• JavaScript variables can be objects. Arrays are special types of objects. That’s why an
array can have different types of variables.
• An array can have objects, functions, arrays.
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myBooks;

3.10.3 Array Properties and Methods


The built-in array properties and methods are the real strength of JavaScript arrays:

Example

var A = books.length; // The number of elements in an array is returned by the length


property.
var B = books.sort(); // Arrays are sorted by the sort() method.

The length Property

The length property of an array returns the length of an array (the number of array elements).

Example

var branch = ["CSE", "ME", "EE"];


branch.length; // the length of branch is 3

• The length property is always one more than the highest array index.

Looping Array Elements
The use of “For” loop is the best way to loop through an array.

Example

var books, text, bLen, i;


books = ["C", "Python", "JavaScript", "Perl"];
bLen = books.length;
text = "<ul>";
for (i = 0; i <bLen; i++) {
text += "<li>" + books[i] + "</li>";
}
Add Array Elements

The push method is used to add a new element to an array.

Example
var books = ["C", "Python", "JavaScript", "Perl"];
books.push("HTML"); // adds a new element (HTML) to books

• Length property can also be used to new element to an array.

Example

var books = ["C", "Python", "JavaScript", "Perl"];


books[books.length] = "HTML"; // A new element (HTML) is added to books

Note: Undefined “holes” can be created in an array if elements are added with high indexes.

Example
var books = ["C", "Python", "JavaScript", "Perl"];
books[6] = "HTML"; // adds a new element (HTML) to books

3.10.4 Associative Arrays


Arrays with named indexes are supported by several programming languages. Associative arrays
(or hashes) are the arrays with named indexes. Arrays with named indexes are not supported by
JavaScript. Numbered indexes are being used for arrays in JavaScript.

Example

var student = [];


student[0] = "Mark";
student[1] = "Juke";
student[2] = 23;
var a = student.length; // student.length will return 3
var b = student[0]; // student[0] will return "Mark"

Note:
The array is redefined to a standard object in JavaScript, if named indexes are used. After that,
some array methods and properties can produce the incorrect results.

Example

var student = [];


student["fName"] = "Mark";
student["lastName"] = "Juke";
student["age"] = 23;
var a = student.length; // 0 will be returnd by student.length
var b = student[0]; // student[0] will return undefined

3.10.5 The Difference between Arrays and Objects


In JavaScript, numbered indexes are used by arrays. Whereas named indexes are used by
Objects.
Arrays are a special kind of objects, with numbered indexes.

3.10.6 Use of arrays and objects


• Associative arrays are not supported by JavaScript.
• When the element names to be strings (text), then objects should be used.
• When the element names to be numbers, then arrays should be used.

3.11 Functions
A group of reusable code that can be called anywhere in the program, is defined as Function. By
using function, there is no need of writing the same code repeatedly. It helps programmers in
writing modular codes. By using functions, programmer is allowed to divide a big program into a
number of small and manageable functions.
Like any other advanced programming language, all the features necessary to write modular code
using functions is supported by JavaScript. There are functions such as alert () and write () are
used repeatedly but they had been written in core JavaScript exactly once.
JavaScript allows us to write our own function in. This part tells that how you can to write your
own functions in JavaScript.

3.11.1 Function Operations


Defining a Function
Before using a function, it need to be define. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.

Syntax
The syntax is as follows:

<script type="text/javascript">
<!--
function function_name(parameter-list)
{
statements
}
//-->
</script>

Example

A function called sayHello which takes no parameters is defined in the following example:
<script type=”text/javascript”>
<!--
function sayHello()
{
alert("Hello there");
}
//-->
</script>

Calling a Function

You would need to write the name of that function to invoke a function somewhere later in the
script, as shown in the following program.

<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function </p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p>Set the different text in write method and then try...</p>
</body>
</html>

Output

Click the following button to call the function

3.11.2 Function Parameters


Till now, functions without parameters are explained. However, different parameters can be
passed while calling a function. These passed parameters can be captured inside the function and
we can do any manipulation over those parameters. Multiple parameters can be taken by a
function and comma separates them.

Example

Our sayHello function is modified in this example. Now it takes two parameters.

<html>
<head>
<script type="text/javascript">
function sayHello(branch, year)
{
document.write (branch + " is " + year +);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('CSE', 2)" value="Say Hello">
</form>
<p>Set different parameters inside the function and then try...</p>
</body>
</html>

Output

Click the following button to call the function

Set different parameters inside the function and then try...

The return Statement

An optional return statement can present a JavaScript function. This is required to return a value
from a function. This statement should be the last statement in a function.

For example
In a function, if two numbers are passed and then it can be expected that the function will return
their addition in the calling program.

Example

The following example defines a function that takes two parameters and concatenates them
before returning the output in the calling program.

<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
varoutput;
output = concatenate('Ram', 'Sita');
document.write (output );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Set different parameters inside the function and then try...</p>
</body>
</html>
Output

Click the following button to call the function

Set different parameters inside the function and then try...

3.11.3 Nested Functions

Before the JavaScript 1.2, function definition was allowed only in top-level global code, but
JavaScript 1.2 allows function definitions to be nested within other functions as well. Still
function definitions cannot be appeared within loops or conditionals. These restrictions on
function definitions apply only on function declarations with the function statement.
Function literals (another feature introduced in JavaScript 1.2) may appear within any JavaScript
expression, which means that they can appear within if and other statements.

Example

Try the following example to learn how to implement nested functions.

<html>
<head>
<script type="text/javascript">
<!--
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}
function secondFunction(){
var output;
output = hypotenuse(1,2);
document.write (output );
}
//-->
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>

Output

Click the following button to call the function

Use different parameters inside the function and then try...

3.11.5 Function Literals


The concept of function literals is introduced in JavaScript 1.2, which is another new way of
defining functions. An unnamed function is defined by a function literal, which is an expression.

Syntax
The syntax for a function literal is much like a function statement, except that it is used as an
expression rather than a statement and no function name is required.

<script type="text/javascript">
<!—var variablename = function(Argument List){
Function Body
};
//-->
</script>

Syntactically, a function name can be specified while creating a literal function as follows.

<script type="text/javascript">
<!--
var variable_name = function FunctionName(Argument List){
Function Body
};
//-->
</script>
But this name does not have any significance, so it is not worthwhile.

3.12 Summary
Dynamic HTML webpages can be created using JavaScript. It is light-weighted. JavaScript has
three primitive data types: Numbers, Strings, Boolean. JavaScript has two trivial data types: null
and undefined and a composite data type: Object. Two types of the variable present in
JavaScript: Global and Local variable. Variable initialization stores a value in a variable.
Variable initialization can be done at the time of creation or when it is needed. Scope of a
variable can be defined as a section of a program in which a variable is defined. Operators are
symbols that are used to perform operations on operands. Several operators are present in
JavaScript i.e. Arithmetic, Comparison, Bitwise, Logical, Assignment, Conditional Operators. In
JavaScript, control structure (i.e. loops) is used to minimize the number of lines. The following
loops are used in JavaScript: While, do-while and for loop. Conditional statements are used to
make correct decisions and perform right actions that enable the code. JavaScript arrays stores
multiple values in a single variable. Creation of array, accessing an element. Arrays are special
type of objects. A group of reusable code that can be called anywhere in the program, is defined
as Function. The return statement is used to return a value in a function. Objects are made of
attributes. If an attribute contains a function, it is thought to be a method of the object; otherwise,
the attribute is viewed as a property. A constructor is a function that creates and initializes an
object. A special constructor function called Object() is provided by JavaScript to build the
object.

3.13 Questions for Exercise


1. Write a Java Script using for loop for displaying sum of first 150 numbers.
2. If a=10 and b=20 write a java script to swap these two numbers.
3. Explain the structure of java script program.
4. List the data types in java script with suitable example.
5. Explain the syntax of function in java script with example.
6. Explain how to create User defined object in Java Script.
7. Define the method for an object.
8. Give the output of the following code segment:
<body>
<script language=”javascript”>
var sum=new Array(6);
var Total= 0;
sum[0]= 0;
for (var count = 1; count < 4; count++)
{
Total+ = count;
sum[count] = Total;
document.write (sum[count] + “<br>”)
}
document.write (Total)
</script>
</body>
9. Write a JavaScript function that checks whether a passed string is palindrome or not?
10. Write a JavaScript program to calculate the factorial of a number.

3.14 Suggested Reading

• Uttam K.Roy. 2010. Web Technologies. New York: Oxford University Press.
• M.Srinivasan. 2012. Web Technology Theory and Practice. India: Dorling Kindersley
Pvt.Ltd.
• David Flanagan. 2011. JavaScript: The Definitive Guide, Sixth Edition. U.S.A.: O’Reilly
Media, Inc.
• Thomas Powell Fritz Schneider. 2012. JavaScript 2.0-The Complete Reference, Third
Edition. U.S.A.: McGraw-Hill/Osborne
UNIT 4: Understanding XML

UNIT STRUCTURE

4.1. Objective
4.2. SGML
4.3. XML
4.4. XML and HTML
4.5. Modelling XML Data
4.6. Styling XML using XSL
4.7. XHTML
4.8. Summary
4.9. Question for exercise
4.10. Suggested reading

4.1 Objective
XML stands for Extensible Markup Language. It is a new markup language, developed by the
W3C (World Wide Web Consortium), mainly to overcome the limitations in HTML. This unit
outlines the basic concepts of XML. The chapter explains the need of XML as well as what
XML is good at. Upon completion of this unit, the readers shall be able to understand what are
markup languages, the relationship between SGML, XML and HTML, the benefits of using
XML, the various constructs of XML that are used to achieve the required objectives as well as
typical applications of XML

4.2 SGML
Standard Generalized Markup Language (SGML) has been developed and standardized by the
International Organization for Standardization (ISO) in 1986. SGML is a generalized standard
since it does not require any specific system, device and language. A markup language uses a set
of additional items called markups to create a document of hierarchical structure. SGML itself is
not a markup language. It is used for defining and structuring other document markup languages
such as HTML and for specifying the rules for tagging elements in a document. Hence, SGML
can be considered as a specification for embedding descriptive markup within a document.
SGML considers the semantics and other auxiliary components of the document for structuring
the document without specifying the graphical design of the document. The actual graphical
styling of such a document may vary, depending on the yield medium and style inclinations. The
advantages of SGML based documents:
• They can be made by considering document structure rather than appearance qualities (which
may change after some time).
• The document will be more portable as SGML compiler can interpret any document using
the reference to its document type definition (DTD).
Documents initially planned for the print medium can be re-adjusted to other media, for example,
computer display screen.
The language utilized by Web browser, Hypertext Markup Language (HTML), is a case of an
SGML-based language. The document structure is written in a Document Type Definition
(DTD) sometimes also referred to as SGML application. A DTD specifies a set of elements, their
relationships, and the tag set to mark the document.
The SGML approach is not to impose its own tag set but to propose a language for authors to
describe the structure of their documents and mark them accordingly. The markup describes the
structure of the document. SGML is an enabling standard, not a complete document architecture.
The strength of SGML is that it is a language to describe documents—in many respects similar
to programming languages. It is therefore flexible and open to new applications.
In today's distributed networking environment, numerous documents are structured as the
Extensible Markup Language (XML) which is an information portrayal language that utilizes
SGML standards. SGML is based on somewhat earlier generalized markup languages developed
at IBM, including General Markup Language (GML) and Information Structure Identification
Language (ISIL).

4.3 XML
XML stands for Extensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML). A markup language is used to provide
information about a document. XML tags identify the data and are used to store and organize the
data, rather than specifying how to display it like HTML tags, which are used to display the data.
There are three important characteristics of XML that make it useful in a variety of systems and
solutions:
• XML is extensible: XML allows you to create your own self-descriptive tags or language,
that suits your application.
• XML carries the data, does not present it: XML allows you to store the data irrespective
of how it will be presented.
• XML is a public standard: XML was developed by an organization called the World
Wide Web Consortium (W3C) and is available as an open standard.

XML Usage

A short list of XML usage says it all:


• XML can work behind the scene to simplify the creation of HTML documents for large
web sites.
• XML can be used to exchange the information between organizations and systems.
• XML can be used for offloading and reloading of databases.
• XML can be used to store and arrange the data, which can customize your data handling
needs.
• XML can easily be merged with style sheets to create almost any desired output.
• Virtually, any type of data can be expressed as an XML document.
4.3.1 XML Syntax

The rules for writing XML syntax can be broken down into the following components:
1. XML Declaration
2. Elements and Tags
3. Attributes
4. Text
5. References
These components have been discussed in details in the following subsections.
4.3.1.1 XML Declaration
The XML document can optionally have an XML declaration. The XML declaration is the first
line of any XML document. The XML declaration is case sensitive and is written as follows −
<?xml version = "1.0" encoding = "UTF-8"?>
Where version is the XML version and encoding specifies the character encoding used in the
document. The XML recommendation suggests that the declaration should be included in every
XML document.
4.3.1.2 Elements and Tags
XML-elements, also known as XML-tags or XML-nodes are used to structure XML documents.
The names of these elements should be enclosed within the triangular brackets < > as shown
below:

<element-name>

Syntax for Elements and Tags


The elements or tags should have a start and the end tag. The syntax for writing xml elements is
shown below:
<element-name-start-tag>……………….</element-name-end-tag>

XML elements can contain:


• Text
• Attributes
• other elements
• or a mix of the above
Nesting of Elements:
Multiple XML-elements, known as children elements, can be contained within a single XML-
element. However, there should not be any overlapping of these children element tags. For
instance: The end tag of an element must have the same name as that of the most recent
unmatched start tag.
The following example illustrate the incorrect nesting of elements:

<?xml version="1.0"?>
<employee>
<name>Rajeev
The correct way
< /employee > of using nested elements has been illustrated below:
</name>
<?xml version="1.0"?>
<employee>
<name>Rajeev
< / name >
Root Element:
Every element in an XML document should be the children of a single element, known as the
root element. There can be only one root element in an XML document. The following is not a
correct XML document, because both the x and y elements occur at the top level without a root
element

<x>...</x>
<y>...</y>

The following example illustrates the correct usage of Root Element:

<root>
<x>...</x>
<y>...</y>
</root>

Naming Rules for XML Elements


XML elements must follow these naming rules:
• Element names must start with a letter or underscore
• Element names cannot start with the letters ‘xml’ or ‘XML’ or ‘Xml’, etc.
• Element names can contain letters, digits, hyphens, underscores, and periods
• Element names are case-sensitive
• Element names cannot contain spaces
Any name can be used, no words are reserved (except xml).
4.3.1.3 Attributes
Elements have related properties, called attributes, which have certain values (by default, or set
by authors or scripts). Attribute/value pairs appear before the closing (">") of an element's start
tag. Any number of (legal) attribute value pairs, in any order, isolated by spaces, might appear in
an element's start tag.
The syntax for writing XML attributes is given below:
<element-name attribute1 attribute2 >
....content..
< /element-name>

Here, attribute1 and attribute2 can be declared as:

attribute_name = "value"
In the above syntax, value has to be in double (" ") or single (' ') quotes. Here, attribute1 and
attribute2 are unique attribute labels.

The following example illustrates the usage of XML attributes

<person age="35">
<name>Amit</name>
<gender>male</gender>
</person>

Attributes are used to distinguish among elements of the same name, when you do not want to
create a new element for every situation. Hence, the use of an attribute can add a little more
detail in differentiating two or more similar elements.

Attribute Types

The following tables lists the different attribute types:


Attribute Type Description
It takes any literal string as a value. CDATA
is a String Type. CDATA is character data.
String Type
This means, any string of non-markup
characters is a legal part of the attribute.
This has a list of predefined values in its
declaration, out of which, it must assign one
value. There are two types of enumerated
attribute:

• Notation Type: It declares that an


Enumerated Type
element will be referenced to a
NOTATION declared somewhere else
in the XML document.
• Enumeration: Enumeration allows you
to define a specific list of values that
the attribute value must match.
This is a more constrained type. The validity
constraints noted in the grammar are applied
after the attribute value is normalized. The
TokenizedType attributes are given as:
Tokenized Type
• ID: It is used to specify the element as
unique.
• IDREF: It is used to reference an ID
that has been named for another
element.
• IDREFS: It is used to reference all IDs
of an element.
• ENTITY: It indicates that the attribute
will represent an external entity in the
document.
• ENTITIES: It indicates that the
attribute will represent external
entities in the document.
• NMTOKEN: It is similar to CDATA
with restrictions on what data can be
part of the attribute.
• NMTOKENS: It is similar to CDATA
with restrictions on what data can be
part of the attribute.

Table 4.1: Attribute Types

Rules for specifying XML Attributes


• An attribute name must not appear more than once in the same start-tag or empty element
tag.
• An attribute must be declared in the Document Type Definition (DTD) using an
Attribute-List Declaration.
• Attribute values must not contain direct or indirect entity references to external entities.
• The replacement text of any entity referred to directly or indirectly in an attribute value
must not contain a less than sign (<).
4.3.1.4 Text

The names of XML-elements and XML-attributes are case-sensitive, which means the name of
start and end elements need to be written in the same case. To avoid character encoding
problems, all XML files should be saved as Unicode UTF-8 or UTF-16 files.

Whitespace characters like blanks, tabs and line-breaks between XML-elements and between the
XML-attributes will be ignored.

Some characters are reserved by the XML syntax itself. Hence, they cannot be used directly. To
use them, some replacement-entities are used, which are listed below:
Characters NOT Allowed Replacement Description
< &lt; Less than
> &gt; Greater than
& &amp; Ampersand
‘ &apos; Apostrophe
“ &quot; Quotation mark

Table 4.2 Replacement Entities

4.3.1.5 Character references


Character references are numeric or emblematic names for characters that might be incorporated
into an HTML document. They refer to seldom utilized characters, or those that authoring tools
make it troublesome or difficult to enter. They begin with a "&" sign and end with a semi-colon
(;). Some basic illustrations include:
"&lt;" means less than (<).
"&gt;" means greater than (>).
"&quot;" means quotation (“) mark.
"&#229;" means letter "a" with a small circle above it.
"&#1048;" means Cyrillic capital letter "I".
"&#x6C34;" means the Chinese character for water.

4.3.1.6 Comments
XML comments have the following linguistic structure:

<!-- this shows a comment line-->


<!-- and this is also a comment line,
For more than one line -->
White space is not allowed between the markup declaration open delimiter ("<!") and the
comment open delimiter ("--"), however, is allowed between the comment close delimiter ("--")
and the markup declaration close delimiter (">"). A typical mistake is to incorporate a series of
hyphens ("---") within a comment. Putting at least two contiguous hyphens inside comments
ought to be maintained a strategic distance from.

4.4 XML Schema (XSDs)


XML Schema replaces DTDs with a more powerful and intuitive approach to create schemas for
XML-based markup languages. Schemas created using XML are coded in the XSD (XML
Schema Definition) language, and are therefore referred to as XSDs. XML Schema and the XSD
language were created by the W3C (World Wide Web Consortium), and represent a considerably
more powerful and flexible approach to schemas than DTDs. The idea behind XML Schema is to
use XML as the basis for creating schemas. So, instead of using the special DTD language to
create a schema, familiar XML elements and attributes that are defined in the XSD language can
be used.
An XSD is very similar in purpose to DTD to establish the schema of a class of XML
documents. XSDs describe elements and their content models to validate the documents similar
to DTDs. However, XSDs go several steps beyond DTDs by allowing to associate data types
with elements. In a DTD, element content is pretty much limited to text, while an XSD is more
flexible as it can set the data type of elements to specific types, such as integer numbers and
dates.
The most compelling aspect of XSDs is the fact that they are based upon an XML vocabulary
(XSD). This means that an XSD can be created as an XML document. So, the familiar
tag/attribute approach to encode XML documents is all needed to code an XSD document. The
specific elements and attributes that comprise the XSD language needs to be learnt, but it isn't
too terribly difficult to learn. XSDs aren't nearly as compact as DTDs, and can be more difficult
to understand initially. The reason is because XSDs are considerably more powerful and flexible
than DTDs, and advanced features comes with complexity. First, learn all about creating XSDs
using XML Schema, "Using XML Schema XSDs," after which this code will make complete
sense. For now, the main thing to understand is that XML Schema allows to use XML code to
model data in a more detailed manner than DTDs. For example, in an XSD, the number of times
an element is allowed to appear exactly when nested can be specified.
Another schema technology exists that helps to simplify the complexities associated with XSDs
is RELAX NG, which many people consider to be more powerful, more concise, and easier to
use than XML Schema. RELAX NG doesn't yet enjoy the widespread support of DTDs and
XSDs but that scenario is likely to change.

4.5 HTML versus XML


Similarities HTML between XML
Both use tags (e.g. <h2> and </year>)
Tags may be nested (tags within tags)
Human users can read and interpret both HTML and XML representations quite easily.

4.5.1 HTML vs XML: Structural Information


• HTML documents do not contain structural information: pieces of the document and their
relationships.
• XML is more easily accessible to machines because every piece of information is
described.
• Relations are also defined through the nesting structure.
E.g., the <author> tags appear within the <book> tags, so they describe properties of the
particular book.
A machine processing the XML document would be able to deduce that the author
element refers to the enclosing book element rather than by proximity considerations.
• XML allows the definition of constraints on values
E.g. a year must be a number of four digits
4.5.2 HTML vs XML: Formatting
• The HTML representation provides more than the XML representation: The formatting
of the document is also described
• Τhe main use of an HTML document is to display information: it must define formatting
• XML: separation of content from display same information can be displayed in different
ways

4.5.3 HTML vs XML: Another Example


In HTML

<h2>Relationship speed-distance</h2>
<i> D = S × T </i>
In XML

<equation>
<meaning>Relationship speed-distance</meaning>
<leftside> D </leftside>
<rightside> S × T </rightside>
</equation>

4.5.4 HTML vs XML: Different Use of Tags


• In both HTML docs same tags
• In XML completely different
• HTML tags define display: color, lists …
• XML tags not fixed: user definable tags
• XML meta markup language: language for defining markup languages

4.6 Modelling XML Data


The data model for XML is very simple - or very abstract, depending on one's point of view.
XML provides no more than a baseline on which more complex models can be built. All those
more restricted applications will share some common invariants.
Think of an XML document as a linearization of a tree structure. At every node in the tree there
are several character strings. The tree structure and the character strings together form the
information content of an XML document. Almost everything will follow naturally from that.
Some of the characters in the document are only there to support the linearization, others are part
of the information content. A more recent document, The XQuery 1.0 and XPath 2.0 Data Mode,
describes another data model for XML.
For a different, and much more formal approach, see `ADT and marshalling for XML'

4.6.1 A Tree and a Graph Overlaid

The main structure of an XML document is tree-like, and most of the lexical structure is devoted
to define that tree, but there is also a way to make connections between arbitrary nodes in a tree.
For example, in the following document, there is a root node with three children, one of the
children has a link to the other children:

<p>
<q id="x7">1st q</q>
<q id="x8">2nd q</q>
<q href="#x7">3rd q</q>
</p>

The corresponding tree to this document can be visualized as follows:


Figure 4.1 Tree-like structure of the example document

The last q has an `href’ attribute and it points to an element with the same `id’ as that of the first
q, so the third q points to the first. (Note that this is a generalization of a similar mechanism in
HTML) The linking model is explained in the XML-link draft.

4.6.2 The Tree

The tree that an XML document represents has a number of different types of nodes:
a) element
b) document
c) processing instruction [not needed?]
d) comment
e) data

4.6.2.1 Element nodes

An element node is created by expressions like the following:

<p a1=”A1” . . . an=”An”>c1 . . . cm</p> for n>=0, m>=0


or these:
<p a1=”A1” . . . an=”An”/> for n>=0

Such an element node has a type p, an ordered list of children ci, and a set of attributes, which
are pairs of attribute names ai and attribute values Ai. In contrast to the children, the order of the
attributes doesn’t matter. Thus, the same node can be linearized with different expressions.
Furthermore, all the ai are different, but the Ai don’t have to be. Note that if m=0, the two
expressions above are equivalent, and indeed one can use either one at will. The type, attribute
names and attribute values consist of strings of characters. There are restrictions on the lexical
structure of the type and attribute names: they must consist of (Unicode) letters, (Unicode) digits,
dashes and dots, they must be at least one character long and they must start with a letter or a
dash. There are no restrictions on attribute values, in particular they may be empty (but see under
`Escape mechanism’ below). The attribute name “id” (upper or lower case) is reserved for
something called the ID of the element. Furthermore, attribute names may not start with the four
letters “xml-“ (upper or lower case), as these are also reserved for xml-link.

4.6.2.2 Document node


A document node is a specialized kind of element node. It has a type p but no attributes. Instead
it has an optional URL u. The intent of the URL is to specify a specialized data model for this
node and its children. A document node looks like this:
<!doctype p “u”>c1 . . . cm for m>0
Exactly one of the ci must be an element node and furthermore it must have type p, the same as
the document type. The other children, if any, must be either comment nodes or processing
instruction nodes. Also, if the document node is not the root node of the document, then i=m. In
other words, if the document node is not the root, its one child i.e. an element node must be its
last child.
The type and URL are again character strings. The type has the same lexical constraints
as the type of an element and the URL has no constraints. There is one exception to the rule that
a document node must have a type. The root node of the XML tree may be an anonymous
document node, without a type and without a URL. Such a document node is represented in the
document by the absence of a `<!doctype>’ expression. In other words, if the first expression in
the document is not `<!doctype...>’, the document has an anonymous root.

4.6.2.3 Processing instruction node

A processing instruction (PI) node is always a leaf node. It only has an instruction i associated
with it. The instruction is a sequence of zero or more characters, without any restrictions, except
that the sequence might not start with the three characters `xml’ (upper, lower or mixed case)
followed by a space or newline. It looks like this in the XML document: <?i?>
Processing instructions that start with `xml’ + whitespace have special meaning to XML. They
look like this: <?xml i?>

4.6.2.4 Comment node

A comment node is similar to a processing instruction. It is also a leaf node and has only
a comment c: <!—c
The intention is that comment nodes are used to include explanatory notes for human
consumption, while processing instructions are for consumption by some application. In the
XML data model, however, there is no difference between them (apart from the processing
instructions that start with `<?xml’).

4.6.2.5 Data node

Data nodes are also leaf nodes. They have a single characteristic: the data d. Since all the other
nodes have delimiters to distinguish them, data nodes don’t need them. Everything that is not
between `< and `>’ is data. (With one exception, at certain places newlines may be inserted for
the benefit of people editing XML by hand, and those newlines are not part of any node.) Data
nodes cannot be empty, that is, their data characteristic contains at least one character.

4.7 Styling XML with XSL

4.7.1 XSL

XSL is a language used to express style sheets. An XSL style sheet describes how to display an
XML document of a given type. XSL shares the functionality and is compatible with CSS2
(although it uses a different syntax). It also adds a transformation language for XML documents
called XSLT. Originally, intended to perform complex styling operations, is now widely used as
a general-purpose XML processing language. XSLT is thus used for purposes other than XSL,
like generating HTML web pages from XML data, advanced styling features, expressed by an
XML document type which defines a set of elements called Formatting Objects, and attributes
(in part borrowed from CSS2 properties and adding more complex ones.

4.7.2 XSLT

The Extensible Stylesheet Language Transformation (XSLT) is used for transforming XML
documents into XHTML documents or to other XML documents. Data transformation
means parsing an input XML document into a tree of nodes. Transformation is about data
exchange.

Before designing a XSLT document, we will go through the mostly used XSLT elements and
attributes. The prefix xsl: specifies the XSLT elements. The following are some XSLT elements:

• Xsl: stylesheet: Specifies that the document is a XSL stylesheet. This element defines the
namespace to access the XSLT elements and attributes. Example:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform

Xsl: template: Declare the HTML template. It uses the Match attribute to search in the
XML document. Here “/” means it is for the entire document. Example:

<xsl:template match="/"> <html>…</html> </xsl:template>

Xsl if: implements an if-else condition. Assume I want to display some example based on
condition then this element helps. Example:

xsl:if test="price > 10">..</xsl:if>

xsl: sort: sorts the XML data based on a node name. It selects an attribute to provide the
node name. The following exmple is sorting the data ordered by the artist XML node's
value. Example:

<xsl:sort select="artist"/>

xsl: choose: implements a Switch-case in XSLT. Inside the choose element it uses
a when element to check the values. Inside the when element it uses a test attribute to
define the condition for the case. Example:
<xsl:choose>
<xsl:when test="price > 10">
……
</xsl:when>
</xsl:choose>
xsl: for-each: iterates over XML data. Assume I have multiple tutorial nodes present in
some XML data then this element helps. Example:
<xsl:for-each select="tutorials/tutorial">…</xsl:for-each>

Create xslt file: (tutorials.xslt)

<?xml version="1.0" encoding="iso-8859-1"?>


<!-- Edited by XMLSpy® -->
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" x
mlns="http://www.w3.org/1999/xhtml">
<body style="font-family:Arial;font-size:12pt;">
<div style="border-style: solid; color: teal;">
<xsl:for-each select="tutorials/tutorial">
<div style="color:green;padding:4px">
<span style="font-weight:bold; color:blue;">
<xsl:value-of select="name"/>
</span>
<xsl:value-of select="url"/>
</div>
</xsl:for-each>
</div>
</body>
</html>

4.7.3 How it works

In the preceding xslt file we loop over (<xsl:for-each) a XML node (tutorials/tutorial) and
display the data inside the div with the designed format. It creates a div depending on whether
there are no tutorial nodes found inside the XML data. Now we need to add a reference xslt file
inside the XML file (tutorial.xml).
See the Yellow marked code that will be additional code. Now the updated code XML will be:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


<?xml-stylesheet type="text/xsl" href=" tutorials.xslt"?>
<tutorials>
………
</tutorials>

Browse the XML file to see how the data looks in the browser. Please see the following
screenshot:
Figure 4.2: Output of XML data using XSLT

4.8 XHTML

Extensible HyperText Markup Language (XHTML) was developed by W3C (World Wide Web
Consortium) in order to facilitate the developers for making the transition from HTML to XML.
It can be understood as HTML redesigned as XML. The XHTML 1.0 is the first document type
in the XHTML family. XHTML is identical to HTML 4.01 with few differences. This is a
cleaner and stricter version of HTML 4.01. Upon migration to XHTML, today web developers
can enter the XML world with all of its benefits, while still retaining confident in the backward
and future compatibility of the content.

4.8.1 Why to use XHTML?


The use of XHTML provides the following benefits −
• XHTML provides a well-structured and more consistent format to the webpages so that
they can be easily parsed by the existing and the future web browsers.
• XHTML documents conform to the XML standards and hence can be easily viewed,
edited, and validated using standard XML tools.
• XHTML combines the strength of HTML and XML. Also, XHTML pages can be
rendered by all XML enabled browsers.
• XHTML documents can make use of applets, scripts and other applications that require
either the XML Document Object Model or the HTML Document Object Model.
• XHTML defines quality standard for webpages and by following that, the web pages
become as quality web pages. The W3C certifies those pages with their quality stamp.
• The document can be easily maintained, edited, converted and formatted in the long run.

➢ Important points to remember while writing a new XHTML document or converting existing
HTML document into XHTML document –
• XHTML document should be initialized with a DOCTYPE declaration.
• The XHTML tags must be closed properly
• The XHTML tags and attributes should be in lower case only.
• There should be proper nesting of all the tags.
• The attribute values should be within quotes.
• Attribute minimization should be avoided.
• The id attribute replaces the name attribute.
• Deprecate the language attribute of the script tag.

4.8.2 DOCTYPE Declaration


It is required that all the XHTML documents must begin with the DOCTYPE declaration. The
following example illustrates the usage of DOCTYPE −

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

4.8.3 Case Sensitivity


XHTML is case sensitive markup language. The XHTML tags and attributes must be written in
lower case only.

<!-- Invalid XHTML syntax -->


<A Href="/xhtml/xhtml_article.html">XHTML Article</A>

<!—Valid XHTML syntax is -->


<a href="/xhtml/xhtml_article.html">XHTML Article</a>

4.8.4 Closing the Tags


Each and every XHTML tags should have an equivalent closing tag. Even the empty elements
should also have closing tags. Here is an example showing valid and invalid usage of tags −

<!-- This is an invalid XHTML syntax-->


<p>This paragraph is not correct according to XHTML syntax.

<!-- This is also an invalid XHTML syntax-->


<img src="/images/xhtml.gif" >

The following is the correct XHTML syntax. Difference is that, both the tags are closed properly.

<!-- This is a valid XHTML syntax-->


<p>This paragraph is correct according to XHTML syntax</p>

<!-- This is also valid after having a closing tag -->


<img src="/images/xhtml.gif" />

4.8.5 Attribute Quotes


The XHTML attributes values must be quoted. Otherwise, the XHTML document is considered
as an invalid document. Here is the example showing syntax −

<!-- This is an invalid XHTML syntax -->


<img src="/images/xhtml.gif" width=350 height=100 />

<!-- The valid XHTML syntax is as follows -->


<img src="/images/xhtml.gif" width="350" height="100" />

4.8.6 Attribute Minimization


Attribute minimization is not allowed in XHTML. It means that the attribute and its value need
to be explicitly stated. The following example shows the difference −

<!-- This is an invalid XHTML syntax -->


<option selected>

<!-- The valid XHTML syntax is as follows -->


<option selected="selected">

The following table shows a list of the minimized attributes in HTML and the way to write them
in XHTML −
HTML Style XHTML Style
Compact compact="compact"
Checked checked="checked"
Declare declare="declare"
Readonly readonly="readonly"
Disabled disabled="disabled"
Selected selected="selected"
Defer defer="defer"
Ismap ismap="ismap"
Nohref nohref="nohref"
Noshade noshade="noshade"
Nowrap nowrap="nowrap"
Multiple multiple="multiple"
Noresize noresize="noresize"
<a> Should not contain other <a> elements.
<pre> Should not contain the <img>, <object>, <small>,
<big>, <sup> or <sub> elements.
<button> Should not contain the <input>, <select>, <textarea>,
<label>, <button>, <form>, <fieldset>, <iframe> or
<isindex> elements.
<label> Should not contain other <label> elements.
<form> Should not contain other <form> elements.

Table 4.3: Minimized Attributes in HTML

4.8.7 Different from HTML:


Document Structure
XHTML DOCTYPE, the xmlns attribute in <html>, <html>, <head>, <title>, and <body>
are mandatory.
XHTML Elements
• Properly nest the XHTML elements.
• Always close the XHTML elements.
• XHTML elements should be in lowercase.
• one root element for each XHTML document.
XHTML Attributes
• Attribute names should be in lower case.
• Quote the attribute values.
• Forbid attribute minimization.

4.9.8 Conversion from HTML to XHTML

• An XHTML <!DOCTYPE> to the first line of every page is added.


• An xml attribute to the html element of every page is added.
• All element names should be changed to lowercase.
• Empty elements should be closed.
• All attribute names should be changed to lowercase
• All attribute values should be quoted.

4.9 Summary
This unit explored the concepts of SGML and XML and their usage in HTML pages. HTML is
the general markup language for the Web. The HTML format text, add graphics, create links,
input forms, frames and tables, etc., and save it all in a text file that any browser can read and
display. XML documents shape a tree structure that starts at "the root" and branches to "the
leaves". All modern browsers have a built-in XML parser that can read and manipulate any XML
document. The DOM (Document Object Model) characterizes a standard way for getting to
XML. The XMLHttpRequest object provides an approach to communicate with a server after a
web page has been loaded. XML Namespaces give a technique to maintain a strategic distance
from component name clashes.

4.11 Question for exercise


1. What is SGML? Explain in brief.
2. What is xml? Explain with an example? What are types of attributes used in Xml?
3. Compare and contrast XML and HTML.
4. List the rules for naming XML elements.
5. What are XML elements? What are the attributes types of XML?
6. Discuss the importance of using XSDs.
7. What is the Difference between XML and HTML?
8. Explain how XML data modelling can be done.
9. What do you mean by XLST? What is need of XLST?
10. Explain the declaration type of XLST.

4.12 Suggested Reading

• HTML by Jon Duckett, HTML and XHTML: The definitive guide by O’Reilly media
• XML by O’Reilly media
UNIT- 5: Creation of Dynamic Web Pages using JSP
UNIT STRUCTURE
5.0 Objective
5.1 Dynamic Web Page
5.2 Introduction of JSP
5.3 Pages Overview
5.4 JSP Scripting
5.5 Standard Action
5.6 Page Directive
5.7 Include Directive
5.8 Summary
5.9 Questions for Exercise
5.10 Suggested Readings

5.0 Objective
A server-side dynamic web page is created by using server-side scripts which are processed by
an application server. The application server controls the server-side dynamic web page. The
parameters of the server-side script determine the assembling of every new web page that
incorporates more customer side handling. The following unit explains core concepts of creating
dynamic web pages and introducing the concepts of JSP. It also sheds light on JSP scripting and
page directive. With the help of this unit the reader will be able to create the web pages
dynamically and use various scripting.

5.1 Dynamic Web Page


Dynamic web page is one which reveals different information at different time. A part of the web
page can be changed easily rather than loading the entire web page or document of the web page.
To make any change in the content of the web page, the dynamic web page is reloaded by user or
program. The server or the updated DOM (document object model) of the page can call the
updating information. This can either lead to the truncation of the browsing history or can create
a saved version to go back to it. The advantage of using Ajax technologies to update a dynamic
web page will eradicate this i.e. it will neither truncate the web browsing history of the page
being displayed nor create a page to go back. In spite of varying webpage content, the Ajax
technology renders the end user only one dynamic page managed as a single page. The Ajax
engine resides on the browser only, requesting parts of the DOM (from an application server to
its clients).
The following are two types of web pages:
5.1.1 Server-Side Dynamic Web Page
Server-side scripting is used to create server-side dynamic web page. The parameters of the
server-side script determine the assembling of every new web page that incorporates more
customer side handling.
5.1.2 Client-Side Dynamic Web Page
Client-side scripting such as JavaScript is used to process client-side dynamic web page. The
script is then passed to the Document Object Model (DOM).

5.2 Introduction to JSP (Java Server Pages)


Dynamic web applications can be developed using JSP technology. The JSP pages are much
easier to maintain than a Servlet. JSP pages are quiet opposite of Servlets, as servlet embeds
HTML code inside a Java code, while JSP embeds Java code inside HTML with the help of JSP
tags. The JSP can perform every task a Servlet can do. The Presentation and Business logic are
easily separable in JSP as a web designer design and update JSP pages using presentation layer
whereas, a java developer write server-side complex codes without being concerned about web
design. The presentation layer and the business layer can easily interact over HTTP requests. The
java codes can be easily embedded into HTML tags in JSP.
Java Server Pages is a server-side technology which does all the processing at server. It is
generally used to create dynamic web applications using java. Any html file can be easily
converted to a JSP file only by changing the file extension from “.html” to “.jsp”, and it will run
just fine. JSP differs from HTML in ability of using java code inside HTML. In JSP, Java code is
embedded in HTML using JSP tags. For e.g. every time we run this code, it will display the
current time. This shows this code is dynamic.
<HTML>
<BODY>
Hi Beginner
Current time of the day: <%= new java.util.Date() %>
</BODY>
</HTML>

5.2.1 Your First JSP


Let us start our reading by a JSP example
Example:

<%-- JSP comments -- %>


<HTML>
<HEAD>
<TITLE>Title </TITLE>
</HEAD>
<BODY>
<%out.print ("This is a Sample JSP code");%>
</BODY>
</HTML>

Output:

This is a Sample JSP code.


5.2.2 Explanation of above code:

i) <%–JSP Comment–%>: This represent JSP Comments. This tag is used for adding comments
to a JSP page. Further details will be discussed later
Note: Comments starts with a tag <%– and ends with –%>.

ii) The HTML tags like Head, Title and Body are frequently used. The content within these tags
will be delivered in a similar way to client (Web browser).

iii) Scriptlets are the JSP elements that contain Java codes. <%out.print (“Sample JSP code”)
;%> is an example of Scriptlet. Syntax of scriptlet is: <%Executable java code%>. As the java
code ends with semicolon (;), so, the Scriptlets. out.print (“Sample JSP code”) is a java
statement, which prints“Sample JSP code ”.

Both static and dynamic contents are there in dynamic webpages. Static content will have only
text-based formats defined in HTML or XML whereas, the java code embedded inside the
HTML used as JSP tags generates the dynamic content.

5.2.3 Difference between Servlet & JSP


Like JSP, Servlets also generates dynamic webpages. One of the major difference is that servlet
embed HTML code inside java while the JSP does the opposite. Few other points are:

Servlets
1. A Servlet is a Java program.
2. Servlets supports HTML tags.
3. It is used for developing the business layer of an enterprise application.
4. Java developers create and maintain the servlets.

JSP
1. JSP program is a HTML code.
2. It supports the java statements by embedding it into HTML using JSP tags.
3. Differentiate the presentation layer and business layer. So, both can be developed
separately easily of an enterprise application
4. Web developers uses JSP frequently used for designing websites.

5.2.4 Advantages of JSP over Servlet


1. JSP has the preferences of servlet, as it gives better performance than CGI built-in
session features. It also inherits java features like – multithreading, database connectivity,
exception handling and few more.
2. JSP also separates the content generation from content making it more flexible.
3. With the use of the JSP, it will be now easy for a web designer to present the information
needed.
4. The web application programmers can now fully concentrate on processing/building the
information.
5.2.5 JSP Application Architecture
Before starting to develop a web application, we must have a basic idea of its architecture. Based
on the request processing location (Servlet or JSP) two architectures for JSP has been formulated
which are– Model1 Architecture & Model2 Architecture.

1) Model 1 Architecture: In case of the Model 1 architecture JSP will play key role. All the
requests made by the client are processed by JSP. A bean object is created by JSP as the client
(web browser) requests. The created object completes the request and passes the response to the
JSP. The response is sent by JSP to the client. In this model, JSP performs most of the
processing. Figure 5.1 represents Model 1 Architecture.

Figure 5.1: Model 1 Architecture

2) Model 2 Architecture: In Model 2, the major role is played by servlets and the client’s (web
browser) request is processed by it. The JSP only takes care of the presentation part (GUI part)
by using bean object created by servlet. Here, the controlling and request processing tasks is
performed by servlet only. The bean object is created by servlet when required by the JSP page
and then calls the respective JSP page as the request made by client. For this type of Model, JSP
doesn’t do any type of processing whereas, Servlet performs all the required processing. Figure
5.2 shows Model 2 Architecture.
Figure 5.2: Model 2 Architecture

5.3 Pages Overview


Java Server Pages (JSP) is an innovation which is utilized for building up the Webpages that
backings dynamic substance conveyance. It helps the developers to embed java code in HTML
pages, which makes the utilization of JSP tags, Java Server Pages which begin with <% and end
with %> is generally a sort of servlet which fulfills the role of a user interface is designed that is
towards a Java web application. Utilizing Java Server Pages, we can present records from a
database and could gather users through Webpage forms. Web developers generally compose
text files such as JSPs that combines HTML or XHTML code. or any other source, that creates
Webpages dynamically. These JSP tags are utilized for several purposes such by accessing the
JavaBeans components, as gathering database information or registering user preferences,
sharing information between requests and passing control from one page onto the next, and
pages etc.

5.3.1 Why Use JSP?


JSP is similar to Common Gateway Interface (CGI). In case JSP provide several advantages over
CGI:
• Altogether better performance is provided because JSP embeds Dynamic Elements in
HTML Pages as opposed to have distinguishable CGI files.
• The server always compiles JSP before processing whereas, the server loads the
interpreter and the target script each time the page is requested in CGI/Perl.
• JSP are built over Java Servlets API, so JSP can use all the powerful Enterprise which
include JDBC, JNDI Java APIs, EJB, JAXP, and so on.
• JSP pages that handle the business logic can be used in combination with servlets
o This is supported by the Java servlet template engines model.
We lastly conclude that an integral part of Java EE, is JSP which is a complete enterprise class
applications platform. This illustrate that JSP plays a major role from the simplest applications to
the most complex and demanding one.

5.3.2 Advantages of Using JSP


Following are the advantages of JSP over other technologies:
Versus Active Server Pages (ASP) technology
The twofold advantages using JSP are: a) The dynamic part written in Java is more powerful and
easier as compared to different MS specific language like Visual Basic. b) It is versatile to non-
Microsoft Web servers and other operating systems.
Versus Pure Servlets technology
Most convenient part is to adjust and to write customary HTML rather to have a lot statements
that produce the HTML like println.
Versus Server-Side Includes (SSI) technology
SSI is intended extremely intended that utilize form data for basic inclusions, it makes database
connections, and so forth.
Versus JavaScript technology
HTML could be however created dynamically on the client that can barely interact to perform
complex assignments with the web server like image processing and database access and so
forth.
Versus Static HTML
Normal regular HTML as it is statically defined cannot contain dynamic information.

5.3.3 JSP Architecture

Figure 5.3: JSP Architecture


The above diagram shows the JSP architecture. can The JSP page of web container is directly
accessed by the web browser. The JavaBeans of the web container representing the application
model is interacted by JSP pages. Upon request made by the client through JSP page, the
response is sent back to the client depending on the requests which are invoked by the client
request. The JavaBeans are used by JSP pages to get data from the database, if response requires
accessing the database.

5.3.4 Life Cycle of JSP


JSP pages follow these stages:
• Translation to servlet code
• Compiling to byte code
• Loading the servlet class
• Creating the servlet instance
• Calling jspInit method
• Calling _jspService method
• Calling jspDestroy method

5.3.4.1 Translation: In the initial step, the JSP file is converted the web container converts the
into a Java source file containing servlet class definition by the web container. The JSP pages
and tag files are validated by the web container.

5.3.4.2 Compilation: The servlet source code is compiled into a Java class file by the web
container in this step.

5.3.4.3 JSP Page Class Loading: The servlet class byte code is stacked into the web container’s
JVM software using class loader in this step.

5.3.4.4 JSP Page Servlet Instance: An instance of the servlet class is created by the web
container in this step.

5.3.4.5 JSP Page Initialization: The servlet is initialized by calling the jspInit() method by the
web container. As the method is created, it is called immediately. It is called only once during
JSP life cycle.To perform initialization we need to override jspInit() method:

public void jspInit (){


//write your code
}

5.3.4.6 JSP Page Service: The requests are now serviced by the initialized servlet. The user
request is processed by calling _jspService () method by the web container. This method is called
for each request during its life cycle. The method takes HttpServletRequest and
HttpServletResponse parameters.

5.3.4.7 JSP Page Destroyed: The JSP servlet instance is being expelled (removed) from the web
containers service by calling the jspDestroy () method which permit JSP page to clean the
resources. This ends the JSP life cycle. This method can be written as follows:
public void jspDestroy()
{
//write your code
}

5.3.5 JSP Syntax


This section enlightens us about basic syntax in Java Server Page and define them in brief such
as Scriptlet, Declarative, Expression and Comments.

Syntax Name Code


Scriptlet Tag <% java code for statement %>
Declarative tag <%! Statements %>
Expression tag <% = Statements %>
Comment tag <%-----comments provided------ %>

5.3.5.1 The Scriptlet Tag


This tag is used to embed Java code in JSP. The syntax is as follows:

<% java code %>

Example using scriptlet tag


Example:

<% float j=5.0; %>

5.3.5.2 The Declarative Tag


This tag is used for including members either attributes or methods in to the JSP servlet class.
The syntax is as follows:
<! Statement for loop %>

Example using declarative tag


Example:

<! int increment=0; %>

5.3.5.3 The Expression Tag


The Java language expression is written in this tag for evaluation during HTTP request and is
then included in HTTP response stream. The syntax is as follows:

<%= expression %>

Example using expression tag


Example:

The time and date of the day is: <%= new java.util.Date () %>
5.3.5.4 The Comment Tag
This tag is used to ignore or hide some parts of the code. The syntax is as follows:

<% - -comment -- %>

Example using comment tag


Example:

<%-- JSP comment is like this -- %>

Example to demonstrate use of above mentioned scripting languages


Example:

<%! int fontSize=5;%><br>


<html>
<head>
<title>our example</title>
</head>
<body>
<%-- program to add --%><br>
<%
int x = 9 ;<br>
int y = 1; <br>
int output = x+y; %><br>
<font color="blue" size="<%= fontSize %>"><br>
<% out.print(" Total=" +output); %><br>
</font><br>
</body>
</html>

Output:

Total=10

5.4 JSP Scripting


For JSP Scripting element <% %> tags are used to write the code. During translation of the JSP
page, the code inside <% %> tags are processed by the JSP engine. Any other text in the JSP
page is considered as HTML code or plain text. Just for experiment, try removing the <%
%> scriplet tag from the above code and run it as JSP. We will see that everything is printed as it
is on the browser, because without the scriplet tag, everything is considered plain HTML code.

5.4.1 JSP Scripting Elements


In this Book we will figure out the use of JSP Expressions. JSP uses three types of scripting
elements:
• JSP Expressions: The linguistic structure is “<%= some java code %>”. Small java code
can incorporate into a JSP page using this tag.
• JSP Scriptlet: Multiple lines of Java code can be inserted using this tag. The syntax for
scriptlet is “<% some java code %>”.
• JSP Declaration: This tag is used for declaring variable or method. The syntax for
declaration is “<%! Variable or method declaration %>”, in here we
Let’s have a look at these in detail.

5.4.1.1 JSP Expressions


This element is used compute a single line small expression and the HTML containing the result
is returned to the browser.
Example:

The time on the server is <%= new java.util.Date () %>

Output:

The time on the server is Friday March 23 05:24:33 GMT 2018.

Explanation
The “new java.util.Date ()” has processed the actual date and time of the HTML on the browser.
Few other examples:
Examples
• This example shows expression for converting lower case string to upper case. Here is
the code:
The Expression: Following expression is used for converting a string to uppercase.
<%= new String(“Hello World”).to Uppercase() %>. A “string” object with value “Hello
World” is created. After that, a Java function “.toUpperCase” is called to convert the string to
upper case.
The HTML: Converting a string to uppercase: HELLO WORLD
• Mathematical expressions can also be used in JSP.
The Expression: 40 multiplied to 5: <%= 40*5 %>. We can easily compute and get answers to
mathematical problems using simple mathematical expressions embedded in our HTML.
The HTML: 40 multiplied to 5: 200.
• Boolean expressions can also be used in JSP.
The Expression: Is 79 less than 65? <%= 79 <65 %>. The return type is always string either
going to be “true” or “false” of these Boolean expressions.
The HTML: Is 79 less than 65? False

5.4.1.2 JSP Scriptlets


A lot of Java code can be embedded in your HTML code by using this JSP Scripting Element.
While the web server processing the page, the Java code is processed from top to bottom. The
syntax is very similar as we don’t have to put in an equal sign after the opening % sign. Here,
we have to use “out.println()” to show what we want to mix with HTML rather than directly
combining the result of the code with the HTML rather. Here is an example:

Example:

<h2> Hello World</h2>


<%
for (inti=0; i<= 5; i++)
{
out.println(“<br/> I love counting: ” + i);
}
%>

Output:

I love counting: 1
I love counting: 2
I love counting: 3
I love counting: 4
I love counting: 5

Explanation
In the above example, a basic h2 heading has been set up. Then, we have a “for loop” in the
scriptlet. Don’t put in a lot of code in a scriptlet in JSP. It will be easily manageable and
readable. Try refactoring this code into different Java classes and make use of MVC to keep it
under control if we can’t find any other option.
In each iteration of the loop we are printing the “I really love counting” and appending it with
the integer value of the “i” printed through the HTML.

5.4.1.3 JSP Declarations


Using the JSP declaration we are declaring the method in the beginning of the code and then
calling the same method whenever we need in the same page. This declaration come in handy
when we have a code snippet that we want to be executed more than once. The syntax is simple:

Code:

<%!
String makeItLower(String data)
{
returndata.toLowerCase();
}
%>

Example:
Lower case “My Program” :< %= makeItLower (“My Program”) %>

Output:

Lower case “My Program” :< %= makeItLower (“My Program”) %>

Explanation
In the method declaration we are having our standard java method with the return type of a
String. We take a string as an argument and return it converted to a lower case. Later we call this
function through a JSP Expression.

5.5 Standard Action


In this topic, we are discussing Actions in JSP. We can dynamically insert any file, reusing
JavaBeans components, generating HTML for the Java plugin or forward the user to another
page. There is just a single syntax for, as it fits in to the XML to the elements Action.

<jsp:action_name attribute = "value of the attribute" />

The accompanying lists out the table accessible to JSP actions :


Syntax Purpose

jsp:include file is Included or a record is made at the time


the page is asked
jsp:forward Forwards the request into a new page

jsp:setProperty It sets the property of a JavaBean and includes


it
jsp:getProperty The property of a JavaBean is inserted into our
output
jsp:useBean This Finds a JavaBean or instantiates it

jsp:body This dynamically Defines element's body


which is in XML
jsp:element It is defining dynamically XML elements

jsp:attribute This Defines element's attribute which is


dynamically-defined in XML
jsp:text It reports and is used for composing template
and text in JSP pages
jsp:plugin It Generates makes an EMBED or OBJECT
tag code particular to browser than for the Java
module
Table 5.1: JSP Actions
5.5.1 Common Attributes
For the most part that are common, basically to all components of Action are: the scope attribute
and the id characteristic.

5.5.1.1 Id attribute
If an instance of the Action is created of an object, through the implicit object, it can be
referenced through its id value can be used to it through certain PageContext. The id attribute is
uniquely recognizing the Action element, and enables the action to be referenced inside the JSP
page.

5.5.1.2 Scope attribute


The scope attribute is distinguishing that the characterized Action lifecycle of an element or
component. As the scope attribute decides the object lifespan which is associated with the id
value, the id property and the scope attribute are straightforwardly relating to each other . This
attribute consists of four possible values identified to it: (a) session, (b) request, (c) page (d)
application.

5.5.2 The <jsp:include> Action


The above include action allows us to embed into the page the files being that have been created
(generated). The syntax is depictes as follows:

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

This activity embeds a file at the time requested by the page. Different from
the include directive, at the time the JSP page is translated (converted) it inserts the file into a
servlet. Next follows a table that lists out the properties associated with the incorporate action:

Attribute Description

Flush Whether or not the included asset has its buffer


removed is decided by the boolean attribute
before it is included.
Page The predefined page which is to be
incorporated its relative URL is found.

Table 5.2: Properties Associated with <include> Action


Example:
Give us a chance to characterize the two records main.jsp and date.jsp which are as shown
below. Following is the substance of the record for date.jsp:

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>


Following is the substance of the main.jsp:

<html>
<head>
<title>Example of include action</title>
</head>
<body>
<center>
<h3> Example of “include action” </h3>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html>

Output:

Example of “include action”


Today's date: 12-Sep-2010 14:54:22

5.5.3 The <jsp:useBean> Action


The useBean action normally searches for an object that is existing, it uses the id and scope
variables. This action is quite versatile. It tries to create a particular object, when an object is not
found.
The least difficult syntax for a bean to be able to load it is:

<jsp:useBean id = "name" class = "package.class" />

Once any bean class to be loaded into the page has been loaded, we can jsp: getProperty and
use jsp: setProperty actions for retrieving and modifying the properties of the bean. The table
below lists the attributes of useBean action

Attribute Description

Type Type of the variable is Specified which will be


included to refer to an object.
Class Full package name is assigned to the bean.

bean Name The name of the bean as indicated by the


instantiate () method of the java.beans.Beans
class is shown.

Table 5.2 Attributes of useBean Action


Give us now a chance to talk about the jsp:setProperty and the jsp:getProperty actions before
giving a valid example related to these actions.
5.5.3.1 The <jsp: setProperty> Action
The Bean ought to have been defined beforehand using this action. This action sets the Bean
properties. There are ways to utilize the setProperty action mainely two of them are given below:
The jsp:setProperty can be used after but outside of an element which is jsp:useBean , as given
below:

<jsp:useBean id = "Name" ... />


...
<jsp:setProperty name = "Name" property = "Property" .../>

Context for which jsp:setProperty appears is inside jsp:useBean body. The jsp:setProperty is
executed regardless of whether we are executing a new bean or an existing bean is found as
shown below:

<jsp:useBean id = "Name" ... >


...
<jsp:setProperty name = "Name" property = "Property" .../>
</jsp:useBean>
In the case the jsp:setProperty is not executed if an existing one was found. It is
executed only if a new object is instantiated.
5.5.3.2 The <jsp:getProperty> Action
The getProperty action is utilized in recovering the value of a given property is changed to
string, which is embedded into its output . The getProperty action comprises of two
characteristics, the properties are required. The getProperty action syntax is as per the following:

<jsp:useBean id = "Name" ... />


...
<jsp:getProperty name = "Name" property = "Property" .../>

Example
On testing the bean class:
/* File: TestBean.java */
package action;
public class TestBean {
private String message = "No message specified";
public String getMessage() {
return(msg);
}
public void setMessage(String msg) {
this.message = msg;
}
}
On Compiling code to generate TestBean.class file which ensure that we copied into C:\apache-
tomcat-7.0.2\webapps\WEB-INF\classes\action path the TestBean.class and the CLASSPATH
variable this folder is ought to be set .This code is used in main.jsp file. This sets/gets the bean
and loads it in a straightforward String parameter:
Output:

Using JavaBeans in JSP


Got Text….
Hi JSP.....

5.5.4 The <jsp: forward> Action


This action is used to terminate the current page action and the request is forwarded to another
resource such as static page, Java Servlet, JSP page. Following is the syntax for
the forward action:

<jsp:forward page = "Relative URL" />

Example:
On reusing the files date.jsp and main.jsp.The content of the date.jsp file is:

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

The main.jsp file content:

<html>
<head>
<title> This is index page </title>
</head>
<body>
<center>
<h2> This is index page </h2>
<jsp:forward page = "date.jsp" />
</center>
</body>
</html>

By keeping every one of the document in the directory which is the root and trying to
access main.jsp. The result will be as depicted underneath. Here the content of it is discarded
from the main page and show content from page requested only.
Output:

Today's date: 15-Sep-2015 15:55:22

5.5.5 The <jsp:plugin> Action


This action is utilized typically in inserting some components of Java into page. It decides the
browser type and helps in inserting the <object> or <embed> needed tags. On the off chance that
the required plugin is not there, then it is downloaded and then Java components are executed.
The plugin action contains of attributes that correspond to common HTML tags used to format
Java components. The Java component can be likewise an Applet or a JavaBean.
The parameters for Applet or Bean is sent by using the <param>. The syntax of plugin action
usage:

Example:

<jsp:plugin type = "applet" codebase = "dir" code = "Applet.class"


width = "80" height = "100">
<jsp:param name = "fontcolor" value = "blue" />
<jsp:param name = "background" value = "red" />
<jsp:fallback>
Unable to initialize the Java Plugin
</jsp:fallback>
</jsp:plugin>

We try using some applet for this action. A new <fallback> element, to specify a message can be
used error string to be sent to the user in case the component fails.
Output:

The <jsp:element> Action


The <jsp:attribute> Action
The <jsp:body> Action

5.6 Page Directive


We can code the page directives at anyplace in our JSP page. The guidelines to the container
relating to JSP current page is provided by the page directive. The directives of page are coded at
top of the JSP page by convention. The basic syntax of page directive is as follows:

<%@ page attribute = "value attr" %>

The XML code equivalent to the above syntax is as follows:

<jsp:directive.page attribute = "value attr" />

The attributes associated with the page directive are listed below:

Attribute Purpose

Buffer A buffering model is specified for the output


stream.
autoFlush Servlet output buffer behavior is controlled by
this.
contentType It characterizes the character encoding scheme.

errorPage This characterizes the URL of another JSP that


reports on Java unchecked runtime exceptions
(special cases).
isErrorPage It shows if this JSP page is a URL indicated by
another JSP page's errorPage characteristic.
Extends Determines a superclass that the produced
servlet must extend.
Import Indicates a bundle of packages or classes for
use in the JSP as the Java import statement
does for Java classes.
Info Characterizes a string that can be accessed with
the servlet's getServletInfo() method.
isThreadSafe Characterizes the threading model for the
generated servlet.
Language Characterizes the programming language used
in the JSP page.
Session Specifies whether or not the JSP page
participates in HTTP sessions.
isELIgnored Characterizes whether or not the EL expression
within the JSP page will be ignored.
isScriptingEnabled Characterizes if the scripting elements are
allowed for use.

Table 5.4 Attributes of Page Directive


Some of the above attributes are being explained below:

5.6.1 The buffer Attribute


The buffer attribute is used to specify the buffering characteristics for the server output response
object. It directs the servlet to write to the buffer before writing to the response object. We may
code an estimation of "none" to indicate no buffering so that the servlet output is promptly
directed to the response object or you may code a maximum buffer size in kilobytes. To
coordinate the servlet to write the output directly to the response output object, use the following:

<%@ page buffer = "none" %>

Use the accompanying to direct the servlet to compose (write) the output to a buffer of size not
less than 8 kilobytes

<%@ page buffer = "16kb" %>

5.6.2 The autoFlush Attribute


This attribute is used to flush automatically or to generate an exception message when the buffer
is full. The autoFlush characteristic i.e. attribute specifies whether or not the buffered output
should be flushed automatically. The true value (default) indicates automatic buffer flushing and
a value of false throws an exception. The accompanying directive is responsible for throwing an
exception when the servlet's output buffer is full:

<%@ page autoFlush = "false" %>

This directive directly flush the output buffer when full:

<%@ page autoFlush = "true" %>

Generally, the autoFlush attributes and the buffer are coded on a single page directive as follows:

<%@ page buffer = "16kb" autoflush = "true" %>

5.6.3 The contentType Attribute


The default content type is text/html, which is the standard content type of HTML pages. The
contentType attribute is used to set the character encoding for a JSP page and for the generated
response page.
If we want to write out XML from our JSP, we can do using following directive:

<%@ page contentType = "text/xml" %>

The accompanying statement directs the browser to render the generated page as HTML:

<%@ page contentType = "text/html" %>

The accompanying directive sets the content type as a Microsoft Word document

<%@ page contentType = "application/msword" %>

5.6.4 The errorPage Attribute


The errorPage attribute is used for telling the JSP engine to run a page if there is an error while
the current page running. The corresponding URL serve as the value of the errorPage attribute.
When all uncaught special cases are caught, then the directive displays MyErrorPage.jsp as
foolow:

<%@ page errorPage = "MyErrorPage.jsp" %>

5.6.5 The isErrorPage Attribute


The default value of the isErrorPage attribute is false. The isErrorPage characteristic indicates
that the current JSP can be utilized as the error page for another JSP. The value of isErrorPage is
either true or false. For instance, the handleError.jsp sets the isErrorPage option to true because it
should deal with errors:

<%@ page isErrorPage = "true" %>

5.6.6 The extends Attribute


The extends attribute is determining a superclass that a produce a servlet must extend. For
instance, the following directive directs the JSP translator, to create the servlet such that the
servlet extends somePackage.SomeClass:

<%@ page extends = "somePackage.SomeClass" %>

5.6.7 The import Attribute


The import attribute is serving an indistinguishable function as, and carries on like, the Java
import explanation. The value for the import alternative is the name of the package we are
importing .To import java.sql.*, use the following page directive:

<%@ page import = "java.sql.*" %>

For importing multiple packages, we can specify them separated by comma as follows:

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


5.6.8 The info Attribute
The info attribute lets you provide a description of the JSP. The following is a coding example:

<%@ page info = "This JSP Page Written by ZARA” %>

5.6.9 The language Attribute


The language attribute specifies the programming language used in scripting the JSP page.
For instance, since we usually use Java as the scripting language, our language option looks like
this:

<%@ page language = "java" %>

5.7 Include Directive


A file is included during the translation phase by using include directive. The content of the
other external files is merged with the current JSP by the container upon instruction from the
directive. The Include Directive can be anywhere in your JSP page. The syntax of the directive is
as follows:

<%@ include file = "relative url" >


The filename in the include directive is a relative URL. If only a filename with no associated
path is specified, the JSP compiler searches that file in the same directory as your JSP. The XML
code equivalent of the above syntax is as follows:
<jsp:directive.include file = "relative url" />

Example
Including a typical header and footer with multiple pages of content is a good example of
include directive. Following three files have been defined below: (a)header.jps,(b)footer.jsp,
and (c)main.jsp.
header.jsp content is as follows:
<%!
int pageCount = 0;
void addCount() {
pageCount++;
}
%>
<% addCount(); %>
<html>
<head>
<title>An example of Include Directive </title>
</head>
<body>
<center>
<h2> An example of Include Directive </h2>
<p>You have visited this site <%= pageCount %> times.</p>
</center>
<br/><br/>

footer.jsp content is as follows:

<br/><br/>
<center>
<p>Copyright © 2015</p>
</center>
</body>
</html>

main.jsp content is as follows:


<%@ include file = "header.jsp" %>
<center>
<p>Thank you for visiting this page.</p>
</center>
<%@ include file = "footer.jsp" %>

Output:
An example of Include Directive
You have visited this site 1 times.
Thank you for visiting this page
Copyright © 2015

By refresh main.jsp and the page hit counter keeps increasing.


Webpages can be designed based on your creative instincts; it is recommended to keep the
dynamic parts of the website in separate files and then merging them in the main file. This is
convenient for whenever a part of the webpage need to be changed.

5.8 Summary
In this whole unit we have learned about jsp and how to create web pages using jsp and different
concepts related to use of jsp for different purposes. We have gone through jsp overview its
syntax and tags and how to use it for rendering different contents we have also learned about
arrays and how to define call and use them. The chapter also illustrates differences between
object and arrays and how they are instantiated. At last a brief explanation of the page directives
and include directives have been provided.

5.9 Questions for Exercise


1. What is jsp? Write a sample code for jsp using any simple example and explain all contents
used in code?
2. List various advantages of jsp along with its architecture.
3. Explain any 5 syntax for jsp action. Illustrate with example.
4. Discuss the lifecycle of jsp using suitable diagram.
5. Give an overview of page directive and include directive used in jsp.

5.10 Suggested Readings


• Pure JSP: Java Server Pagesby James Goodwill (Sams, 2000)
• JavaServer Pagesby Larne Pekowsky (Addison-Wesley, 2000)
• Instant JavaServer Pagesby Paul Tremblett (Osborne McGraw-Hill, 2000)
• Web Development with JavaServer Pagesby Duane K. Fields and Mark A. Kolb
(Manning Publications, 2000)

You might also like