You are on page 1of 130

Web Technologies - Syllabus

Unit1: Basics of
Internet

The Internet; WWW; Domain Names and Addresses; Web Hosting; DNS; Web publishing;
Web Browsers & Web Servers; Web Pages; Web sites; Concept of Search Engines; Search
engines types; searching the Web and Web Servers; URL; MIME; HTTP; Electronic mail;
ftp; telnet; finger.

Unit2: HTML5

Introduction to HTML5, The browser wars, features of HTML5, Structural Elements, New
Form/Input Elements, New Attributes, Canvas, Simple shapes, shapes styles, complex
shapes, Text and Shadows, canvas pitfalls, canvas & SVG, audio and video, web storage,
web sockets, web workers, indexed DB, drag and drop, web notifications.

Unit3: DOM AND


jQuery

Recap JavaScript; JQuery introduction; ready Function; jQuery Documentation; jQuery


Selectors; DOM Traversal; DOM Manipulation; jQuery Event Model, Handling Events with
jQuery; jQuery UI Overview; Animation and Special
Effects.

Unit4: HTTP Server


Programming

HTML forms and CGI; HTTP; Servlet Programming; The Life Cycle of a Servlet; Using
Tomcat for Servlet Development; A simple Servlet; deployment of simple servlets, web
server (Java web server / Tomcat/ Web logic) The Servlet API; The Javax.servlet Package;
Reading Servlet Parameter; The Javax.servlet.http package; Handling HTTP Requests and
Responses, HTTP GET and POST methods, Using Cookies; Session Tracking.

Unit5: JSP and XML

Java Server Pages (JSP); JSP, JSP life cycle, Tags, Tomcat, Request String, User Sessions,
Cookies, Session Objects; XML – Tags, Elements, Attributes, XML with CSS, XML and
DTD (Document Type Definition), XML Schema.
Web Browsers, Servers and Search Engines

In this lesson we will be learning about the following.

1. Web browsers and servers

2. Web pages and sites

3. Concept of search engines and their types

Web browsers and servers

For International Network communication, we require a web browser and web servers. Web
browser and servers play an important role to establish the connection. The client sends
requests for web document or service. The message goes from the web browser to the web
server is known as an HTTP request. When the web server receives the request, it searches its
stores to find the appropriate page. If the web server is able to locate the page, it parcels up to
the HTML contained within (using some transport layer protocol), addresses these parcels to
the browser (using HTTP), and transmit them back across the network.
If the web server is unable to find the requested page, it sends a page containing an error
message (i.e. Error 404 – page not found) and it parcels up to the dispatches that page to the
browser. This message received by the web browser by the server is called the HTTP
response.

The main differences between the Web browser and web servers are:

WEB BROWSER WEB SERVER

Web Browser is an Application program


that displays a World wide web document. Web server is a program or the computer that
It usually uses the internet service to provide services to other programs called client.
access the document.

The Web server accepts, approve and respond to


The Web browser requests the server for
the request made by the web browser for a web
the web documents and services.
document or services.

The web browser act as an interface The web server is a software or a system which
between the server and the client and maintain the web applications, generate response
displays a web document to the client. and accept clients data.

The web browser sends an HTTP request The web server gets HTTP requests and send
and gets an HTTP response. HTTP responses.

There exist three types of processing models for


Doesn’t exist any processing model for the
web server i.e Process-based, Thread based and
web browser.
Hybrid.
WEB BROWSER WEB SERVER

Web browser stores the cookies for Web servers provide an area to store and
different websites. organize the pages of the website.

The web server can be a remote machine placed


The web browser is installed on the client at the other side of your network or even on the
computer. other end of the globe, or it is your very own
personal computer at home.

Web pages and site

There are many terms and terminologies that are associated and let us understand each one in
detail.

Web page
A document which can be displayed in a web browser such as Firefox, Google
Chrome, Opera, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also
often called just "pages."
Website
A collection of web pages which are grouped together and usually connected together
in various ways. Often called a "web site" or simply a "site."
Web server
A computer that hosts a website on the Internet.
Search engine
A web service that helps you find other web pages, such as Google, Bing, Yahoo, or
DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you
can perform search engine searches directly in the address bar of Firefox, Chrome,
etc.) or through a web page (e.g. bing.com or duckduckgo.com).
How search engines work?

There may be some differences in how the search engines work but the fundamentals remain
the same. Each of them has to do the following tasks:

1. Crawling
2. Indexing
3. Creating results
1. Crawling

Search engines have their own crawlers, small bots that scan websites on the world wide web.
These little bots scan all sections, folders, subpages, content, everything they can find on the
website.

Crawling is based on finding hypertext links that refer to other websites. By parsing these
links, the bots are able to recursively find new sources to crawl.

2. Indexing

Once the bots crawl the data, it’s time for indexing. The index is basically an online library of
websites.

Your website has to be indexed in order to be displayed in the search engine results page.
Keep in mind that indexing is a constant process. Crawlers come back to each website to
detect new data.

3. Creating results

Search engines create the results once the user submits a search query. It’s a process of
checking the query against all website records in the index. Based on the algorithm, the
search engine picks the best results and creates an ordered list.

Search Engine Algorithm

A search engine algorithm is a unique formula that determines how the websites are sorted in
the search engine results page. It’s a trademark of each search engine, therefore, it’s kept
secret.

The algorithm is a mixture of various ranking factors. You will find many articles dealing
with the “real” Google ranking factors. The truth is that even when you know what the
factors are, you don’t know their exact weights.

The most important ranking factor of all search engines should be the relevancy. The main
goal of search engines is to find what the internet user is looking for.

When it comes to Google, the major ranking factors are:

• Website/content relevancy
• Strength and relevancy of backlinks

Some of the other very important ranking factors are:

• Mobile optimization
• Content structure and optimization
• Usability
• Accessibility
• Page speed
• Social signals
• Overall domain authority

Popular Search engines

In terms of worldwide popularity, Google has been #1 for years. This is the list of top 10
most popular search engines:

1. Google

Google is the giant in the industry and has probably the most sophisticated algorithm. It
includes machine learning, AI and RankBrain, another algorithm that can tweak the weights
of ranking factors according to user’s behavior and quality of previous results. More than
70% internet users worldwide do their searches on Google since 1998.

2. Baidu

Baidu is the first search engine launched in China in 2000. It’s like Chinese Google. Baidu
cooperates with companies such as Microsoft, Qualcomm, Intel or Daimler on various AI
projects. Similarly to Google, they offer a lot of other solutions such as cloud services, maps,
social networking, image and video search and many others.

3. Bing

Microsoft launched their search engine in 2009 as a new project after earlier search engines
MSN Search and Windows Live Search. The main goal was to develop a competitor for
Google. From the global point of view, it’s not really there but in the US, Bing is the 2nd
most popular tool for the internet searches.

4. Yahoo!

Originally, it was one of the most widely used email providers and search engines. The
company grew significantly in the 1990s but after 2000, they somehow started lacking the
innovation and lost their value. In 2017, Yahoo! was acquired by Verizon Communications.

5. Yandex

Yandex Search is the major Russian search engine. According to Wikipedia, Yandex
generates more than 50% of all searches in Russia. Though the algorithm is not as
sophisticated as Google, it constantly gets better by integrating AI and machine learning that
analyze searches and learn from them.

6. Ask

Ask (formerly Ask Jeeves) was launched in 1996. It was designed to answer questions
submitted to the search form. Thanks to the Ask toolbar, this search engine was able to
compete with big players such as Bing, Yahoo! and Google. Unfortunately, the toolbar was
many times installed as an unwanted browser feature.

7. DuckDuckGo

DuckDuckGo is a bit different search engine. They protect the users’ privacy by not tracking
any information. DuckDuckGo doesn’t show personalized results based on your previous
searches. Likewise, advertisers can’t follow the behavior of the users. On the other hand, you
can launch ads via Bing since DuckDuckGo is their search partner together with Yahoo.

8. Naver

Naver is the Google of South Korea. This search engine covers around 75% of searches in the
country. It was launched in 1999 and in 2000 it was able to pull out various types of results
that match the entered keywords. The results included websites, images, blogs, restaurants,
shops, etc. Google launched this feature 5 years later.

9. AOL

In the 1990’s, AOL was one of the biggest crawler-based search engines. As a company,
AOL offers a lot of other services: email service, instant messenger, video content, yellow
pages, city guides. The AOL Search is nowadays used by not more than 0.5% of the internet
users.

10. Dogpile

Dogpile is a metasearch engine, so it creates the search engine results page by doing
simultaneous search requests for the same query in other search engines, namely: Google,
Yahoo!, Yandex and others. Dogpile was launched in 1995.

URL

URL stands for Uniform Resource Locator. A URL is nothing more than the address of a
given unique resource on the Web. In theory, each valid URL points to a unique resource.
Such resources can be an HTML page, a CSS document, an image, etc. In practice, there are
some exceptions, the most common being a URL pointing to a resource that no longer exists
or that has moved. As the resource represented by the URL and the URL itself are handled by
the Web server, it is up to the owner of the web server to carefully manage that resource and
its associated URL.

Every URL is made up of multiple parts, and the way yours are built will have a variety of
effects on your site’s security and Search Engine Optimization (SEO).
The following are the important parts of a URL for regular users. Let us understand each one
of it.

1. The protocol

Consider the following URL:

https://example.com/blog/fix-broken-links-in-wordpress/

The easiest part of this address to overlook is the very first part. You’re probably so used to
seeing http:// and https:// at the beginning of every URL that you don’t give it a second
thought. However, this element – the URL’s ‘protocol’ – is more important than you might
think.

The protocol tells your browser how to communicate with a website’s server, in order to send
and retrieve information. In other words, it’s what enables a URL to work in the first place.
Traditionally, most sites have used Hypertext Transfer Protocol (HTTP), and you’ll still see
this version across the web.

However, there’s been a recent move towards widespread adoption of Hypertext Transfer
Protocol Secure (HTTPS). While this protocol does essentially the same thing as HTTP, it’s a
much more secure option that encrypts the data sent back and forth between the browser and
server. That’s why most browsers give it a green security padlock:

Fortunately, making sure your own site runs on HTTPS is simple if you’re a WordPress user.
For more information, check out our guide to implementing HTTPS. All you’ll need is a free
Let’s Encrypt certificate, and the (also free) Really Simple SSL plugin.

2. The domain name

Let’s go back to the full URL for a moment:

https://themeisle.com/blog/fix-broken-links-in-wordpress/

The next part is the most identifiable element of a web address – the ‘domain name’. In this
case, it’s themeisle.com (our website!). A domain name is an identifier for a specific site,
which will generally bring you straight to the home page if nothing else is added to the end of
it.

Of course, a domain name is actually made up of two smaller parts. There’s the name of the
website in question, then the Top-Level Domain (TLD). The latter term refers to
the .com, .org, .net designator (among others) at the end of the domain name.

When you’re setting up a new site, it pays to spend some time carefully considering the
domain name you’ll use. It should be unique and attention-grabbing, but at the same time
clear and easy to remember.

Your choice of TLD matters as well. For many sites, sticking with .com is the best option. It’s
the TLD internet users are most familiar with and are usually expecting, which means it will
be easiest for them to remember. However, you can also benefit from choosing a TLD that’s
a better fit for your niche or field. There are actually hundreds of TLD options (many of
which are region- or industry-specific), so there’s plenty of choice if you want to venture
beyond a simple .com.

3. The path

If you just wanted to visit our website’s front page, all you would need are the protocol and
the domain name: https://themeisle.com. But each individual page or file on a website also
has its own URL. Once again, here’s what it looks like:

https://themeisle.com/blog/fix-broken-links-in-wordpress/

The part after the TLD is known as the ‘path’. This is because it directs the browser to a
specific page on the website. In this case, it leads first to our blog, then to a particular
post: How to Automatically Find and Fix Broken Links in WordPress. The very last part is
also sometimes called a URL ‘slug’.

Uniform Resource Locator (URL)

• A client that wants to access the document in an internet needs an address and to
facilitate the access of documents, the HTTP uses the concept of Uniform Resource
Locator (URL).
• The Uniform Resource Locator (URL) is a standard way of specifying any kind of
information on the internet.
• The URL defines four parts: method, host computer, port, and path.

• Method: The method is the protocol used to retrieve the document from a server. For
example, HTTP.
• Host: The host is the computer where the information is stored, and the computer is
given an alias name. Web pages are mainly stored in the computers and the computers
are given an alias name that begins with the characters "www". This field is not
mandatory.
• Port: The URL can also contain the port number of the server, but it's an optional
field. If the port number is included, then it must come between the host and path and
it should be separated from the host by a colon.
• Path: Path is the pathname of the file where the information is stored. The path itself
contain slashes that separate the directories from the subdirectories and files.
MIME

MIME stands for Multi-purpose Internet Mail Extensions or Multimedia Internet Mail
Extensions . It is a encoding protocol like BinHex in Mac and UUEncode in UNIX. At first it
was used as a way of sending more than just text via email. Later the protocol was extended
to manage file typing by Web servers.

Email attachment
Let's talk about email first. By using MIME, you can enclose the following types of binary
file to your text-based e-mail message:

• character sets other than ASCII


• enriched text
• images
• sounds
• other messages (reliably encapsulated)
• tar files
• PostScript
• FTPable file pointers

The easiest way to send and receive MIME attachment is to use a MIME-aware Email client
such as Netscape Mail or Microsoft Outlook. The procedure is self-explanatory. When a
MIME ready e-mail system receives a MIME encoded file, the binary file should show up as
an attachment and the proper software in your computer should be capable of reading the file.
For example, if the attached file is a PostScript file, your LaserWriter Utilities should be able
to download it to the printer. If the file is a graphic, DeBabelizer or PhotoShop should be able
to open the file.

However, you must pay attention to the file extension. For instance, if someone sends you a
JPEG image from a Mac with an extension as "JPEG," you would not be able to open it in a
PC unless you change the extension to "JPG," and vice versa.

HTTP

• HTTP stands for HyperText Transfer Protocol.


• It is a protocol used to access the data on the World Wide Web (www).
• The HTTP protocol can be used to transfer the data in the form of plain text,
hypertext, audio, video, and so on.
• This protocol is known as HyperText Transfer Protocol because of its efficiency that
allows us to use in a hypertext environment where there are rapid jumps from one
document to another document.
• HTTP is similar to the FTP as it also transfers the files from one host to another host.
But, HTTP is simpler than FTP as HTTP uses only one connection, i.e., no control
connection to transfer the files.
• HTTP is used to carry the data in the form of MIME-like format.
• HTTP is similar to SMTP as the data is transferred between client and server. The
HTTP differs from the SMTP in the way the messages are sent from the client to the
server and from server to the client. SMTP messages are stored and forwarded while
HTTP messages are delivered immediately.
Features and Transactions

Features of HTTP:

• Connectionless protocol: HTTP is a connectionless protocol. HTTP client initiates a


request and waits for a response from the server. When the server receives the request,
the server processes the request and sends back the response to the HTTP client after
which the client disconnects the connection. The connection between client and server
exist only during the current request and response time only.
• Media independent: HTTP protocol is a media independent as data can be sent as
long as both the client and server know how to handle the data content. It is required
for both the client and server to specify the content type in MIME-type header.
• Stateless: HTTP is a stateless protocol as both the client and server know each other
only during the current request. Due to this nature of the protocol, both the client and
server do not retain the information between various requests of the web pages.

HTTP Transactions

The above figure shows the HTTP transaction between client and server. The client initiates a
transaction by sending a request message to the server. The server replies to the request
message by sending a response message.

Messages

HTTP messages are of two types: request and response. Both the message types follow the
same message format.
Request Message: The request message is sent by the client that consists of a request line,
headers, and sometimes a body.

Response Message: The response message is sent by the server to the client that consists of a
status line, headers, and sometimes a body.

E-Mail Protocols

E-mail Protocols are set of rules that help the client to properly transmit the information to or
from the mail server. Here in this tutorial, we will discuss various protocols such as SMTP,
POP, and IMAP.
SMPTP

SMTP stands for Simple Mail Transfer Protocol. It was first proposed in 1982. It is a
standard protocol used for sending e-mail efficiently and reliably over the internet.

Key Points:

• SMTP is application level protocol.


• SMTP is connection oriented protocol.
• SMTP is text based protocol.
• It handles exchange of messages between e-mail servers over TCP/IP network.
• Apart from transferring e-mail, SMPT also provides notification regarding incoming
mail.
• When you send e-mail, your e-mail client sends it to your e-mail server which further
contacts the recipient mail server using SMTP client.
• These SMTP commands specify the sender’s and receiver’s e-mail address, along
with the message to be send.
• The exchange of commands between servers is carried out without intervention of any
user.
• In case, message cannot be delivered, an error report is sent to the sender which
makes SMTP a reliable protocol.

IMAP

IMAP stands for Internet Message Access Protocol. It was first proposed in 1986. There
exist five versions of IMAP as follows:

1. Original IMAP
2. IMAP2
3. IMAP3
4. IMAP2bis
5. IMAP4

Key Points:

• IMAP allows the client program to manipulate the e-mail message on the server
without downloading them on the local computer.
• The e-mail is hold and maintained by the remote server.
• It enables us to take any action such as downloading, delete the mail without reading
the mail.It enables us to create, manipulate and delete remote message folders called
mail boxes.
• IMAP enables the users to search the e-mails.
• It allows concurrent access to multiple mailboxes on multiple mail servers.

POP

POP stands for Post Office Protocol. It is generally used to support a single client. There are
several versions of POP but the POP 3 is the current standard.
Key Points

• POP is an application layer internet standard protocol.


• Since POP supports offline access to the messages, thus requires less internet usage
time.
• POP does not allow search facility.
• In order to access the messaged, it is necessary to download them.
• It allows only one mailbox to be created on server.
• It is not suitable for accessing non mail data.
• POP commands are generally abbreviated into codes of three or four letters. Eg.
STAT.

FTP

• FTP stands for File transfer protocol.


• FTP is a standard internet protocol provided by TCP/IP used for transmitting the files
from one host to another.
• It is mainly used for transferring the web page files from their creator to the computer
that acts as a server for other computers on the internet.
• It is also used for downloading the files to computer from other servers.

Objectives of FTP

• It provides the sharing of files.


• It is used to encourage the use of remote computers.
• It transfers the data more reliably and efficiently.

Why FTP?

Although transferring files from one system to another is very simple and straightforward, but
sometimes it can cause problems. For example, two systems may have different file
conventions. Two systems may have different ways to represent text and data. Two systems
may have different directory structures. FTP protocol overcomes these problems by
establishing two connections between hosts. One connection is used for data transfer, and
another connection is used for the control connection.

Mechanism of FTP
The above figure shows the basic model of the FTP. The FTP client has three components:
the user interface, control process, and data transfer process. The server has two components:
the server control process and the server data transfer process.

There are two types of connections in FTP:

• Control Connection: The control connection uses very simple rules for
communication. Through control connection, we can transfer a line of command or
line of response at a time. The control connection is made between the control
processes. The control connection remains connected during the entire interactive
FTP session.
• Data Connection: The Data Connection uses very complex rules as data types may
vary. The data connection is made between data transfer processes. The data
connection opens when a command comes for transferring the files and closes when
the file is transferred.

FTP Clients

• FTP client is a program that implements a file transfer protocol which allows you to
transfer files between two hosts on the internet.
• It allows a user to connect to a remote host and upload or download the files.
• It has a set of commands that we can use to connect to a host, transfer the files
between you and your host and close the connection.
• The FTP program is also available as a built-in component in a Web browser. This
GUI based FTP client makes the file transfer very easy and also does not require to
remember the FTP commands.

Advantages of FTP:

• Speed: One of the biggest advantages of FTP is speed. The FTP is one of the fastest
way to transfer the files from one computer to another computer.
• Efficient: It is more efficient as we do not need to complete all the operations to get
the entire file.
• Security: To access the FTP server, we need to login with the username and
password. Therefore, we can say that FTP is more secure.
• Back & forth movement: FTP allows us to transfer the files back and forth. Suppose
you are a manager of the company, you send some information to all the employees,
and they all send information back on the same server.
Disadvantages of FTP:

• The standard requirement of the industry is that all the FTP transmissions should be
encrypted. However, not all the FTP providers are equal and not all the providers
offer encryption. So, we will have to look out for the FTP providers that provides
encryption.
• FTP serves two operations, i.e., to send and receive large files on a network.
However, the size limit of the file is 2GB that can be sent. It also doesn't allow you to
run simultaneous transfers to multiple receivers.
• Passwords and file contents are sent in clear text that allows unwanted eavesdropping.
So, it is quite possible that attackers can carry out the brute force attack by trying to
guess the FTP password.
• It is not compatible with every system.

Telnet

• The main task of the internet is to provide services to users. For example, users want
to run different application programs at the remote site and transfers a result to the
local site. This requires a client-server program such as FTP, SMTP. But this would
not allow us to create a specific program for each demand.
• The better solution is to provide a general client-server program that lets the user
access any application program on a remote computer. Therefore, a program that
allows a user to log on to a remote computer. A popular client-server program Telnet
is used to meet such demands. Telnet is an abbreviation for Terminal Network.
• Telnet provides a connection to the remote computer in such a way that a local
terminal appears to be at the remote side.

There are two types of login:

Local Login

When a user logs into a local computer, then it is known as local login.

When the workstation running terminal emulator, the keystrokes entered by the user are
accepted by the terminal driver. The terminal driver then passes these characters to the
operating system which in turn, invokes the desired application program.
However, the operating system has special meaning to special characters. For example, in
UNIX some combination of characters have special meanings such as control character with
"z" means suspend. Such situations do not create any problem as the terminal driver knows
the meaning of such characters. But, it can cause the problems in remote login.

Remote login

o When the user wants to access an application program on a remote computer,


then the user must perform remote login.

How remote login occurs

At the local site

The user sends the keystrokes to the terminal driver, the characters are then sent to the
TELNET client. The TELNET client which in turn, transforms the characters to a universal
character set known as network virtual terminal characters and delivers them to the local
TCP/IP stack

At the remote site

The commands in NVT forms are transmitted to the TCP/IP at the remote machine. Here, the
characters are delivered to the operating system and then pass to the TELNET server. The
TELNET server transforms the characters which can be understandable by a remote
computer. However, the characters cannot be directly passed to the operating system as a
remote operating system does not receive the characters from the TELNET server. Therefore
it requires some piece of software that can accept the characters from the TELNET server.
The operating system then passes these characters to the appropriate application program.
Network Virtual Terminal (NVT)

o The network virtual terminal is an interface that defines how data and
commands are sent across the network.
o In today's world, systems are heterogeneous. For example, the operating
system accepts a special combination of characters such as end-of-file token
running a DOS operating system ctrl+z while the token running a UNIX
operating system is ctrl+d.
o TELNET solves this issue by defining a universal interface known as network
virtual interface.
o The TELNET client translates the characters that come from the local terminal
into NVT form and then delivers them to the network. The Telnet server then
translates the data from NVT form into a form which can be understandable
by a remote computer.

Finger

Finger is a networking tool and one of the earliest computer networking programs that
enabled a user to view another user’s basic information when using the same computer
system or logged on in the same network. The program can determine user identity though an
email address and determine whether that user is currently logged in, as well as the status of
their log sessions.

It was originally created by Les Earnest in 1971 and later became a standard part of BSD
UNIX, and was commonly used by Windows users. This was later interfaced by David
Zimmerman with the Name program to become the Name/Finger Protocol in 1977.

Finger was duly named for the act of pointing, as it points to a person as well as to different
information regarding that user. When invoked, Finger displays information including the
user’s real name, office location, phone number, and even their last login time, although the
information displayed can be modified depending on the data maintained by the user in the
computer system.

To be able to Finger another web user, the program must be installed in the user’s computer
or access a Finger gateway and type the user’s email address. The server at the other end
must be able to handle Finger requests too.

Let us see the differences between HTML and HTML5 now.

HTML HTML5
It didn’t support audio and video without the use It supports audio and video controls with
of flash player support. the use of <audio> and <video> tags.
It uses SQL databases and application
It uses cookies to store temporary data.
cache to store offline data.
Allows JavaScript to run in background.
Does not allow JavaScript to run in browser. This is possible due to JS Web worker API
in HTML5.
Vector graphics is possible in HTML with the
Vector graphics is additionally an integral
help of various technologies such as VML,
a part of HTML5 like SVG and canvas.
Silver-light, Flash, etc.
It does not allow drag and drop effects. It allows drag and drop effects.
Not possible to draw shapes like circle, HTML5 allows to draw shapes like circle,
rectangle, triangle etc. rectangle, triangle etc.
It supported by all new browser like
It works with all old browsers.
Firefox, Mozilla, Chrome, Safari, etc.
Older version of HTML are less mobile-friendly. HTML5 language is more mobile-friendly.
Doctype declaration is quite simple and
Doctype declaration is too long and complicated.
easy.
New element for web structure like nav,
Elements like nav, header were not present.
header, footer etc.
Character encoding is long and complicated. Character encoding is simple and easy.
It is almost impossible to get true GeoLocation One can track the GeoLocation of a user
of user with the help of browser. easily by using JS GeoLocation API.
It can not handle inaccurate syntax. It is capable of handling inaccurate syntax.
Attributes like charset, async and ping are absent Attributes of charset, async and ping are a
in HTML. part of HTML 5.
Features of HTML5

HTML5 introduces a number of new elements and attributes that can help you in building
modern websites. Here is a set of some of the most prominent features introduced in HTML5.

• New Semantic Elements − These are like <header>, <footer>, and <section>.
• Forms 2.0 − Improvements to HTML web forms where new attributes have been
introduced for <input> tag.
• Persistent Local Storage − To achieve without resorting to third-party plugins.
• WebSocket − A next-generation bidirectional communication technology for web
applications.
• Server-Sent Events − HTML5 introduces events which flow from web server to the
web browsers and they are called Server-Sent Events (SSE).
• Canvas − This supports a two-dimensional drawing surface that you can program
with JavaScript.
• Audio & Video − You can embed audio or video on your webpages without resorting
to third-party plugins.
• Geolocation − Now visitors can choose to share their physical location with your web
application.
• Microdata − This lets you create your own vocabularies beyond HTML5 and extend
your web pages with custom semantics.
• Drag and drop − Drag and drop the items from one location to another location on
the same webpage.

General Purpose Attributes

There are some attributes, such as id, title, class, style, etc. that you can use on the majority of
HTML elements. The following section describes their usages.

The id Attribute

The id attribute is used to give a unique name or identifier to an element within a document.
This makes it easier to select the element using CSS or JavaScript.

Example

<input type="text" id="firstName">


<div id="container">Some content</div>
<p id="infoText">This is a paragraph.</p>

Note: The id of an element must be unique within a single document. No two elements in the
same document can be named with the same id, and each element can have only one id.

The class Attribute

Like id attribute, the class attribute is also used to identify elements. But unlike id,
the class attribute does not have to be unique in the document. This means you can apply the
same class to multiple elements in a document, as shown in the following example:

Example

<input type="text" class="highlight">


<div class="box highlight">Some content</div>
<p class="highlight">This is a paragraph.</p>

Tip: Since a class can be applied to multiple elements, therefore any style rules that are
written to that class will be applied to all the elements having that class.
The title Attribute

The title attribute to is used to provide advisory text about an element or its content. Try out
the following example to understand how this actually works.

Example

Try this code »

<abbr title="World Wide Web Consortium">W3C</abbr>


<a href="images/kites.jpg" title="Click to view a larger image">
<img src="images/kites-thumb.jpg" alt="kites">
</a>

Tip: The value of the title attribute (i.e. title text) is displayed as a tooltip by the web
browsers when the user place mouse cursor over the element.

The style Attribute

The style attribute allows you to specify CSS styling rules such as color, font, border, etc.
directly within the element. Let's check out an example to see how it works:

Example
<p style="color: blue;">This is a paragraph.</p>
<img src="images/sky.jpg" style="width: 300px;" alt="Cloudy Sky">
<div style="border: 1px solid red;">Some content</div>

What is HTML Form?

HTML Forms are required to collect different kinds of user inputs, such as contact details like
name, email address, phone numbers, or details like credit card information, etc.

Forms contain special elements called controls like inputbox, checkboxes, radio-buttons,
submit buttons, etc. Users generally complete a form by modifying its controls e.g. entering
text, selecting items, etc. and submitting this form to a web server for further processing.

The <form> tag is used to create an HTML form. Here's a simple example of a login form:

Example

Try this code »

<form>
<label>Username: <input type="text"></label>
<label>Password: <input type="password"></label>
<input type="submit" value="Submit">
</form>
What is Canvas?

The HTML5 canvas element can be used to draw graphics on the webpage via JavaScript.
The canvas was originally introduced by Apple for the Mac OS dashboard widgets and to
power graphics in the Safari web browser. Later it was adopted by the Firefox, Google
Chrome and Opera. Now the canvas is a part of the new HTML5 specification for next
generation web technologies.

By default the <canvas> element has 300px of width and 150px of height without any border
and content. However, custom width and height can be defined using the
CSS height and width property whereas the border can be applied using the
CSS border property.

Understanding Canvas Coordinates

The canvas is a two-dimensional rectangular area. The coordinates of the top-left corner of
the canvas are (0, 0) which is known as origin, and the coordinates of the bottom-right corner
are (canvas width, canvas height). Here's a simple demonstration of canvas default coordinate
system.
(0,0)

What is SVG?

What is SVG?

The Scalable Vector Graphics (SVG) is an XML-based image format that is used to define
two-dimensional vector based graphics for the web. Unlike raster image (e.g. .jpg, .gif, .png,
etc.), a vector image can be scaled up or down to any extent without losing the image quality.

An SVG image is drawn out using a series of statements that follow the XML schema — that
means SVG images can be created and edited with any text editor, such as Notepad. There
are several other advantages of using SVG over other image formats like JPEG, GIF, PNG,
etc.

· SVG images can be searched, indexed, scripted, and compressed.

· SVG images can be created and modified using JavaScript in real time.

· SVG images can be printed with high quality at any resolution.

· SVG content can be animated using the built-in animation elements.

· SVG images can contain hyperlinks to other documents.

Tip: The vector images are composed of a fixed set of shapes defined by math, while the
bitmap or raster images are composed of a fixed set of dots called pixels.

Embedding SVG into HTML Pages


You can embed SVG graphics directly into your document using the HTML5 <svg> element.

Let's take a look at the following example to understand how it basically works:

Example

Try this code »

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Embedding SVG in HTML</title>

</head>

<body>

<svg width="300" height="200">

<text x="10" y="20" style="font-size:14px;">

Your browser support SVG.

</text>

Sorry, your browser does not support SVG.

</svg>

</body>

Difference between SVG and Canvas

The HTML5 introduced the two new graphical elements <canvas> and <svg> for creating
rich graphics on the web, but they are fundamentally different.

The following table summarizes some of the basic differences between these two elements,
which will help you to understand how to use these elements effectively and appropriately.
SVG
1)Vector based (composed of shapes)
2)Multiple graphical elements, which become the part of the page's DOM tree
3)Modified through script and CSS
4)Good text rendering capabilities
5)Give better performance with smaller number of objects or larger surface, or both
6)Better scalability. Can be printed with high quality at any resolution. Pixelation does not occur

Canvas
1)Raster based (composed of pixel)
2)Single element similar to <img> in behavior. Canvas diagram can be saved to PNG or JPG format
3)Modified through script only
4)Poor text rendering capabilities
5)Give better performance with larger number of objects or smaller surface, or both
6)Poor scalability. Not suitable for printing on higher resolution. Pixelation may occur

What is Web Storage?

The HTML5's web storage feature lets you store some information locally on the user's
computer, similar to cookies, but it is faster and much better than cookies. However, web
storage is no more secure than cookies. Please check out the tutorial on PHP cookies to learn
more about cookies.

The information stored in the web storage isn't sent to the web server as opposed to the
cookies where data sent to the server with every request. Also, where cookies let you store a
small amount of data (nearly 4KB), the web storage allows you to store up to 5MB of data.

There are two types of web storage, which differ in scope and lifetime:

· Local storage — The local storage uses the localStorage object to store data for your
entire website on a permanent basis. That means the stored local data will be available on the
next day, the next week, or the next year unless you remove it.

· Session storage — The session storage uses the sessionStorage object to store data on
a temporary basis, for a single browser window or tab. The data disappears when session
ends i.e. when the user closes that browser window or tab.

What is a Web Worker?

If you try to do intensive task with JavaScript that is time-consuming and require hefty
calculations browser will freeze up the web page and prevent the user from doing anything
until the job is completed. It happens because JavaScript code always runs in the foreground.

HTML5 introduces a new technology called web worker that is specifically designed to do
background work independently of other user-interface scripts, without affecting the
performance of the page. Unlike normal JavaScript operations, web worker doesn't interrupt
the user and the web page remains responsive because they are running the tasks in the
background.

Tip: The HTML5's web worker feature is supported in all major modern web browsers like
Firefox, Chrome, Opera, Safari and Internet Explorer 10 and above.

Create a Web Worker File

The simplest use of web workers is for performing a time-consuming task. So here we are
going to create a simple JavaScript task that counts from zero to 100,000.

Let's create an external JavaScript file named "worker.js" and type the following code.

Example

Download

var i = 0;
function countNumbers() {
if(i < 100000) {
i = i + 1;
postMessage(i);
}

// Wait for sometime before running this script again


setTimeout("countNumbers()", 500);
}
countNumbers();

Note: Web workers have no access to the DOM. That means you can't access any DOM
elements in the JavaScript code that you intend to run using web workers.

What is JavaScript?

JavaScript was initially created to “make web pages alive”.

The programs in this language are called scripts. They can be written right in a web page’s
HTML and run automatically as the page loads.

Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.

In this aspect, JavaScript is very different from another language called Java.

Why is it called JavaScript?


When JavaScript was created, it initially had another name: “LiveScript”. But Java was very
popular at that time, so it was decided that positioning a new language as a “younger brother”
of Java would help.

But as it evolved, JavaScript became a fully independent language with its own specification
called ECMAScript, and now it has no relation to Java at all.

Today, JavaScript can execute not only in the browser, but also on the server, or actually on
any device that has a special program called the JavaScript engine.

The browser has an embedded engine sometimes called a “JavaScript virtual machine”.

Different engines have different “codenames”. For example:

• V8 – in Chrome and Opera.


• SpiderMonkey – in Firefox.
• …There are other codenames like “Trident” and “Chakra” for different versions of IE,
“ChakraCore” for Microsoft Edge, “Nitro” and “SquirrelFish” for Safari, etc.

The terms above are good to remember because they are used in developer articles on the
internet. We’ll use them too. For instance, if “a feature X is supported by V8”, then it
probably works in Chrome and Opera.

How do engines work?

Engines are complicated. But the basics are easy.

1. The engine (embedded if it’s a browser) reads (“parses”) the script.


2. Then it converts (“compiles”) the script to the machine language.
3. And then the machine code runs, pretty fast.

The engine applies optimizations at each step of the process. It even watches the compiled
script as it runs, analyzes the data that flows through it, and further optimizes the machine
code based on that knowledge.

What can in-browser JavaScript do?

Modern JavaScript is a “safe” programming language. It does not provide low-level access to
memory or CPU, because it was initially created for browsers which do not require it.

JavaScript’s capabilities greatly depend on the environment it’s running in. For
instance, Node.js supports functions that allow JavaScript to read/write arbitrary files,
perform network requests, etc.

In-browser JavaScript can do everything related to webpage manipulation, interaction with


the user, and the webserver.

For instance, in-browser JavaScript is able to:

• Add new HTML to the page, change the existing content, modify styles.
• React to user actions, run on mouse clicks, pointer movements, key presses.
• Send requests over the network to remote servers, download and upload files (so-
called AJAX and COMET technologies).
• Get and set cookies, ask questions to the visitor, show messages.
• Remember the data on the client-side (“local storage”).

What CAN’T in-browser JavaScript do?

JavaScript’s abilities in the browser are limited for the sake of the user’s safety. The aim is to
prevent an evil webpage from accessing private information or harming the user’s data.

Examples of such restrictions include:

• JavaScript on a webpage may not read/write arbitrary files on the hard disk, copy
them or execute programs. It has no direct access to OS functions.

Modern browsers allow it to work with files, but the access is limited and only
provided if the user does certain actions, like “dropping” a file into a browser window
or selecting it via an <input> tag.

There are ways to interact with camera/microphone and other devices, but they
require a user’s explicit permission. So a JavaScript-enabled page may not sneakily
enable a web-camera, observe the surroundings and send the information to the NSA.

• Different tabs/windows generally do not know about each other. Sometimes they do,
for example when one window uses JavaScript to open the other one. But even in this
case, JavaScript from one page may not access the other if they come from different
sites (from a different domain, protocol or port).

This is called the “Same Origin Policy”. To work around that, both pages must agree
for data exchange and contain a special JavaScript code that handles it. We’ll cover
that in the tutorial.

This limitation is, again, for the user’s safety. A page from http://anysite.com which a
user has opened must not be able to access another browser tab with the
URL http://gmail.com and steal information from there.

• JavaScript can easily communicate over the net to the server where the current page
came from. But its ability to receive data from other sites/domains is crippled. Though
possible, it requires explicit agreement (expressed in HTTP headers) from the remote
side. Once again, that’s a safety limitation.

Such limits do not exist if JavaScript is used outside of the browser, for example on a server.
Modern browsers also allow plugin/extensions which may ask for extended permissions.
What makes JavaScript unique?

There are at least three great things about JavaScript:

• Full integration with HTML/CSS.


• Simple things are done simply.
• Support by all major browsers and enabled by default.

JavaScript is the only browser technology that combines these three things.

That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating
browser interfaces.

That said, JavaScript also allows to create servers, mobile applications, etc.

JavaScript Comment

1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments

The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, warnings or suggestions so that end user can easily interpret the
code.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.

Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.

1. To make code easy to understand It can be used to elaborate the code so that end
user can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being executed.
Sometimes, we add the code to perform some action. But after sometime, there may
be need to disable the code. In such case, it is better to use comments.

Types of JavaScript Comments

There are two types of comments in JavaScript.

1. Single-line Comment
2. Multi-line Comment

JavaScript Single line Comment

It is represented by double forward slashes (//). It can be used before and after the statement.

Let’s see the example of single-line comment i.e. added before the statement.
<script>
// It is single line comment
document.write("hello javascript");
</script>

<script> Let’s see the example of single-line comment i.e. added after the statement.

var a=10;
var b=20;
var c=a+b;//It adds values of a and b variable
document.write(c);//prints sum of 10 and 20
</script>
JavaScript Multi line Comment

It can be used to add single as well as multi line comments. So, it is more convenient.

It is represented by forward slash with asterisk then asterisk with forward slash. For example:

/* your code here */

It can be used before, after and middle of the statement.

<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9


JavaScript Comparison Operators

The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

JavaScript Bitwise Operators

The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2


JavaScript Logical Operators

The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true

JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators

The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-else.

, Comma Operator allows multiple expressions to be evaluated as single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.


void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

If Statement

JavaScript If-else

The JavaScript if-else statement is used to execute the code whether condition is true or
false. There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement

It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.

if(expression){
//content to be evaluated
}
Flowchart of JavaScript If statement
Let’s see the simple example of if statement in javascript.

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
Test it Now
Output of the above example
value of a is greater than 10

JavaScript If...else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Flowchart of JavaScript If...else statement
Let’s see the example of if-else statement in JavaScript to find out the even or odd number.

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
Test it Now
Output of the above example
a is even number
JavaScript If...else if statement

It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.

if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

Let’s see the simple example of if else if statement in javascript.

<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
JavaScript Object

A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.

Creating Objects in JavaScript

There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:

1. object={property1:value1,property2:value2.....propertyN:valueN}

As you can see, property and value is separated by : (colon).

Let’s see the simple example of creating object in JavaScript.

<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Test it Now
Output of the above example
102 Shyam Kumar 40000

2) By creating instance of Object

The syntax of creating object directly is given below:

1. var objectname=new Object();


Here, new keyword is used to create object.

Let’s see the example of creating object directly.

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Test it Now
Output of the above example
101 Ravi 50000

3) By using an Object constructor

Here, you need to create function with arguments. Each argument value can be assigned in
the current object by using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
Test it Now
Output of the above example
103 Vimal Jaiswal 30000

Defining method in JavaScript Object

We can define method in JavaScript object. But before defining method, we need to add
property in the function with same name as method.

The example of defining method in object is given below.


<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;

this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
Test it Now
Output of the above example
103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000

JavaScript Object Methods

The various methods of Object are as follows:

S.No Methods Description

This method is used to copy enumerable and own


1 Object.assign()
properties from a source object to a target object

This method is used to create a new object with


2 Object.create()
the specified prototype object and properties.

This method is used to describe some behavioral


3 Object.defineProperty()
attributes of the property.

This method is used to create or configure


4 Object.defineProperties()
multiple object properties.

This method returns an array with arrays of the


5 Object.entries()
key, value pairs.

This method prevents existing properties from


6 Object.freeze()
being removed.

This method returns a property descriptor for the


7 Object.getOwnPropertyDescriptor()
specified property of the specified object.
This method returns all own property descriptors
8 Object.getOwnPropertyDescriptors()
of a given object.

This method returns an array of all properties


9 Object.getOwnPropertyNames()
(enumerable or not) found.

This method returns an array of all own symbol


10 Object.getOwnPropertySymbols()
key properties.

This method returns the prototype of the


11 Object.getPrototypeOf()
specified object.

This method determines whether two values are


12 Object.is()
the same value.

13 Object.isExtensible() This method determines if an object is extensible

14 Object.isFrozen() This method determines if an object was frozen.

15 Object.isSealed() This method determines if an object is sealed.

This method returns an array of a given object's


16 Object.keys()
own property names.

This method is used to prevent any extensions of


17 Object.preventExtensions()
an object.

This method prevents new properties from being


18 Object.seal() added and marks all existing properties as non-
configurable.

This method sets the prototype of a specified


19 Object.setPrototypeOf()
object to another object.

20 Object.values() This method returns an array of values.

What is jQuery?

jQuery is a small, light-weight and fast JavaScript library. It is cross-platform and supports
different types of browsers. It is also referred as ?write less do more? because it takes a lot of
common tasks that requires many lines of JavaScript code to accomplish, and binds them into
methods that can be called with a single line of code whenever needed. It is also very useful
to simplify a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.

• jQuery is a small and lightweight JavaScript library.


• jQuery is cross-platform.
• jQuery means "write less do more".
• jQuery simplifies AJAX call and DOM manipulation.
An Example jQuery Program

<!DOCTYPE html>
<html>
<head>
<title>First jQuery Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.m
in.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("p").css("background-color", "pink");
});
</script>
</head>
<body>
<p>This is first paragraph.</p>
<p>This is second paragraph.</p>
<p>This is third paragraph.</p>
</body>
</html>
What are Selectors?

jQuery Selectors are used to select and manipulate HTML elements. They are very important
part of jQuery library.

With jQuery selectors, you can find or select HTML elements based on their id, classes,
attributes, types and much more from a DOM.

In simple words, you can say that selectors are used to select one or more HTML elements
using jQuery and once the element is selected then you can perform various operation on that.

All jQuery selectors start with a dollor sign and parenthesis e.g. $(). It is known as the factory
function.

The $() factory function

Every jQuery selector start with thiis sign $(). This sign is known as the factory function. It
uses the three basic building blocks while selecting an element in a given document.

S.No. Selector Description

Tag It represents a tag name available in the DOM.


1)
Name: For example: $('p') selects all paragraphs'p'in the document.
It represents a tag available with a specific ID in the DOM.
2) Tag ID: For example: $('#real-id') selects a specific element in the document that
has an ID of real-id.

It represents a tag available with a specific class in the DOM.


Tag
3) For example: $('real-class') selects all elements in the document that have a
Class:
class of real-class.

What is DOM?

DOM stands for Document Object Model and is a mechanism for representing and
interacting with your HTML, XHTML or XML documents. It allows you to navigate and
manipulate your documents through a programming language, which in the browser will
almost always be JavaScript. DOM navigation and manipulation using standard JavaScript
can be pretty cumbersome, but fortunately for us, jQuery comes with a bunch of DOM
related methods, making it all much easier.

jQuery provides various methods to add, edit or delete DOM element(s) in the HTML page.

The following table lists some important methods to add/remove new DOM elements.

Method Description

append() Inserts content to the end of element(s) which is specified by a selector.

Inserts content (new or existing DOM elements) before an element(s) which is


before()
specified by a selector.

Inserts content (new or existing DOM elements) after an element(s) which is


after()
specified by a selector.

prepend() Insert content at the beginning of an element(s) specified by a selector.

remove() Removes element(s) from DOM which is specified by selector.

replaceAll() Replace target element(s) with specified element.

wrap() Wrap an HTML structure around each element which is specified by selector.

jQuery Events

jQuery events are the actions that can be detected by your web application. They are used to
create dynamic web pages. An event shows the exact moment when something happens.

These are some examples of events.

• A mouse click
• An HTML form submission
• A web page loading
• A keystroke on the keyboard
• Scrolling of the web page etc.

These events can be categorized on the basis their types:

Mouse Events

• click
• dblclick
• mouseenter
• mouseleave

Keyboard Events

• keyup
• keydown
• keypress

Form Events

• submit
• change
• blur
• focus

Document/Window Events

• load
• unload
• scroll
• resize

Note: A term "fires" is generally used with events. For example: The click event fires in the
moment you press a key.

Syntax for event methods

Most of the DOM events have an equivalent jQuery method. To assign a click events to all
paragraph on a page, do this:

$("p").click ();

The next step defines what should happen when the event fires. You must pass a function to
the event.

$("p").click(function(){
// action goes here!!
});
click() Event

jQuery click()

When you click on an element, the click event occurs and once the click event occurs it
execute the click () method or attaches a function to run.

It is generally used together with other events of jQuery.

Syntax:

$(selector).click()

It is used to trigger the click event for the selected elements.

$(selector).click(function)

It is used to attach the function to the click event.

Let's take an example to demonstrate jQuery click() event.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
alert("This paragraph was clicked.");
});
});
</script>
</head>
<body>
<p>Click on the statement.</p>
</body>
</html>
Test it Now

Output:

Click on the statement.

Let's take an example to demonstrate the jquery click() event. In this example, when you
click on the heading element, it will hide the current heading.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("h1,h2,h3").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<h1>This heading will disappear if you click on this.</h1>
<h2>I will also disappear.</h2>
<h3>Me too.</h3>
</body>
</html>
Test it Now

Output:

jQuery focus()

The jQuery focus event occurs when an element gains focus. It is generated by a mouse click
or by navigating to it.

This event is implicitly used to limited sets of elements such as form elements like <input>,
<select> etc. and links <a href>. The focused elements are usually highlighted in some way
by the browsers.

The focus method is often used together with blur () method.

Syntax:

1. $(selector).focus()

It triggers the focus event for selected elements.

1. $(selector).focus(function)

It adds a function to the focus event.

Parameters of jQuery focus() event

Parameter Description

It is an optional parameter. It is used to specify the function to run when the


Function
element gets the focus.
Example of jQuery focus() event

Let's take an example to demonstrate jQuery focus() event.

1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>focus demo</title>
6. <style>
7. span {
8. display: none;
9. }
10. </style>
11. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
12. </head>
13. <body>
14. <p><input type="text"> <span>Focus starts.. Write your name.</span></p>
15. <p><input type="password"> <span>Focus starts.. Write your password.</span></p>

16. <script>
17. $( "input" ).focus(function() {
18. $( this ).next( "span" ).css( "display", "inline" ).fadeOut( 2000 );
19. });
20. </script>
21. </body>
22. </html>

submit()

jQuery submit event is sent to the element when the user attempts to submit a form.

This event is only attached to the <form> element. Forms can be submitted either by clicking
on the submit button or by pressing the enter button on the keyboard when that certain form
elements have focus. When the submit event occurs, the submit() method attaches a function
with it to run.

Syntax:

1. $(selector).submit()

It triggers the submit event for selected elements.

1. $(selector).submit(function)

It adds a function to the submit event.


Parameters of jQuery submit() event

Parameter Description

It is an optional parameter. It is used to specify the function to run when the


Function
submit event is executed.

Example of jQuery submit() event

Let's take an example to demonstrate jQuery submit() event.

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>submit demo</title>
6. <style>
7. p {
8. margin: 0;
9. color: blue;
10. }
11. div,p {
12. margin-left: 10px;
13. }
14. span {
15. color: red;
16. }
17. </style>
18. <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
19. </head>
20. <body>
21. <p>Type 'javatpoint' to submit this form finally.</p>
22. <form action="javascript:alert( 'success!' );">
23. <div>
24. <input type="text">
25. <input type="submit">
26. </div>
27. </form>
28. <span></span>
29. <script>
30. $( "form" ).submit(function( event ) {
31. if ( $( "input:first" ).val() === "javatpoint" ) {
32. $( "span" ).text( "Submitted Successfully." ).show();
33. return;
34. }
35. $( "span" ).text( "Not valid!" ).show().fadeOut( 2000 );
36. event.preventDefault();
37. });
38. </script>
39. </body>
40. </html>

jQuery UI Example

What is jQuery UI

• Good for highly interactive web applications


• Open source and free to use
• Powerful theme mechanism
• Stable and maintenance friendly
• Extensive browser support

jQuery UI Example

In this tutorial, you will get a lot of jQuery UI examples to understand the topic well. Let's
see a simple jQuery UI example.

File: jqueryuidraggable1.html
<!DOCTYPE html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-
ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<style>
#draggable { width: 100px; height: 100px; padding: 0.5em; background:#7fffd4;}
</style>
<script>
$(function() {
$( "#draggable" ).draggable();
});
</script>
</head>
<body>
<div id="draggable" class="ui-widget-content">
<p>I am draggable!</p>
</div>
</body>
</html>

jQuery UI Introduction

jQueryUI stands for jQuery User Interface. It is a collection of animated visual effects, GUI
widgets, and themes implemented with jQuery, CSS, HTML and JavaScript. These new plug-
ins add a lot of new functionalities in the jQuery core library.
It is a very popular and powerful mobile first front-end framework used for faster and easier
web development. According to a survey it is used on over 176000 websites, making it the
second most popular JavaScript library on the Web.

jQuery UI History

jQueryUI is a free and open source software first published and released in September 2007.
It is distributed by jQuery foundation under the MIT license.

jQuery UI Features

• jQueryUI facilitates you to make highly interactive web applications.


• It is open source and free to use.
• It provides a powerful theme mechanism.
• It is very stable and maintenance friendly.
• It provides an extensive browser support
• Good documentation

jQuery UI Categorization

We can categorize the jQueryUI into four groups.

1. Interactions
2. Widgets
3. Effects
4. Utilities

1) Interactions: Interactions are the set of plug-ins which facilitates users to interact with
DOM elements. These are the mostly used interactions:

• Draggable
• Droppable
• Resizable
• Selectable
• Sortable

2) Widgets: Widgets are the jQuery plug-ins which makes you able to create user interface
elements like date picker, progress bar etc. These are the mostly used widgets:

• Accordion
• Autocomplete
• Dialog
• Button
• Date Picker
• Menu
• Progress Bar
• Tabs
• Tooltip
• Slider
• Spinner
3) Effects: The internal jQuery effects contain a full suite of custom animation and transition
for DOM elements.

• Hide
• Show
• Add Class
• Remove Class
• Switch Class
• Toggle Class
• Color Animation
• Effect
• Toggle

4) Utilities: Utilities are the modular tools, used by jQuery library internally.

• Position: It is used to set the position of the element according to the other element's
alignment (position).

Accordion

jQuery UI Accordian is an expandable and collapsible content holder that is broken into
sections and probably looks like tabs.

Syntax:

You can use the accordion () method in two forms:

1. $(selector, context).accordion (options) Method

1. $(selector, context).accordion ("action", params) Method

First Method

$(selector, context).accordion (options) Method:

The accordion (options) method specifies that an HTML element and its contents should be
treated and managed as accordion menus. The options parameter is an object that specifies
the appearance and behavior of the menu involved.

Syntax:

1. $(selector, context).accordion (options);

You can use one or more options at a time using Javascript object. In the case of more than
one options to be provided, you have to separate them using a comma as follows:

1. $(selector, context).accordion({option1: value1, option2: value2..... });

Following is a list of different options that can be used with this method:
Option Description

It specifies the index of the menu that is open when the page is first accessed. By
default its value is 0. It is of two types:
boolean: if set to false will collapse all panels. This requires the collapsible
active
option to be true.
integer: The zero-based index of the panel that is active (open). a negative value
selects panels going backward from the last panel.

The animate option is used to set how to animate changing panels. By default its
value is {}.

this is of four types:


animate
boolean: a value of false will disable animations.
number: this is a duration in milliseconds
string: name of easing to use with default duration.
object: animation settings with easing and duration properties.

This option allows users to click on the open panel's header have no effect when
collapsible it is set to false. It facilitates users to close a menu by clicking on it when it is set
to true. By default its value is false.

If you set this option's value true then it disables the accordion. By default its
disabled
value is false.

This option specifies the event used to select an accordion header. By default its
event
value is click.

This option specifies a selector or element to override the default pattern for
header identifying the header elements. By default its value is > li > :first-child,>
:not(li):even.

The heightStyle option is used to control the height of accordion and panels. By
default its value is auto.
Its possible values are:
heightStyle
auto: all panels will be set to the height of the tallest panel.
fill: expand to the available height based on the accordion's parent height.
content: each panel will be only as tall as its content.

This option is an object that defines the icons to use to the left of the header text
icons for opened and closed panels. The icon to use for closed panels is specified as a
property named header, whereas the icon to use for open panels is specified as a
property named headerselected. By default its value is { "header": "ui-icon-
triangle-1-e", "activeheader": "ui-icon-triangle-1-s" }.

jQuery UI Accordion() Example 1

Let's take an example of jQuery UI Accordion() method:

1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8"
5. <title>jQuery UI Accordion - Default functionality</title>
6. <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-
ui.css">
7. <script src="//code.jquery.com/jquery-1.10.2.js"></script>
8. <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
9. <link rel="stylesheet" href="/resources/demos/style.css">
10. <script>
11. $(function() {
12. $( "#accordion" ).accordion();
13. });
14. </script>
15. </head>
16. <body>
17. <div id="accordion">
18. <h3>What is Java?</h3>
19. <div>
20. <p>
21. Java is a simple, object oriented, concurrent and general purpose programming lang
uage.
22. Some other important features of java are robust, secure, portable, interactive and hi
gh performance.
23. Java was developed by Sun Microsystems in 1995 since then it has become very pop
ular due to its feature
24. like platform independent and robust in the case of memory management.
25. </p>
26. </div>
27. <h3>Why is it called platform?</h3>
28. <div>
29. <p>
30. Because java has its own run time environment (JRE) and API so it is called platfor
m.
31. </p>
32. </div>
33. <h3>Where is it used?</h3>
34. <div>
35. <p>
36. According to Sun Microsystems, nearly 3 billion devices run java. Some of these d
evices
37. are mobile phones, games, robotics, application in banking sector etc.
38. </p>
39. </div>
40. <h3>Why JavaTpoint</h3>
41. <div>
42. <ul>
43. <li>Life Time Validity</li>
44. <li>Training by Java Professionals</li>
45. <li>Get an opportunity to work on real time projects</li>
46. <li>Interaction with Industry Experts</li>
47. <li>Small Batches to focus on each student</li>
48. </ul>
49. </div>
50. </div>
51. </body>
52. </html>

Test it Now

Second Method

The accordion ("action", params) method is used to perform an action on accordion elements,
such as selecting/de-selecting the accordion menu. The action is specified as a string in the
first argument (e.g., "disable" disables all menus).

Syntax:

1. $(selector, context).accordion ("action", params);

Following is a list of actions that can be passed.

Action Description

This action destroys the accordion functionality of an element


destroy
completely. The elements return to their pre-init state.

This action disable all menus. No click will be taken into account.
disable
This method does not accept any arguments.

This action reactivate all menus. The clicks are again considered. This
enable
method does not accept any arguments.

This action gets the value of currently associated accordion element


option(optionName)
with the specified optionname. This takes a string value as argument.

This action gets an object containing key/value pairs representing the


option
current accordion options hash.
option(optionName, This action sets the value of the accordion option associated with the
value) specified optionName.

This action sets one or more options for the accordion. Here options is
option(options)
a map of option-value pairs to set.

This action processes any headers and panels that were added or
removed directly in the dom. it then re-computes the height of the
refresh
accordion panels. Results depend on the content and the heightStyle
option. This method does not accept any arguments.

This action returns the accordion widget element; the one annotated
widget
with the UI-accordion class name.

jQuery UI Accordion() method example 2

Let's take an example to demonstrate the use of option (optionName, value) method:

1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>jQuery UI Accordion Example </title>
6. <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-
ui.css" rel="stylesheet">
7. <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
8. <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
9. <script>
10. $(function() {
11. $( "#accordion-5" ).accordion({
12. disabled: false
13. });
14. $("input").each(function () {
15. $(this).change(function () {
16. if ($(this).attr("id") == "disableaccordion") {
17. $("#accordion-5").accordion("option", "disabled", true);
18. } else {
19. $("#accordion-5").accordion("option", "disabled", false);
20. }
21. });
22. });
23. });
24. </script>
25. <style>
26. #accordion-5{font-size: 14px;}
27. </style>
28. </head>
29. <body>
30. <div id="accordion-5">
31. <h3>What is Java?</h3>
32. <div>
33. <p>
34. Java is a simple, object oriented, concurrent and general purpose programmi
ng language.
35. Some other important features of java are robust, secure, portable, interactiv
e and high performance.
36. Java was developed by Sun Microsystems in 1995 since then it has become
very popular due to its feature
37. like platform independent and robust in the case of memory management.
38. </p>
39. </div>
40. <h3>Why is it called Platform?</h3>
41. <div>
42. <p>
43. Because java has its own run time environment (JRE) and API so it is called
platform.
44. </p>
45. </div>
46. <h3>Where is it used?</h3>
47. <div>
48. <p>
49. According to Sun Microsystems, nearly 3 billion devices run java. Some of th
ese devices
50. are mobile phones, games, robotics, application in banking sector etc.
51. </p>
52.
53. </div>
54. <h3>Why JavaTpoint?</h3>
55. <div>
56. <ul>
57. <li>Life Time Validity</li>
58. <li>Training by Java Professionals</li>
59. <li>Get an opportunity to work on real time projects</li>
60. <li>Interaction with Industry Experts</li>
61. <li>Small Batches to focus on each student</li>
62. </ul>
63. </div>
64.
65. </div>
66. <div style="margin-top:30px">
67. <input type="radio" name="disable" id="disableaccordion"
68. value="disable">Disable accordion
69. <input type="radio" name="disable" id="enableaccordion" checked
70. value="enable">Enable accordion
71. </div>
72. </body>
73. </html>
Accordion

jQuery UI Accordian is an expandable and collapsible content holder that is broken into
sections and probably looks like tabs.

Syntax:

You can use the accordion () method in two forms:

1. $(selector, context).accordion (options) Method

1. $(selector, context).accordion ("action", params) Method

First Method

$(selector, context).accordion (options) Method:

The accordion (options) method specifies that an HTML element and its contents should be
treated and managed as accordion menus. The options parameter is an object that specifies
the appearance and behavior of the menu involved.

Syntax:

1. $(selector, context).accordion (options);

You can use one or more options at a time using Javascript object. In the case of more than
one options to be provided, you have to separate them using a comma as follows:

1. $(selector, context).accordion({option1: value1, option2: value2..... });

Following is a list of different options that can be used with this method:

Option Description

It specifies the index of the menu that is open when the page is first accessed. By
default its value is 0. It is of two types:
boolean: if set to false will collapse all panels. This requires the collapsible
active
option to be true.
integer: The zero-based index of the panel that is active (open). a negative value
selects panels going backward from the last panel.

The animate option is used to set how to animate changing panels. By default its
value is {}.
animate

this is of four types:


boolean: a value of false will disable animations.
number: this is a duration in milliseconds
string: name of easing to use with default duration.
object: animation settings with easing and duration properties.

This option allows users to click on the open panel's header have no effect when
collapsible it is set to false. It facilitates users to close a menu by clicking on it when it is set
to true. By default its value is false.

If you set this option's value true then it disables the accordion. By default its
disabled
value is false.

This option specifies the event used to select an accordion header. By default its
event
value is click.

This option specifies a selector or element to override the default pattern for
header identifying the header elements. By default its value is > li > :first-child,>
:not(li):even.

The heightStyle option is used to control the height of accordion and panels. By
default its value is auto.
Its possible values are:
heightStyle
auto: all panels will be set to the height of the tallest panel.
fill: expand to the available height based on the accordion's parent height.
content: each panel will be only as tall as its content.

This option is an object that defines the icons to use to the left of the header text
for opened and closed panels. The icon to use for closed panels is specified as a
icons property named header, whereas the icon to use for open panels is specified as a
property named headerselected. By default its value is { "header": "ui-icon-
triangle-1-e", "activeheader": "ui-icon-triangle-1-s" }.

jQuery UI Accordion() Example 1

Let's take an example of jQuery UI Accordion() method:

1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8"
5. <title>jQuery UI Accordion - Default functionality</title>
6. <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-
ui.css">
7. <script src="//code.jquery.com/jquery-1.10.2.js"></script>
8. <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
9. <link rel="stylesheet" href="/resources/demos/style.css">
10. <script>
11. $(function() {
12. $( "#accordion" ).accordion();
13. });
14. </script>
15. </head>
16. <body>
17. <div id="accordion">
18. <h3>What is Java?</h3>
19. <div>
20. <p>
21. Java is a simple, object oriented, concurrent and general purpose programming lang
uage.
22. Some other important features of java are robust, secure, portable, interactive and hi
gh performance.
23. Java was developed by Sun Microsystems in 1995 since then it has become very pop
ular due to its feature
24. like platform independent and robust in the case of memory management.
25. </p>
26. </div>
27. <h3>Why is it called platform?</h3>
28. <div>
29. <p>
30. Because java has its own run time environment (JRE) and API so it is called platfor
m.
31. </p>
32. </div>
33. <h3>Where is it used?</h3>
34. <div>
35. <p>
36. According to Sun Microsystems, nearly 3 billion devices run java. Some of these d
evices
37. are mobile phones, games, robotics, application in banking sector etc.
38. </p>
39. </div>
40. <h3>Why JavaTpoint</h3>
41. <div>
42. <ul>
43. <li>Life Time Validity</li>
44. <li>Training by Java Professionals</li>
45. <li>Get an opportunity to work on real time projects</li>
46. <li>Interaction with Industry Experts</li>
47. <li>Small Batches to focus on each student</li>
48. </ul>
49. </div>
50. </div>
51. </body>
52. </html>
Test it Now

Second Method

The accordion ("action", params) method is used to perform an action on accordion elements,
such as selecting/de-selecting the accordion menu. The action is specified as a string in the
first argument (e.g., "disable" disables all menus).

Syntax:

1. $(selector, context).accordion ("action", params);

Following is a list of actions that can be passed.

Action Description

This action destroys the accordion functionality of an element


destroy
completely. The elements return to their pre-init state.

This action disable all menus. No click will be taken into account.
disable
This method does not accept any arguments.

This action reactivate all menus. The clicks are again considered. This
enable
method does not accept any arguments.

This action gets the value of currently associated accordion element


option(optionName)
with the specified optionname. This takes a string value as argument.

This action gets an object containing key/value pairs representing the


option
current accordion options hash.

option(optionName, This action sets the value of the accordion option associated with the
value) specified optionName.

This action sets one or more options for the accordion. Here options is
option(options)
a map of option-value pairs to set.

This action processes any headers and panels that were added or
removed directly in the dom. it then re-computes the height of the
refresh
accordion panels. Results depend on the content and the heightStyle
option. This method does not accept any arguments.

This action returns the accordion widget element; the one annotated
widget
with the UI-accordion class name.

jQuery UI Accordion() method example 2

Let's take an example to demonstrate the use of option (optionName, value) method:
1. <!doctype html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>jQuery UI Accordion Example </title>
6. <link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-
ui.css" rel="stylesheet">
7. <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
8. <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
9. <script>
10. $(function() {
11. $( "#accordion-5" ).accordion({
12. disabled: false
13. });
14. $("input").each(function () {
15. $(this).change(function () {
16. if ($(this).attr("id") == "disableaccordion") {
17. $("#accordion-5").accordion("option", "disabled", true);
18. } else {
19. $("#accordion-5").accordion("option", "disabled", false);
20. }
21. });
22. });
23. });
24. </script>
25. <style>
26. #accordion-5{font-size: 14px;}
27. </style>
28. </head>
29. <body>
30. <div id="accordion-5">
31. <h3>What is Java?</h3>
32. <div>
33. <p>
34. Java is a simple, object oriented, concurrent and general purpose programmi
ng language.
35. Some other important features of java are robust, secure, portable, interactiv
e and high performance.
36. Java was developed by Sun Microsystems in 1995 since then it has become
very popular due to its feature
37. like platform independent and robust in the case of memory management.
38. </p>
39. </div>
40. <h3>Why is it called Platform?</h3>
41. <div>
42. <p>
43. Because java has its own run time environment (JRE) and API so it is called
platform.
44. </p>
45. </div>
46. <h3>Where is it used?</h3>
47. <div>
48. <p>
49. According to Sun Microsystems, nearly 3 billion devices run java. Some of th
ese devices
50. are mobile phones, games, robotics, application in banking sector etc.
51. </p>
52.
53. </div>
54. <h3>Why JavaTpoint?</h3>
55. <div>
56. <ul>
57. <li>Life Time Validity</li>
58. <li>Training by Java Professionals</li>
59. <li>Get an opportunity to work on real time projects</li>
60. <li>Interaction with Industry Experts</li>
61. <li>Small Batches to focus on each student</li>
62. </ul>
63. </div>
64.
65. </div>
66. <div style="margin-top:30px">
67. <input type="radio" name="disable" id="disableaccordion"
68. value="disable">Disable accordion
69. <input type="radio" name="disable" id="enableaccordion" checked
70. value="enable">Enable accordion
71. </div>
72. </body>
73. </html>

jQuery Animation

jQuery includes methods which give special effects to the elements on hiding, showing,
changing style properties, and fade-in or fade-out operation. These special effect methods can
be useful in building an interactive user interface.

The following table lists jQuery methods for adding special effects to the DOM elements.

jQuery Methods for Special


Description
Effects

animate() Perform custom animation using element's style properties.

Show or manipulate the queue of functions to be executed on


queue()
the specified element.

Stop currently running animations on the specified


stop()
element(s).
jQuery Methods for Special
Description
Effects

fadeIn() Display specified element(s) by fading them to opaque.

fadeOut() Hides specified element(s) by fading them to transparent.

fadeTo() Adjust the opacity of the specified element(s)

Display or hide the specified element(s) by animating their


fadeToggle()
opacity.

hide() Hide specified element(s).

show() Display specified element(s).

toggle() Display hidden element(s) or hide visible element(s).

slideUp() Hide specified element(s) with sliding up motion.

slideDown() Display specified element(s) with sliding down motion.

slideToggle() Display or hide specified element(s) with sliding motion.

Let's look at some important methods for special effects.

jQuery animate() Method

The jQuery animate() method performs custom animation using element's style properties.
The animate() method changes existing style properties to the specified properties with
motion.

Specify a selector to get the reference of an element to which you want to add animation
effect and then call animate() method with JSON object for style properties, speed of
animation and other options.

Syntax:
$('selector expression').animate({ stylePropertyName : 'value'},
duration,
easing,
callback);

$('selector expression').animate({ propertyName : 'value'},{ options });

Apply Animation

In the following example, we are changing height and width of the element with animation.

Example: jQuery animate() Method


$('#myDiv').animate({
height: '200px',
width: '200px'
});

<div id="myDiv" class="redDiv">


</div>
Try it

Set Animation Duration

You can apply animation duration in miliseconds as a second parameter of animate() method.

Example: Set Duration


$('#myDiv').animate({
height: '200px',
width: '200px'
},
5000);

<div id="myDiv" class="redDiv">


</div>
Try it

Apply Easing Method

Specify a string parameter indicating which easing function to use for the transition. The
jQuery library provides two easing function: linear and swing.

Example: Apply Easing Method


$('#myDiv').animate({
height: '200px',
width: '200px'
},
5000, 'swing');

<div id="myDiv" class="redDiv">


</div>
Try it

Callback Function on Animation Complete

Specify a callback function to execute when animation is complete.

Example: Specify Callback Function


$('#myDiv').animate({
height: '200px',
width: '200px'
},
5000,
function () {
$('#msgDiv').append('Animation completed');
});
});

<div id="myDiv" class="redDiv">


</div>

<div id="msgDiv"></div>
Try it

Specify Animation Options

You can specify various options as JSON object. The options include duration, easing, queue,
step, progress, complete, start, done and always. Visit api.jquery.com for more information.

Example: Specify Options


$('#myDiv').animate({
height: '200px',
width: '200px'
},
{ // options parameter
duration: 5000,
complete: function () {
$(this).animate({
height: '100px',
width: '100px'
}, 5000,
function () {
$('#msgDiv').text('Animation completed..');
});
},
start: function () {
$('#msgDiv').append('starting animation..');
}
});

<div id="msgDiv"></div>

<div id="myDiv" class="redDiv">


</div>
Try it

jQuery queue() Method


The jQuery queue() method shows or manipulates the queue of special effect functions to be
executed on the specified element.

Syntax:
$('selector expression').queue();
Example: jQuery queue() Method
$('#myDiv').toggle(500);
$('#myDiv').fadeOut(500);
$('#myDiv').fadeIn(500);
$('#myDiv').slideDown(500);
$('#msgDiv').append('Animation functions: ' + $('#myDiv').queue().length);

<div id="msgDiv"></div>

<div id="myDiv" class="redDiv">


</div>
Try it

jQuery fadeIn() Method

The jQuery fadeIn() method displays specified element(s) by fading them to opaque.

Syntax:
$('selector expression').fadeIn(speed, easing, callback);
Example: jQuery fadeIn() Method
$('#myDiv').fadeIn(5000, function () {
$('#msgDiv').append('fadeIn() completed.')
});

<div id="myDiv" class="redDiv">


</div>

<div id="msgDiv"></div>
Try it

jQuery fadeOut() Method

The jQuery fadeOut() method hides specified element(s) by fading them to transparent.

Syntax:
$('selector expression').fadeOut(speed, easing, callback);
Example: jQuery fadeOut() Method
$('#div1').fadeOut(5000, function () {
$('#msgDiv').append('fadeOut() completed.')
});
<div id="msgDiv"></div>

<div id="myDiv" class="redDiv">


</div>
Try it

jQuery hide() and show() Method

The jQuery hide() method hides and show() method displays the specified element. You can
specify speed, easing and callback function which will be executed when hide/show
completes.

Syntax:
$('selector expression').hide(speed, easing, callback);
$('selector expression').show(speed, easing, callback);
Example: jQuery hide() & show() Methods
$('#div1').hide(500, function () {
$('#msgDiv').append('Red div is hidden.')
});

$('#div2').hide(500, function () {
$('#msgDiv').append('Yellow div is hidden.')
});

<div id="div1" class="redDiv">


</div>

<div id="div2" class="yellowDiv">


</div>
Try it

jQuery toggle() Method

The jQuery toggle() method hides or displays specified element(s).

Syntax:
$('selector expression').toggle(speed, easing, callback)
Example: jQuery toggle() Method
$('#myDiv').toggle(500, function () {
$('#msgDiv').append('fadeOut completed.')
});

<div id="myDiv" class="redDiv">


</div>

Points to Remember :
1. The jQuery special effect methods allow you to add animations on DOM elements.
2. Use the selector to get the reference of an element(s) and then call jQuery effect
methods to edit it.
3. Important DOM manipulation methods: animate(), queue(), fadeIn(), fadeOut(),
hide(), show(), toggle(), slideUp(), slideDown() etc.

jQuery Animation

jQuery includes methods which give special effects to the elements on hiding, showing,
changing style properties, and fade-in or fade-out operation. These special effect methods can
be useful in building an interactive user interface.

The following table lists jQuery methods for adding special effects to the DOM elements.

jQuery Methods for Special


Description
Effects

animate() Perform custom animation using element's style properties.

Show or manipulate the queue of functions to be executed on


queue()
the specified element.

Stop currently running animations on the specified


stop()
element(s).

fadeIn() Display specified element(s) by fading them to opaque.

fadeOut() Hides specified element(s) by fading them to transparent.

fadeTo() Adjust the opacity of the specified element(s)

Display or hide the specified element(s) by animating their


fadeToggle()
opacity.

hide() Hide specified element(s).

show() Display specified element(s).

toggle() Display hidden element(s) or hide visible element(s).

slideUp() Hide specified element(s) with sliding up motion.

slideDown() Display specified element(s) with sliding down motion.

slideToggle() Display or hide specified element(s) with sliding motion.

Let's look at some important methods for special effects.

jQuery animate() Method


The jQuery animate() method performs custom animation using element's style properties.
The animate() method changes existing style properties to the specified properties with
motion.

Specify a selector to get the reference of an element to which you want to add animation
effect and then call animate() method with JSON object for style properties, speed of
animation and other options.

Syntax:
$('selector expression').animate({ stylePropertyName : 'value'},
duration,
easing,
callback);

$('selector expression').animate({ propertyName : 'value'},{ options });

Apply Animation

In the following example, we are changing height and width of the element with animation.

Example: jQuery animate() Method


$('#myDiv').animate({
height: '200px',
width: '200px'
});

<div id="myDiv" class="redDiv">


</div>
Try it

Set Animation Duration

You can apply animation duration in miliseconds as a second parameter of animate() method.

Example: Set Duration


$('#myDiv').animate({
height: '200px',
width: '200px'
},
5000);

<div id="myDiv" class="redDiv">


</div>
Try it
Apply Easing Method

Specify a string parameter indicating which easing function to use for the transition. The
jQuery library provides two easing function: linear and swing.

Example: Apply Easing Method


$('#myDiv').animate({
height: '200px',
width: '200px'
},
5000, 'swing');

<div id="myDiv" class="redDiv">


</div>
Try it

Callback Function on Animation Complete

Specify a callback function to execute when animation is complete.

Example: Specify Callback Function


$('#myDiv').animate({
height: '200px',
width: '200px'
},
5000,
function () {
$('#msgDiv').append('Animation completed');
});
});

<div id="myDiv" class="redDiv">


</div>

<div id="msgDiv"></div>
Try it

Specify Animation Options

You can specify various options as JSON object. The options include duration, easing, queue,
step, progress, complete, start, done and always. Visit api.jquery.com for more information.

Example: Specify Options


$('#myDiv').animate({
height: '200px',
width: '200px'
},
{ // options parameter
duration: 5000,
complete: function () {
$(this).animate({
height: '100px',
width: '100px'
}, 5000,
function () {
$('#msgDiv').text('Animation completed..');
});
},
start: function () {
$('#msgDiv').append('starting animation..');
}
});

<div id="msgDiv"></div>

<div id="myDiv" class="redDiv">


</div>
Try it

jQuery queue() Method

The jQuery queue() method shows or manipulates the queue of special effect functions to be
executed on the specified element.

Syntax:
$('selector expression').queue();
Example: jQuery queue() Method
$('#myDiv').toggle(500);
$('#myDiv').fadeOut(500);
$('#myDiv').fadeIn(500);
$('#myDiv').slideDown(500);
$('#msgDiv').append('Animation functions: ' + $('#myDiv').queue().length);

<div id="msgDiv"></div>

<div id="myDiv" class="redDiv">


</div>
Try it

jQuery fadeIn() Method

The jQuery fadeIn() method displays specified element(s) by fading them to opaque.

Syntax:
$('selector expression').fadeIn(speed, easing, callback);
Example: jQuery fadeIn() Method
$('#myDiv').fadeIn(5000, function () {
$('#msgDiv').append('fadeIn() completed.')
});

<div id="myDiv" class="redDiv">


</div>

<div id="msgDiv"></div>
Try it

jQuery fadeOut() Method

The jQuery fadeOut() method hides specified element(s) by fading them to transparent.

Syntax:
$('selector expression').fadeOut(speed, easing, callback);
Example: jQuery fadeOut() Method
$('#div1').fadeOut(5000, function () {
$('#msgDiv').append('fadeOut() completed.')
});

<div id="msgDiv"></div>

<div id="myDiv" class="redDiv">


</div>
Try it

jQuery hide() and show() Method

The jQuery hide() method hides and show() method displays the specified element. You can
specify speed, easing and callback function which will be executed when hide/show
completes.

Syntax:
$('selector expression').hide(speed, easing, callback);
$('selector expression').show(speed, easing, callback);
Example: jQuery hide() & show() Methods
$('#div1').hide(500, function () {
$('#msgDiv').append('Red div is hidden.')
});

$('#div2').hide(500, function () {
$('#msgDiv').append('Yellow div is hidden.')
});

<div id="div1" class="redDiv">


</div>

<div id="div2" class="yellowDiv">


</div>
Try it

jQuery toggle() Method

The jQuery toggle() method hides or displays specified element(s).

Syntax:
$('selector expression').toggle(speed, easing, callback)
Example: jQuery toggle() Method
$('#myDiv').toggle(500, function () {
$('#msgDiv').append('fadeOut completed.')
});

<div id="myDiv" class="redDiv">


</div>

Points to Remember :

1. The jQuery special effect methods allow you to add animations on DOM elements.
2. Use the selector to get the reference of an element(s) and then call jQuery effect
methods to edit it.
3. Important DOM manipulation methods: animate(), queue(), fadeIn(), fadeOut(),
hide(), show(), toggle(), slideUp(), slideDown() etc.

jQuery hide()

The jQuery hide() method is used to hide the selected elements.

Syntax:

1. $(selector).hide();
2. $(selector).hide(speed, callback);
3. $(selector).hide(speed, easing, callback);

speed: It is an optional parameter. It specifies the speed of the delay. Its possible vales are
slow, fast and milliseconds.

easing: It specifies the easing function to be used for transition.

callback: It is also an optional parameter. It specifies the function to be called after


completion of hide() effect.

Let's take an example to see the jQuery hide effect.


1. <!DOCTYPE html>
2. <html>
3. <head>
4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></scrip
t>
5. <script>
6. $(document).ready(function(){
7. $("#hide").click(function(){
8. $("p").hide();
9. });
10. });
11. </script>
12. </head>
13. <body>
14. <p>
15. <b>This is a little poem: </b><br/>
16. Twinkle, twinkle, little star<br/>
17. How I wonder what you are<br/>
18. Up above the world so high<br/>
19. Like a diamond in the sky<br/>
20. Twinkle, twinkle little star<br/>
21. How I wonder what you are

22. </p>
23. <button id="hide">Hide</button>
24. </body>
25. </html>

jQuery show()

The jQuery show() method is used to show the selected elements.

Syntax:

1. $(selector).show();
2. $(selector).show(speed, callback);
3. $(selector).show(speed, easing, callback);

speed: It is an optional parameter. It specifies the speed of the delay. Its possible vales are
slow, fast and milliseconds.

easing: It specifies the easing function to be used for transition.

callback: It is also an optional parameter. It specifies the function to be called after


completion of show() effect.

Let's take an example to see the jQuery show effect.


1. <!DOCTYPE html>
2. <html>
3. <head>
4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></scrip
t>
5. <script>
6. $(document).ready(function(){
7. $("#hide").click(function(){
8. $("p").hide();
9. });
10. $("#show").click(function(){
11. $("p").show();
12. });
13. });
14. </script>
15. </head>
16. <body>
17. <p>
18. <b>This is a little poem: </b><br/>
19. Twinkle, twinkle, little star<br/>
20. How I wonder what you are<br/>
21. Up above the world so high<br/>
22. Like a diamond in the sky<br/>
23. Twinkle, twinkle little star<br/>
24. How I wonder what you are
25. </p>
26. <button id="hide">Hide</button>
27. <button id="show">Show</button>
28. </body>
29. </html>

jQuery animate()

The jQuery animate() method provides you a way to create custom animations.

Syntax:

1. $(selector).animate({params}, speed, callback);

Here, params parameter defines the CSS properties to be animated.

The speed parameter is optional and specifies the duration of the effect. It can be set as
"slow" , "fast" or milliseconds.

The callback parameter is also optional and it is a function which is executed after the
animation completes.

Let's take a simple example to see the animation effect.

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></scrip
t>
5. <script>
6. $(document).ready(function(){
7. $("button").click(function(){
8. $("div").animate({left: '450px'});
9. });
10. });
11. </script>
12. </head>
13. <body>
14. <button>Start Animation</button>
15. <p>A simple animation example:</p>
16. <div style="background:#98bf21;height:100px;width:100px;position:absolute;"></di
v>
17. </body>
18. </html>

HTML Forms and CGI

Forms and CGI forms are generally used for two purposes: data collection and interactive
communication. You can conduct surveys or polls, and present registration or online ordering
information through the use of forms. They are also used to create an interactive medium
between the user and the Web server. For example, a form can ask the user to select a
document out of a menu, whereby the server returns the chosen document.

The main advantage of forms is that you can use them to create a front end for numerous
gateways (such as databases or other information servers) that can be accessed by any client
without worrying about platform dependency. On the other hand, there are some
shortcomings with the current implementation:

• The interface does not support any data types besides the general “text” type. The
next HTML specification could contain other data types, such as “int,” “date,” “float,”
and “url.”
• User input cannot be checked on the client side; the user has to press the Submit
button and the CGI program on the server side has to make sure the input is valid.

This lesson covers:

• The HTML tags for writing forms


• How form data is sent to the server
• Examples of designing form-based CGI applications.

HTML Tags

HTML Tags
A form consists of two distinct parts: the HTML code and the CGI program. HTML tags
create the visual representation of the form, while the CGI program decodes (or processes)
the information contained within the form. Before we look at how CGI programs process
form information, let's understand how a form is created. In this section, we'll cover the form
tags and show examples of their use.

The FORM Tag

Here is the beginning of a simple form:

<FORM ACTION="/cgi-bin/program.pl" METHOD="POST">

The <FORM> tag starts the form. A document can consist of multiple forms, but forms
cannot be nested; a form cannot be placed inside another form.

The two attributes within the <FORM> tag ( ACTION and METHOD) are very important.
The ACTION attribute specifies the URL of the CGI program that will process the form
information. You are not limited to using a CGI program on your server to decode form
information; you can specify a URL of a remote host if a program that does what you want is
available elsewhere.

The METHOD attribute specifies how the server will send the form information to the
program. POST sends the data through standard input, while GET passes the information
through environment variables. If no method is specified, the server defaults to GET. Both
methods have their own advantages and disadvantages, which will be covered in detail later
in the chapter.

In addition, another attribute, ENCTYPE, can be specified. This represents the MIME type
(or encoding scheme) for the POST data, since the information is sent to the program as a
data stream. Currently, only two ENCTYPES are allowed: application/x-www-form-
urlencoded and multipart/form-data. If one is not specified, the browser defaults
to application/x-www-form-urlencoded. Appendix D, CGI Lite, shows an example of
using multipart/form-data, while this chapter is devoted to application/x-www-form-
urlencoded.

Text and Password Fields

Most form elements are implemented using the <INPUT> tag. The TYPE attribute
to <INPUT> determines what type of input is being requested. Several different types of
elements are available: text and password fields, radio buttons, and checkboxes. The
following lines are examples of simple text input.

Name: <INPUT TYPE="text" NAME="user" SIZE=40><BR>


Age: <INPUT TYPE="text" NAME="age" SIZE=3 MAXLENGTH=3><BR>
Password: <INPUT TYPE="password" NAME="pass" SIZE=10><BR>

In this case, two text fields and one password field are created using the “text” and
“password” arguments, respectively. The password field is basically the same as a text field
except the characters entered will be displayed as asterisks or bullets. If you skip the TYPE
attribute, a text field will be created by default.
The NAME attribute defines the name of the particular input element. It is not displayed by
the browser, but is used to label the data when transferred to the CGI program. For example,
the first input field has a NAME=“user” attribute. If someone types “andy” into the first input
field, then part of the data sent by the browser will read:

user=andy

The CGI program can later retrieve this information (as we talked about briefly in Chapter
2, Input to the Common Gateway Interface, and will discuss in more detail later in this
chapter) and parse it as needed.

The optional VALUE attribute can be used to insert an initial “default” value into the field.
This string can be overwritten by the user.

Other optional attributes are SIZE and MAXLENGTH. SIZE is the physical size of the input
element; the field will scroll if the input exceeds the size. The default size is 20 characters.
MAXLENGTH defines the maximum number of characters that will be accepted by the
browser; by default there is no limit.

In the following line, the initial text field size is expanded to 40 characters, the maximum
length is specified as 40 as well (so the field will not scroll), and the initial value string is
“Shishir Gundavaram.”

<INPUT TYPE="text" NAME="user" SIZE=40 MAXLENGTH=40 VALUE="Shishir


Gundavaram" >

Before we move on, there is still another type of text field. It is called a “hidden” field and
allows you to store information in the form. The client will not display the field. For example:

<INPUT TYPE="hidden" NAME="publisher" VALUE="ORA">

Hidden fields are most useful for transferring information from one CGI application to
another. See Chapter 8, Multiple Form Interaction, for an example of using hidden fields.

Submit and Reset Buttons

Two more important “types” of the <INPUT> tag are Submit and Reset.

<INPUT TYPE="submit" VALUE="Submit the form">


<INPUT TYPE="reset" VALUE="Clear all fields">

Nearly all forms offer Submit and Reset buttons. The Submit button sends all of the form
information to the CGI program specified by the ACTION attribute. Without this button, the
form will be useless since it will never reach the CGI program.

Browsers supply a default label on Submit and Reset buttons (generally, the unimaginative
labels “Submit” and “Reset,” of course). However, you can override the default labels using
the VALUE attribute.

You can have multiple Submit buttons:


<INPUT TYPE="submit" NAME="option" VALUE="Option 1">
<INPUT TYPE="submit" NAME="option" VALUE="Option 2">

If the user clicked on “Option 1”, the CGI program would get the following data:

option=Option 1

You can also have images as buttons:

<INPUT TYPE="image" SRC="/icons/button.gif" NAME="install"


VALUE="Install Program">

When you click on an image button, the browser will send the coordinates of the click:

install.x=250&install.y=20

Note that each field information is delimited by the “&” character. We will discuss this in
detail later in the chapter. On the other hand, if you are using a text browser, and you select
this button, the browser will send the following data:

install=Install Program

The Reset button clears all the information entered by the user. Users can press Reset if they
want to erase all their entries and start all over again.

Figure 4.1 shows how the form will look in Netscape Navigator.

Figure 4.1: Form with text input fields

Radio Buttons and Checkboxes

Radio buttons and checkboxes are typically used to present the user with several options.
A checkbox creates square buttons (or boxes) that can be toggled on or off. In the example
below, it is used to create four square checkboxes.

<FORM ACTION="/cgi-bin/program.pl" METHOD="POST">


Which movies do you want to order: <BR>
Amadeus <INPUT TYPE="checkbox" NAME="amadeus">
The Last Emperor <INPUT TYPE="checkbox" NAME="emperor">
Gandhi <INPUT TYPE="checkbox" NAME="gandhi">
Schindler's List <INPUT TYPE="checkbox" NAME="schindler">
<BR>

If a user toggles a checkbox “on” and then submits the form, the browser uses the value “on”
for that variable name. For example, if someone clicks on the “Gandhi” box in the above
example, the browser will send:

gandhi=on

You can override the value “on” using the VALUE attribute:

Gandhi <INPUT TYPE="checkbox" NAME="gandhi" VALUE="yes">

Now when the “Gandhi” checkbox is checked, the browser will send:

gandhi=yes

One checkbox is not related to another. Any number of them can be checked at the same
time. A radio button differs from a checkbox in that only one radio button can be enabled at a
time. For example:

How do you want to pay for this product: <BR>


Master Card: <INPUT TYPE="radio" NAME="payment" VALUE="MC"
CHECKED><BR>
Visa: <INPUT TYPE="radio" NAME="payment" VALUE="Visa"><BR>
American Express: <INPUT TYPE="radio" NAME="payment" VALUE="AMEX"><BR>
Discover: <INPUT TYPE="radio" NAME="payment" VALUE="Discover"><BR>
</FORM>

Here are a few guidelines for making a radio button work properly:

• All options must have the same NAME (in this example, “payment”). This is how the
browser knows that they should be grouped together, and can therefore ensure that
only one radio button using the same NAME can be selected at a time.
• Whereas with checkboxes supplying a different VALUE is only a matter of taste, with
radio buttons different VALUEs are crucial to getting meaningful results. Without a
specified VALUE, no matter which item is checked, the browser will assign the string
“on” to the “payment” NAME variable. The CGI program therefore has no way to
know which item was actually checked. So each item in a radio button needs to be
assigned a different VALUE to make sure that the CGI program knows which one
was selected.
For both radio buttons and checkboxes, the CHECKED attribute determines whether the item
should be enabled by default. In the radio button example, the “Master Card” option is given
a CHECKED value, effectively making it the default value.

Figure 4.2 shows how this example will be rendered by the browser.

Figure 4.2: Form with radio buttons and checkboxes

Menus and Scrolled Lists

Menus and scrolled lists are generally used to present a large number of options or choices to
the user. The following is an example of a menu:

<FORM ACTION="/cgi-bin/program.pl" METHOD="POST">


Choose a method of payment:
<SELECT NAME="card" SIZE=1>
<OPTION SELECTED>Master Card
<OPTION>Visa
<OPTION>American Express
<OPTION>Discover
</SELECT>

Option menus and scrolled lists are created using the SELECT tag, which has an opening and
a closing tag. The SIZE attribute determines if a menu or a list is displayed. A value of 1
produces a menu, and a value greater than 2 produces a scrolled list, in which case the
number represents the number of items that will be visible at one time.

A selection in a menu or scrolled list is added using the OPTION tag. The SELECTED
attribute to OPTION allows you to set a default selection.

Now for an example of a scrolled list (a list with a scrollbar):


<SELECT NAME="books" SIZE=3 MULTIPLE>
<OPTION SELECTED>TCP/IP Network Administration
<OPTION>Linux Network Administrators Guide
<OPTION>DNS and BIND
<OPTION>Computer Security Basics
<OPTION>System Performance Tuning
</SELECT>
</FORM>

The example above creates a scrolled list with three visible items and the ability to select
multiple options. (The MULTIPLE attribute specifies that more than one item can be
selected.)

Figure 4.3 shows what the menus and scrolled list look like.

Figure 4.3: Form with menus and scrolled lists

Multiline Text Fields

You must have seen numerous guestbooks on the Web that ask for your comments or
opinions, where you can enter a lot of information. This is accomplished by using a multiline
text field. Here is an example:

<FORM ACTION="/cgi-bin/program.pl" METHOD="POST">


<TEXTAREA ROWS=10 COLS=40 NAME="comments">
</TEXTAREA>

This creates a scrolled text field with 10 rows and 40 columns. (10 rows and 40 columns
designates only the visible text area; the text area will scroll if the user types further).

Notice that you need both the beginning <TEXTAREA> and the
ending </TEXTAREA> tags. You can enter default information between these tags.

<TEXTAREA ROWS=10 COLS=40 NAME="comments_2">


This is some default information.
Some more...
And some more...
</TEXTAREA>
</FORM>

You have to remember that newlines (or carriage returns) are not ignored in this field--unlike
HTML. In the preceding example, the three separate lines will be displayed just as you typed
them.

The multiline examples will be rendered by the browser as shown in Figure 4.4.

Figure 4.4: Form with multiline text input

Quick Reference to Form Tags

Before we get going, here's a short list of all the available form tags:

Table 4.1: Form Tags

Form Tag Description

<FORM ACTION=“/cgi-bin/prog.pl” METHOD=“POST”> Start the form

<INPUT TYPE=“text” NAME=“name” VALUE=“value” SIZE=“size”> Text field

<INPUT TYPE=“password” NAME=“value” VALUE=“value” Password


SIZE=“size”> field
<INPUT TYPE=“hidden” NAME=“name” VALUE=“value”> Hidden field

<INPUT TYPE=“checkbox” NAME=“name” VALUE=“value”> Checkbox

<INPUT TYPE=“radio” NAME=“name” VALUE=“value”> Radio button

<SELECT NAME=“name” SIZE=1> <OPTION SELECTED>One


Menu
<OPTION>Two : </SELECT>

<SELECT NAME=“name” SIZE=n MULTIPLE> Scrolled list

Multiline text
<TEXTAREA ROWS=yy COLS=xx NAME=“name”> . . </TEXTAREA>
fields

<INPUT TYPE=“submit” VALUE=“Message!”> <INPUT TYPE=“submit”


Submit
NAME=“name” VALUE=“value”> <INPUT TYPE=“image”
buttons
SRC=“/image” NAME=“name” VALUE=“value”>

<INPUT TYPE=“reset” VALUE=“Message!”> Reset button

</FORM> Ends form

What is a Servlet?

Servlet can be described in many ways, depending on the context.

• Servlet is a technology which is used to create a web application.


• Servlet is an API that provides many interfaces and classes including documentation.
• Servlet is an interface that must be implemented for creating any Servlet.
• Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a dynamic web
page.
Life Cycle of a Servlet (Servlet Life Cycle)

1. Life Cycle of a Servlet


1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

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

1) Servlet class is loaded

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

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:

1. public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is received.
If servlet is not initialized, it follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service method. Notice that servlet is
initialized only once. The syntax of the service method of the Servlet interface is given
below:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked

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

1. public void destroy()

Servlet API

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet
api.

The javax.servlet package contains many interfaces and classes that are used by the servlet
or web container. These are not specific to any protocol.

The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.

Let's see what are the interfaces of javax.servlet package.


Interfaces in javax.servlet package

There are many interfaces in javax.servlet package. They are as follows:

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in javax.servlet package

There are many classes in javax.servlet package. They are as follows:

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

Interfaces in javax.servlet.http package

There are many interfaces in javax.servlet.http package. They are as follows:

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)

Classes in javax.servlet.http package

There are many classes in javax.servlet.http package. They are as follows:

1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
HTTP Requests

The request sent by the computer to a web server, contains all sorts of potentially interesting
information; it is known as HTTP requests.

The HTTP client sends the request to the server in the form of request message which
includes following information:

• The Request-line
• The analysis of source IP address, proxy and port
• The analysis of destination IP address, protocol, port and host
• The Requested URI (Uniform Resource Identifier)
• The Request method and Content
• The User-Agent header
• The Connection control header
• The Cache control header

The HTTP request method indicates the method to be performed on the resource identified by
the Requested URI (Uniform Resource Identifier). This method is case-sensitive and
should be used in uppercase.
The HTTP request methods are:

HTTP
Description
Request

GET Asks to get the resource at the requested URL.

Asks the server to accept the body info attached. It is like GET request with
POST
extra info sent with the request.

Asks for only the header part of whatever a GET would return. Just like GET
HEAD
but with no body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

Asks for a list of the HTTP methods to which the thing at the request URL
OPTIONS
can respond

Get vs. Post

There are many differences between the Get and Post request. Let's see these differences:

GET POST
In case of post request, large amount of
1) In case of Get request, only limited amount of
data can be sent because data is sent in
data can be sent because data is sent in header.
body.
2) Get request is not secured because data is Post request is secured because data is
exposed in URL bar. not exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
4) Get request is idempotent . It means second
request will be ignored until response of first Post request is non-idempotent.
request is delivered
5) Get request is more efficient and used more Post request is less efficient and used less
than Post. than get.

GET and POST

Two common methods for the request-response between a server and client are:

• GET- It requests the data from a specified resource


• POST- It submits the processed data to a specified resource
Anatomy of Get Request

The query string (name/value pairs) is sent inside the URL of a GET request:

1.GET/RegisterDao.jsp?name1=value1&name2=value2

As we know that data is sent in request header in case of get request. It is the default request
type. Let's see what information is sent to the server.
Some other features of GET requests are:

• It remains in the browser history


• It can be bookmarked
• It can be cached
• It have length restrictions
• It should never be used when dealing with sensitive data
• It should only be used for retrieving the data

Anatomy of Post Request

The query string (name/value pairs) is sent in HTTP message body for a POST request:

1. POST/RegisterDao.jsp HTTP/1.1
2. Host: www. javatpoint.com
3. name1=value1&name2=value2

As we know, in case of post request original data is sent in message body. Let's see how
information is passed to the server in case of post request.

Some other features of POST requests are:

• This requests cannot be bookmarked


• This requests have no restrictions on length of data
• This requests are never cached
• This requests do not retain in the browser history
Servlet Container

It provides the runtime environment for JavaEE (j2ee) applications. The client/user can
request only a static WebPages from the server. If the user wants to read the web pages as per
input then the servlet container is used in java.

The servlet container is the part of web server which can be run in a separate process. We can
classify the servlet container states in three types:

Servlet Container States

The servlet container is the part of web server which can be run in a separate process. We can
classify the servlet container states in three types:

• Standalone: It is typical Java-based servers in which the servlet container and the
web servers are the integral part of a single program. For example:- Tomcat running
by itself
• In-process: It is separated from the web server, because a different program runs
within the address space of the main server as a plug-in. For example:- Tomcat
running inside the JBoss.
• Out-of-process: The web server and servlet container are different programs which
are run in a different process. For performing the communications between them, web
server uses the plug-in provided by the servlet container.

The Servlet Container performs many operations that are given below:

• Life Cycle Management


• Multithreaded support
• Object Pooling
• Security etc.

Session Tracking

session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we need
to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in the
figure given below:

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.

How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the
user as the old user.
Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.

Advantage of Cookies

1. Simplest technique of maintaining the state.


2. Cookies are maintained at client side.

Disadvantage of Cookies

1. It will not work if cookie is disabled from the browser.


2. Only textual information can be set in Cookie object.

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot


of useful methods for cookies.

Constructor of Cookie class


Constructor Description

Cookie() constructs a cookie.


Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int


Sets the maximum age of the cookie in seconds.
expiry)

Returns the name of the cookie. The name cannot be changed


public String getName()
after creation.

public String getValue() Returns the value of the cookie.

public void setName(String


changes the name of the cookie.
name)

public void setValue(String


changes the value of the cookie.
value)

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by
other interfaces. They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is


used to add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.

How to create Cookie?

Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

1. Cookie ck=new Cookie("user","");//deleting value of cookie


2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response
How to get Cookies?

Let's see the simple code to get all the cookies.

1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of
cookie
4. }

Simple example of Servlet Cookies

In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet. As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the different value.

index.html

1. <form action="servlet1" method="post">


2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22. }
web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>

URL Rewriting

1. URL Rewriting
2. Advantage of URL Rewriting
3. Disadvantage of URL Rewriting
4. Example of URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next
resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is
separated from another parameter using the ampersand(&). When the user clicks the
hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we
can use getParameter() method to obtain a parameter value.
Advantage of URL Rewriting

1. It will always work whether cookie is disabled or not (browser independent).


2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send Only textual information

Example of using URL Rewriting

In this example, we are maintaning the state of the user using link. For this purpose, we are
appending the name of the user in the query string and getting the value from the query string
in another page.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. //appending the username in the query string
18. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
19.
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. }
24.
25. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. //getting value from the query string
14. String n=request.getParameter("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21. }

web.xml

1. <web-app>
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>FirstServlet</servlet-class>
5. </servlet>
6.
7. <servlet-mapping>
8. <servlet-name>s1</servlet-name>
9. <url-pattern>/servlet1</url-pattern>
10. </servlet-mapping>
11.
12. <servlet>
13. <servlet-name>s2</servlet-name>
14. <servlet-class>SecondServlet</servlet-class>
15. </servlet>
16.
17. <servlet-mapping>
18. <servlet-name>s2</servlet-name>
19. <url-pattern>/servlet2</url-pattern>
20. </servlet-mapping>
21.
22. </web-app>

HttpSession interface

1. HttpSession interface
2. How to get the HttpSession object
3. Commonly used methods of HttpSession interface
4. Example of using HttpSession

In such case, container creates a session id for each user.The container uses this id to identify
the particular user.An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. public HttpSession getSession():Returns the current session associated with this


request, or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns
a new session.

Commonly used methods of HttpSession interface

1. public String getId():Returns a string containing the unique identifier value.


2. public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession

In this example, we are setting the attribute in the session scope in one servlet and getting that
value from the session scope in another servlet. To set the attribute in the session scope, we
have used the setAttribute() method of HttpSession interface and to get the attribute, we have
used the getAttribute method.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. HttpSession session=request.getSession();
18. session.setAttribute("uname",n);
19.
20. out.print("<a href='servlet2'>visit</a>");
21.
22. out.close();
23.
24. }catch(Exception e){System.out.println(e);}
25. }
26.
27. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. HttpSession session=request.getSession(false);
14. String n=(String)session.getAttribute("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>

JSP

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.

Difference between JSP and Servlets


Advantages of JSP over Servlet

There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.
4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code. Moreover, we can use EL, implicit objects, etc.

JSP

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.

JSP Life Cycle


The Lifecycle of a JSP Page

The JSP pages follow these phases:

• Translation of JSP Page


• Compilation of JSP Page
• Classloading (the classloader loads class file)
• Instantiation (Object of the Generated Servlet is created).
• Initialization ( the container invokes jspInit() method).
• Request processing ( the container invokes _jspService() method).
• Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator. The JSP translator is a part of the web server which is responsible for translating
the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets
converted into the class file. Moreover, all the processes that happen in Servlet are performed
on JSP later like initialization, committing response to the browser and destroy.

Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in
the JSP page. We will learn scriptlet tag later.

1. <html>
2. <body>
3. <% out.print("Hello world..."); %>
4. </body>
5. </html>

It will print Hello World... on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

• Start the server


• Put the JSP file in a folder and deploy on the server
• Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.
JSP API

The JSP API

1. The JSP API


2. javax.servlet.jsp package
3. The JspPage interface
4. The HttpJspPage interface

The JSP API consists of two packages:

1. javax.servlet.jsp
2. javax.servlet.jsp.tagext

javax.servlet.jsp package

The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as
follows:

1. JspPage
2. HttpJspPage

The classes are as follows:

• JspWriter
• PageContext
• JspFactory
• JspEngineInfo
• JspException
• JspError

The JspPage interface

According to the JSP specification, all the generated servlet classes must implement the
JspPage interface. It extends the Servlet interface. It provides two life cycle methods.
Methods of JspPage interface

1. public void jspInit(): It is invoked only once during the life cycle of the JSP when
JSP page is requested firstly. It is used to perform initialization. It is same as the init()
method of Servlet interface.
2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP
before the JSP page is destroyed. It can be used to perform some clean up operation

The HttpJspPage interface

The HttpJspPage interface provides the one life cycle method of JSP. It extends the JspPage
interface.

Method of HttpJspPage interface:

1. public void _jspService(): It is invoked each time when request for the JSP page
comes to the container. It is used to process the request. The underscore _ signifies
that you cannot override this method.

JSP Tags

In this lesson we will be learning about the different types of JSP Tags.

JSP Scriptlets

JSP Scripting elements

The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:

• scriptlet tag
• expression tag
• declaration tag

JSP scriptlet tag

A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

1.<% java source code %>


Example of JSP scriptlet tag

In this example, we are displaying a welcome message.

1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
Example of JSP scriptlet tag that prints the user name

In this example, we have created two files index.html and welcome.jsp. The index.html file
gets the username from the user and the welcome.jsp file prints the username with the
welcome message.

File: index.html

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>

File: welcome.jsp

1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>

JSP expression tag

The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data. It is mainly used to print the values of variable
or method.

Syntax of JSP expression tag

1. <%= statement %>

Example of JSP expression tag

In this example of jsp expression tag, we are simply displaying a welcome message.

1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>
Note: Do not end your statement with semicolon in case of expression tag.
Example of JSP expression tag that prints current time

To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the
instance of Calendar class by the getInstance() method.

index.jsp

1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>

Example of JSP expression tag that prints the user name

In this example, we are printing the username using the expression tag. The index.html file
gets the username and sends the request to the welcome.jsp file, which displays the username.

File: index.jsp

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>

File: welcome.jsp

1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>

JSP Implicit Objects

There are 9 jsp implicit objects. These objects are created by the web containerthat are
available to all the jsp pages.

The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:


Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

1) JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the object
of JspWriter. In case of servlet you need to write:

1. PrintWriter out=response.getWriter();

But in JSP, you don't need to write this code.

Example of out implicit object

In this example we are simply displaying date and time.

index.jsp

1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
JSP request implicit object

The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp
request by the web container. It can be used to get request information such as parameter,
header information, remote address, server name, server port, content type, character
encoding etc.

It can also be used to set, get and remove attributes from the jsp request scope.

Let's see the simple example of request implicit object where we are printing the name of the
user with welcome message.

Example of JSP request implicit object


index.html

1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>

welcome.jsp

1. <%
2. String name=request.getParameter("uname");
3. out.print("welcome "+name);
4. %>

JSP response implicit object

In JSP, response is an implicit object of type HttpServletResponse. The instance of


HttpServletResponse is created by the web container for each jsp request.

It can be used to add or manipulate response such as redirect response to another resource,
send error etc.

Let's see the example of response implicit object where we are redirecting the response to the
Google.

Example of response implicit object


index.html

1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp

1. <%
2. response.sendRedirect("http://www.google.com");
3. %>

JSP application implicit object

In JSP, application is an implicit object of type ServletContext.

The instance of ServletContext is created only once by the web container when application or
project is deployed on the server.

This object can be used to get initialization parameter from configuaration file (web.xml). It
can also be used to get, set or remove attribute from the application scope.

This initialization parameter can be used by all jsp pages.


Example of application implicit object:
index.html

1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>

web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. <context-param>
14. <param-name>dname</param-name>
15. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
16. </context-param>
17.
18. </web-app>
welcome.jsp

1. <%
2.
3. out.print("Welcome "+request.getParameter("uname"));
4.
5. String driver=application.getInitParameter("dname");
6. out.print("driver name is="+driver);
7.
8. %>

session implicit object


In JSP, session is an implicit object of type HttpSession.The Java developer can use this
object to set,get or remove attribute or to get session information.

Example of session implicit object


index.html

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>

welcome.jsp

1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp

1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>

exception implicit object


In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be
used to print the exception. But it can only be used in error pages.It is better to learn it after
page directive. Let's see a simple example:

Example of exception implicit object:


error.jsp

1. <%@ page isErrorPage="true" %>


2. <html>
3. <body>
4.
5. Sorry following exception occured:<%= exception %>
6.
7. </body>
8. </html>

JSP Directives

The jsp directives are messages that tells the web container how to translate a JSP page into
the corresponding servlet.

There are three types of directives:

• page directive
• include directive
• taglib directive

Syntax of JSP Directive

1. <%@ directive attribute="value" %>


JSP page directive

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

1. <%@ page attribute="value" %>

Attributes of JSP page directive

• import
• contentType
• extends
• info
• buffer
• language
• isELIgnored
• isThreadSafe
• autoFlush
• session
• pageEncoding
• errorPage
• isErrorPage

1)import
The import attribute is used to import class,interface or all the members of a package.It is
similar to import keyword in java class or interface.

Example of import attribute

1. <html>
2. <body>
3.
4. <%@ page import="java.util.Date" %>
5. Today is: <%= new Date() %>
6.
7. </body>
8. </html>

2)contentType

The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of
the HTTP response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute

1. <html>
2. <body>
3.
4. <%@ page contentType=application/msword %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>

3)extends

The extends attribute defines the parent class that will be inherited by the generated servlet.It
is rarely used.

4)info

This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.

Example of info attribute

1. <html>
2. <body>
3.
4. <%@ page info="composed by Sonoo Jaiswal" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>

The web container will create a method getServletInfo() in the resulting servlet.For example:

1. public String getServletInfo() {


2. return "composed by Sonoo Jaiswal";
3. }

5)buffer

The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.

Example of buffer attribute

1. <html>
2. <body>
3.
4. <%@ page buffer="16kb" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>
6)language

The language attribute specifies the scripting language used in the JSP page. The default
value is "java".

7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default
its value is false i.e. Expression Language is enabled by default. We see Expression
Language later.

1. <%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page,
you can use isThreadSafe attribute of page directive.The value of isThreadSafe value is
true.If you make it false, the web container will serialize the multiple requests, i.e. it will
wait until the JSP finishes responding to a request before passing another request to it.If you
make the value of isThreadSafe attribute like:

<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

1. public class SimplePage_jsp extends HttpJspBase


2. implements SingleThreadModel{
3. .......
4. }

9)errorPage

The errorPage attribute is used to define the error page, if exception occurs in the current
page, it will be redirected to the error page.

Example of errorPage attribute

1. //index.jsp
2. <html>
3. <body>
4.
5. <%@ page errorPage="myerrorpage.jsp" %>
6.
7. <%= 100/0 %>
8.
9. </body>
10. </html>
10)isErrorPage

The isErrorPage attribute is used to declare that the current page is the error page.

Note: The exception object can only be used in the error page.
Example of isErrorPage attribute

1. //myerrorpage.jsp
2. <html>
3. <body>
4.
5. <%@ page isErrorPage="true" %>
6.
7. Sorry an exception occured!<br/>
8. The exception is: <%= exception %>
9.
10. </body>
11. </html>

Jsp Include Directive

1. Include directive
2. Advantage of Include directive
3. Example of include directive

The include directive is used to include the contents of any resource it may be jsp file, html
file or text file. The include directive includes the original content of the included resource at
page translation time (the jsp page is translated only once so it will be better to include static
resource).

Advantage of Include directive

Code Reusability

Syntax of include directive

1. <%@ include file="resourceName" %>

Example of include directive

In this example, we are including the content of the header.html file. To run this example you
must create an header.html file.

1. <html>

1. <body>
2.
3. <%@ include file="header.html" %>
4.
5. Today is: <%= java.util.Calendar.getInstance().getTime() %>
6.
7. </body>
8. </html>

Note: The include directive includes the original content, so the actual page size grows at
runtime.

JSP Taglib directive

1. JSP Taglib directive


2. Example of JSP Taglib directive

The JSP taglib directive is used to define a tag library that defines many tags. We use the
TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we will use
this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive

1. <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive

In this example, we are using our tag named currentDate. To use this tag we must specify the
taglib directive so the container may get information about the tag.

1. <html>
2. <body>
3.
4. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
5.
6. <mytag:currentDate/>
7.
8. </body>
9. </html>

What is xml

• Xml (eXtensible Markup Language) is a mark up language.


• XML is designed to store and transport data.
• Xml was released in late 90’s. it was created to provide an easy to use and store self
describing data.
• XML became a W3C Recommendation on February 10, 1998.
• XML is not a replacement for HTML.
• XML is designed to be self-descriptive.
• XML is designed to carry data, not to display data.
• XML tags are not predefined. You must define your own tags.
• XML is platform independent and language independent.
Note: Self-describing data is the data that describes both its content and structure.
What is mark-up language

A mark up language is a modern system for highlight or underline a document.

Students often underline or highlight a passage to revise easily, same in the sense of modern
mark up language highlighting or underlining is replaced by tags.

Prerequisite

Before you start to learn xml, you should know basic of HTML & JavaScript.

Why xml

Platform Independent and Language Independent: The main benefit of xml is that you
can use it to take data from a program like Microsoft SQL, convert it into XML then share
that XML with other programs and platforms. You can communicate between two platforms
which are generally very difficult.

The main thing which makes XML truly powerful is its international acceptance. Many
corporation use XML interfaces for databases, programming, office application mobile
phones and more. It is due to its platform independent feature.

Features and Advantages of XML

XML is widely used in the era of web development. It is also used to simplify data storage
and data sharing.

The main features or advantages of XML are given below.

1) XML separates data from HTML

If you need to display dynamic data in your HTML document, it will take a lot of work to
edit the HTML each time the data changes.

With XML, data can be stored in separate XML files. This way you can focus on using
HTML/CSS for display and layout, and be sure that changes in the underlying data will not
require any changes to the HTML.

With a few lines of JavaScript code, you can read an external XML file and update the data
content of your web page.

2) XML simplifies data sharing

In the real world, computer systems and databases contain data in incompatible formats.

XML data is stored in plain text format. This provides a software- and hardware-independent
way of storing data.
This makes it much easier to create data that can be shared by different applications.

3) XML simplifies data transport

One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.

Exchanging data as XML greatly reduces this complexity, since the data can be read by
different incompatible applications.

4) XML simplifies Platform change

Upgrading to new systems (hardware or software platforms), is always time consuming.


Large amounts of data must be converted and incompatible data is often lost.

XML data is stored in text format. This makes it easier to expand or upgrade to new operating
systems, new applications, or new browsers, without losing data.

5) XML increases data availability

Different applications can access your data, not only in HTML pages, but also from XML
data sources.

With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc), and make it more available for blind people, or
people with other disabilities.

6) XML can be used to create new internet languages

A lot of new Internet languages are created with XML.

Here are some examples:

• XHTML
• WSDL for describing available web services
• WAP and WML as markup languages for handheld devices
• RSS languages for news feeds
• RDF and OWL for describing resources and ontology
• SMIL for describing multimedia for the web

Example of XML Document

XML documents uses a self-describing and simple syntax:

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


2. <note>
3. <to>Tove</to>
4. <from>Jani</from>
5. <heading>Reminder</heading>
6. <body>Don't forget me this weekend!</body>
7. </note>

The first line is the XML declaration. It defines the XML version (1.0) and the encoding used
(ISO-8859-1 = Latin-1/West European character set).

The next line describes the root element of the document (like saying: "this document is a
note"):

1. <note>

The next 4 lines describe 4 child elements of the root (to, from, heading, and body).

1. <to>Tove</to>
2. <from>Jani</from>
3. <heading>Reminder</heading>
4. <body>Don't forget me this weekend!</body>

And finally the last line defines the end of the root element.

1. </note>

XML documents must contain a root element. This element is "the parent" of all other
elements.

The elements in an XML document form a document tree. The tree starts at the root and
branches to the lowest level of the tree.

All elements can have sub elements (child elements).

1. <root>
2. <child>
3. <subchild>.....</subchild>
4. </child>
5. </root>

The terms parent, child, and sibling are used to describe the relationships between elements.
Parent elements have children. Children on the same level are called siblings (brothers or
sisters).

All elements can have text content and attributes (just like in HTML).

Another Example of XML: Books

File: books.xml

1. <bookstore>
2. <book category="COOKING">
3. <title lang="en">Everyday Italian</title>
4. <author>Giada De Laurentiis</author>
5. <year>2005</year>
6. <price>30.00</price>
7. </book>
8. <book category="CHILDREN">
9. <title lang="en">Harry Potter</title>
10. <author>J K. Rowling</author>
11. <year>2005</year>
12. <price>29.99</price>
13. </book>
14. <book category="WEB">
15. <title lang="en">Learning XML</title>
16. <author>Erik T. Ray</author>
17. <year>2003</year>
18. <price>39.95</price>
19. </book>
20. </bookstore>

Test it Now

The root element in the example is <bookstore>. All elements in the document are contained
within <bookstore>.

The <book> element has 4 children: <title>,< author>, <year> and <price>.

Another Example of XML: Emails

File: emails.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <emails>
3. <email>
4. <to>Vimal</to>
5. <from>Sonoo</from>
6. <heading>Hello</heading>
7. <body>Hello brother, how are you!</body>
8. </email>
9. <email>
10. <to>Peter</to>
11. <from>Jack</from>
12. <heading>Birth day wish</heading>
13. <body>Happy birth day Tom!</body>
14. </email>
15. <email>
16. <to>James</to>
17. <from>Jaclin</from>
18. <heading>Morning walk</heading>
19. <body>Please start morning walk to stay fit!</body>
20. </email>
21. <email>
22. <to>Kartik</to>
23. <from>Kumar</from>
24. <heading>Health Tips</heading>
25. <body>Smoking is injurious to health!</body>
26. </email>
27. </emails>

XML Attributes

XML elements can have attributes. By the use of attributes we can add the information about
the element.

XML attributes enhance the properties of the elements.

Note: XML attributes must always be quoted. We can use single or double quote.

Let us take an example of a book publisher. Here, book is the element and publisher is the
attribute.

<book publisher="Tata McGraw Hill"></book>

Or

1. <book publisher='Tata McGraw Hill'></book>

Metadata should be stored as attribute and data should be stored as element.

1. <book>
2. <book category="computer">
3. <author> A & B </author>
4. </book>

Data can be stored in attributes or in child elements. But there are some limitations in using
attributes, over child elements

Why should we avoid XML attributes

• Attributes cannot contain multiple values but child elements can have multiple values.
• Attributes cannot contain tree structure but child element can.
• Attributes are not easily expandable. If you want to change in attribute's vales in
future, it may be complicated.
• Attributes cannot describe structure but child elements can.
• Attributes are more difficult to be manipulated by program code.
• Attributes values are not easy to test against a DTD, which is used to define the legal
elements of an XML document.

Difference between attribute and sub-element


In the context of documents, attributes are part of markup, while sub elements are part of the
basic document contents.

In the context of data representation, the difference is unclear and may be confusing.

Same information can be represented in two ways:

1st way:

1. <book publisher="Tata McGraw Hill"> </book>

2nd way:

1. <book>
2. <publisher> Tata McGraw Hill </publisher>
3. </book>

In the first example publisher is used as an attribute and in the second example publisher is an
element.

Both examples provide the same information but it is good practice to avoid attribute in XML
and use elements instead of attributes.

XML Validation

A well formed XML document can be validated against DTD or Schema.

A well-formed XML document is an XML document with correct syntax. It is very necessary
to know about valid XML document before knowing XML validation.

Valid XML document

It must be well formed (satisfy all the basic syntax condition)

It should be behave according to predefined DTD or XML schema

Rules for well formed XML

• It must begin with the XML declaration.


• It must have one unique root element.
• All start tags of XML documents must match end tags.
• XML tags are case sensitive.
• All elements must be closed.
• All elements must be properly nested.
• All attributes values must be quoted.
• XML entities must be used for special characters.
XML DTD

A DTD defines the legal elements of an XML document

In simple words we can say that a DTD defines the document structure with a list of legal
elements and attributes.

XML schema is a XML based alternative to DTD.

Actually DTD and XML schema both are used to form a well formed XML document.

We should avoid errors in XML documents because they will stop the XML programs

XML schema

It is defined as an XML language

Uses namespaces to allow for reuses of existing definitions

It supports a large number of built in data types and definition of derived data types

XML Attributes

XML elements can have attributes. By the use of attributes we can add the information about
the element.

XML attributes enhance the properties of the elements.


Note: XML attributes must always be quoted. We can use single or double quote.

Let us take an example of a book publisher. Here, book is the element and publisher is the
attribute.

<book publisher="Tata McGraw Hill"></book>

Or

1. <book publisher='Tata McGraw Hill'></book>

Metadata should be stored as attribute and data should be stored as element.

1. <book>
2. <book category="computer">
3. <author> A & B </author>
4. </book>

Data can be stored in attributes or in child elements. But there are some limitations in using
attributes, over child elements.

Why should we avoid XML attributes

• Attributes cannot contain multiple values but child elements can have multiple values.
• Attributes cannot contain tree structure but child element can.
• Attributes are not easily expandable. If you want to change in attribute's vales in
future, it may be complicated.
• Attributes cannot describe structure but child elements can.
• Attributes are more difficult to be manipulated by program code.
• Attributes values are not easy to test against a DTD, which is used to define the legal
elements of an XML document.

Difference between attribute and sub-element

In the context of documents, attributes are part of markup, while sub elements are part of the
basic document contents.

In the context of data representation, the difference is unclear and may be confusing.

Same information can be represented in two ways:

1st way:

1. <book publisher="Tata McGraw Hill"> </book>

2nd way:

1. <book>
2. <publisher> Tata McGraw Hill </publisher>
3. </book>
In the first example publisher is used as an attribute and in the second example publisher is an
element.

Both examples provide the same information but it is good practice to avoid attribute in XML
and use elements instead of attributes.

What is DTD

DTD stands for Document Type Definition. It defines the legal building blocks of an XML
document. It is used to define document structure with a list of legal elements and attributes.

Purpose of DTD

Its main purpose is to define the structure of an XML document. It contains a list of legal
elements and define the structure with the help of them.

Checking Validation

Before proceeding with XML DTD, you must check the validation. An XML document is
called "well-formed" if it contains the correct syntax.

A well-formed and valid XML document is one which have been validated against DTD.

Visit http://www.xmlvalidation.com to validate the XML file.

Valid and well-formed XML document with DTD

Let's take an example of well-formed and valid XML document. It follows all the rules of
DTD.

employee.xml

1. <?xml version="1.0"?>
2. <!DOCTYPE employee SYSTEM "employee.dtd">
3. <employee>
4. <firstname>vimal</firstname>
5. <lastname>jaiswal</lastname>
6. <email>vimal@javatpoint.com</email>
7. </employee>

In the above example, the DOCTYPE declaration refers to an external DTD file. The content
of the file is shown in below paragraph.

employee.dtd

1. <!ELEMENT employee (firstname,lastname,email)>


2. <!ELEMENT firstname (#PCDATA)>
3. <!ELEMENT lastname (#PCDATA)>
4. <!ELEMENT email (#PCDATA)>
Test it Now
Description of DTD

<!DOCTYPE employee : It defines that the root element of the document is employee.

<!ELEMENT employee: It defines that the employee element contains 3 elements


"firstname, lastname and email".

<!ELEMENT firstname: It defines that the firstname element is #PCDATA typed. (parse-
able data type).

<!ELEMENT lastname: It defines that the lastname element is #PCDATA typed. (parse-
able data type).

<!ELEMENT email: It defines that the email element is #PCDATA typed. (parse-able data
type).

XML DTD with entity declaration

A doctype declaration can also define special strings that can be used in the XML file.

An entity has three parts:

1. An ampersand (&)
2. An entity name
3. A semicolon (;)

Syntax to declare entity:

1. <!ENTITY entity-name "entity-value">

Let's see a code to define the ENTITY in doctype declaration.

author.xml

1. <?xml version="1.0" standalone="yes" ?>


2. <!DOCTYPE author [
3. <!ELEMENT author (#PCDATA)>
4. <!ENTITY sj "Sonoo Jaiswal">
5. ]>
6. <author>&sj;</author>

Note: A single DTD can be used in many XML files

XML CSS

Purpose of CSS in XML


CSS (Cascading Style Sheets) can be used to add style and display information to an XML
document. It can format the whole XML document.

How to link XML file with CSS


To link XML files with CSS, you should use the following syntax:

1. <?xml-stylesheet type="text/css" href="cssemployee.css"?>

XML CSS Example


Let's see the css file.

cssemployee.css

employee
{
background-color: pink;
}
firstname,lastname,email
{
font-size:25px;
display:block;
color: blue;
margin-left: 50px;
}

Let's create the DTD file.

employee.dtd

<!ELEMENT employee (firstname,lastname,email)>


<!ELEMENT firstname (#PCDATA)>
<!ELEMENT lastname (#PCDATA)>
<!ELEMENT email (#PCDATA)>

Let's see the xml file using CSS and DTD.

employee.xml

<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="cssemployee.css"?>
<!DOCTYPE employee SYSTEM "employee.dtd">
<employee>
<firstname>John</firstname>
<lastname>Tulip</lastname>
<email>jt@gmail.com</email>
</employee>
CSS is not generally used to format XML file. W3C recommends XSLT instead of CSS.

XML Schema

What is XML schema

XML schema is a language which is used for expressing constraint about XML documents.
There are so many schema languages which are used now a days for example Relax- NG and
XSD (XML schema definition).

An XML schema is used to define the structure of an XML document. It is like DTD but
provides more control on XML structure.

Checking Validation

An XML document is called "well-formed" if it contains the correct syntax. A well-formed


and valid XML document is one which have been validated against Schema.

Visit http://www.xmlvalidation.com to validate the XML file against schema or DTD.

XML Schema Example

Let's create a schema file.

employee.xsd

1. <?xml version="1.0"?>
2. <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
3. targetNamespace="http://www.javatpoint.com"
4. xmlns="http://www.javatpoint.com"
5. elementFormDefault="qualified">
6.
7. <xs:element name="employee">
8. <xs:complexType>
9. <xs:sequence>
10. <xs:element name="firstname" type="xs:string"/>
11. <xs:element name="lastname" type="xs:string"/>
12. <xs:element name="email" type="xs:string"/>
13. </xs:sequence>
14. </xs:complexType>
15. </xs:element>
16.
17. </xs:schema>
Let's see the xml file using XML schema or XSD file.

employee.xml

1. <?xml version="1.0"?>
2. <employee
3. xmlns="http://www.javatpoint.com"
4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5. xsi:schemaLocation="http://www.javatpoint.com employee.xsd">
6.
7. <firstname>vimal</firstname>
8. <lastname>jaiswal</lastname>
9. <email>vimal@javatpoint.com</email>
10. </employee>

Description of XML Schema

<xs:element name="employee"> : It defines the element name employee.

<xs:complexType> : It defines that the element 'employee' is complex type.

<xs:sequence> : It defines that the complex type is a sequence of elements.

<xs:element name="firstname" type="xs:string"/> : It defines that the element 'firstname'


is of string/text type.

<xs:element name="lastname" type="xs:string"/> : It defines that the element 'lastname'


is of string/text type.

<xs:element name="email" type="xs:string"/> : It defines that the element 'email' is of


string/text type.

XML Schema Data types

There are two types of data types in XML schema.

1. simpleType
2. complexType

simpleType

The simpleType allows you to have text-based elements. It contains less attributes, child
elements, and cannot be left empty.

complexType

The complexType allows you to hold multiple attributes and elements. It can contain
additional sub elements and can be left empty.
DTD vs XSD

There are many differences between DTD (Document Type Definition) and XSD (XML
Schema Definition). In short, DTD provides less control on XML structure whereas XSD
(XML schema) provides more control.

The important differences are given below:

No. DTD XSD

DTD stands for Document Type


1) XSD stands for XML Schema Definition.
Definition.

DTDs are derived


2) XSDs are written in XML.
from SGML syntax.

XSD supports datatypes for elements and


3) DTD doesn't support datatypes.
attributes.

4) DTD doesn't support namespace. XSD supports namespace.

DTD doesn't define order for child


5) XSD defines order for child elements.
elements.

6) DTD is not extensible. XSD is extensible.

XSD is simple to learn because you don't need to


7) DTD is not simple to learn.
learn new language.

DTD provides less control on XML


8) XSD provides more control on XML structure.
structure.

You might also like