0% found this document useful (0 votes)
40 views

ETCS-308 WebEngineering Notes

Uploaded by

anshugarg401
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

ETCS-308 WebEngineering Notes

Uploaded by

anshugarg401
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 234

Department of Computer Science & Engineering

Notes for B.Tech Students

WEB ENGINEERING
ETCS-308
Sixth Semester

Maharaja Surajmal Institute of Technology


C-4, Janak Puri, New Delhi
DISCLAIMER

COPYRIGHT IS NOT RESERVED BY AUTHORS. AUTHORS ARE NOT


RESPONSIBLE FOR ANY LEGAL ISSUES ARISING OUT OF ANY COPYRIGHT
DEMANDS AND/OR REPRINT ISSUES CONTAINED IN THIS MATERIALS.
THIS IS NOT MEANT FOR ANY COMMERCIAL PURPOSE & ONLY MEANT
FOR PERSONAL USE OF STUDENTS. READERS ARE REQUESTED TO SEND
ANY TYPING ERRORS CONTAINED, HEREIN.
WEB ENGINEERING

Paper Code: ETCS-308 L T/P C


Paper: Web Engineering 3 1 4

INSTRUCTIONS TO PAPER SETTERS: MAXIMUM MARKS: 75


1. Question No. 1 should be compulsory and cover the entire syllabus. This question should have objective
or short answer type questions. It should be of 25 marks.
2. Apart from Question No. 1, rest of the paper shall consist of four units as per the syllabus. Every unit should
have two questions. However, student may be asked to attempt only 1 question from each unit. Each question
should be of 12.5 marks.

Objective: This paper gives understanding of web designing to the students.

UNIT - I
History of the Internet, Basic internet protocols, World Wide Web (W3C), HTTP: Hypertext Transfer
Protocol.
Markup languages-XHTML: Introduction to HTML, basics of XTHML, HTML elements, HTML tags,
lists, tables, frames, forms, defining XHTML’s abstract syntax, defining HTML documents.
CSS style sheets: Introduction, CSS core syntax, text properties, CSS box model, normal flow box
layout, other properties like list, tables, DHTML, XML, XML documents & vocabulary, XML versions
& declarations, Introduction to WML.
[T1,T2][No. of hrs. 10]
UNIT – II
Client Side Programming: JAVA Scripts, basic syntax, variables & data-types, literals, functions,
objects, arrays, built-in objects, JAVA Script form programming, Intrinsic event handling, modifying
element style, document trees,
Server side programming – Java Servlets: Servlet architecture, life cycle, parameter data, sessions,
cookies, servlets capabilities, servlets & concurrency. Introduction to JSP, JSP Tags, JSP life cycle,
custom tags.
[T1,T2][No. of hrs. 12]
UNIT - III
Security Threats, Security risks of a site, Web attacks and their prevention, Web security model, Session
management, authentication, HTTPS and certificates, Application vulnerabilities and defenses.
Client-side security, Cookies security policy, HTTP security extensions, Plugins, extensions, and web
apps, Web user tracking.
Server-side security tools, Web Application Firewalls (WAFs) and Fuzzers.
` [T1,T2][No. of hrs.
10]
UNIT – IV
Introduction to Web 2.0 and Web 3.0, Concepts and Issues, Latest Trends in Web Technologies. Web
Security concerns. Applications of Web Engineering Technologies in distributed systems etc. Case
studies using different tools.
[T1,T2][No. of hrs. 12]
Text Books:
[T1] Web Technologies: A Computer Science Perspective, Jackson, Pearson Education India, 2007.
[T2] Web Engineering: A Practitioner's Approach by Roger S Pressman, David Lowe, TMH, 2008.

Reference Books:
[R1] Achyut Godbole,Atul Kahate, “Web Technologies”, McGraw-Hill Education, Third Edition.
[R2] Uttam K Roy, “Web Technologies”, Oxford University Press, 2012.
[R3] Chris Bates, "Web Programming", Wiley
[R4] Web Engineering by Gertel Keppel, Birgit Proll, Siegfried Reich, Werner R., John Wiley.
[R5] Thinking on the Web: Berner's LEE, Godel and Turing, John Wiley & Sons Inc.
Unit 1
1 History of the Internet
The Internet started in the 1960s as a way for government researchers to share information. Computers
in the '60s were large and immobile and in order to make use of information stored in any one computer,
one had to either travel to the site of the computer or have magnetic computer tapes sent through the
conventional postal system.

Another catalyst in the formation of the Internet was the heating up of the Cold War. The Soviet Union's
launch of the Sputnik satellite spurred the U.S. Defense Department to consider ways information could
still be disseminated even after a nuclear attack. This eventually led to the formation of the ARPANET
(Advanced Research Projects Agency Network), the network that ultimately evolved into what we now
know as the Internet. ARPANET was a great success but membership was limited to certain academic
and research organizations who had contracts with the Defense Department. In response to this, other
networks were created to provide information sharing.

January 1, 1983 is considered the official birthday of the Internet. Prior to this, the various computer
networks did not have a standard way to communicate with each other. A new communications protocol
was established called Transfer Control Protocol/Internetwork Protocol (TCP/IP). This allowed different
kinds of computers on different networks to "talk" to each other. ARPANET and the Defense Data
Network officially changed to the TCP/IP standard on January 1, 1983, hence the birth of the Internet.
All networks could now be connected by a universal language.

Fig. 1.1. UNIVAC Model

The image above is a scale model of the UNIVAC I (the name stood for Universal Automatic Computer)
which was delivered to the Census Bureau in 1951. It weighed some 16,000 pounds, used 5,000 vacuum
tubes, and could perform about 1,000 calculations per second. It was the first American commercial
computer, as well as the first computer designed for business use. (Business computers like the UNIVAC
processed data more slowly than the IAS-type machines, but were designed for fast input and output.)
The first few sales were to government agencies, the A.C. Nielsen Company, and the Prudential
Insurance Company. The first UNIVAC for business applications was installed at the General Electric
Appliance Division, to do payroll, in 1954. By 1957 Remington-Rand (which had purchased the Eckert-
Mauchly Computer Corporation in 1950) had sold forty-six machines.

In the world of technology, there are vast numbers of users' communicating with different devices in
different languages. That also includes many ways in which they transmit data along with the different
software they implement. So, communicating worldwide will not be possible if there were no fixed
'standards' that will govern the way user communicates for data as well as the way our devices treat those
data. Here we will be discussing these standard set of rules.

Types of Protocols

There are various types of protocols that support a major and compassionate role in communicating with
different devices across the network. These are:

1. Transmission Control Protocol (TCP)

2. Internet Protocol (IP)

3. User Datagram Protocol (UDP)

4. Post office Protocol (POP)

5. Simple mail transport Protocol (SMTP)

6. File Transfer Protocol (FTP)

7. Hyper Text Transfer Protocol (HTTP)

8. Hyper Text Transfer Protocol Secure (HTTPS)

9. Telnet

10. Gopher

Yes, we're talking about "protocols" which are set of rules that help in governing the way a particular
technology will function for communication. In other words, it can be said that the protocols are digital
languages implemented in the form of networking algorithms. There are different networks and network
protocols, user's use while surfing.
Table of Contents
# Types of Protocols
# Some Other Protocols
Let's discuss each of them briefly:
1. Transmission Control Protocol (TCP): TCP is a popular communication protocol which is
used for communicating over a network. It divides any message into series of packets that are
sent from source to destination and there it gets reassembled at the destination.

2. Internet Protocol (IP): IP is designed explicitly as addressing protocol. It is mostly used with
TCP. The IP addresses in packets help in routing them through different nodes in a network
until it reaches the destination system. TCP/IP is the most popular protocol connecting the
networks.

3. User Datagram Protocol (UDP): UDP is a substitute communication protocol to Transmission


Control Protocol implemented primarily for creating loss-tolerating and low-latency linking
between different applications.

4. Post office Protocol (POP): POP3 is designed for receiving incoming E-mails.

5. Simple mail transport Protocol (SMTP): SMTP is designed to send and distribute outgoing
E-Mail.

6. File Transfer Protocol (FTP): FTP allows users to transfer files from one machine to another.
Types of files may include program files, multimedia files, text files, and documents, etc.

7. Hyper Text Transfer Protocol (HTTP): HTTP is designed for transferring a hypertext among
two or more systems. HTML tags are used for creating links. These links may be in any form
like text or images. HTTP is designed on Client-server principles which allow a client system
for establishing a connection with the server machine for making a request. The server
acknowledges the request initiated by the client and responds accordingly.

8. Hyper Text Transfer Protocol Secure (HTTPS): HTTPS is abbreviated as Hyper Text
Transfer Protocol Secure is a standard protocol to secure the communication among two
computers one using the browser and other fetching data from web server. HTTP is used for
transferring data between the client browser (request) and the web server (response) in the
hypertext format, same in case of HTTPS except that the transferring of data is done in an
encrypted format. So it can be said that https thwart hackers from interpretation or
modification of data throughout the transfer of packets.

9. Telnet: Telnet is a set of rules designed for connecting one system with another. The connecting
process here is termed as remote login. The system which requests for connection is the local
computer, and the system which accepts the connection is the remote computer.

10. Gopher: Gopher is a collection of rules implemented for searching, retrieving as well as
displaying documents from isolated sites. Gopher also works on the client/server principle.

2 What is HTML?
 HTML stands for Hyper Text Markup Language
 HTML is the standard markup language for creating Web pages
 HTML describes the structure of a Web page
 HTML consists of a series of elements
 HTML elements tell the browser how to display the content
 HTML elements label pieces of content such as "this is a heading", "this is a paragraph", "this
is a link", etc.

A Simple HTML Document

Example

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

Example Explained

 The <!DOCTYPE html> declaration defines that this document is an HTML5 document
 The <html> element is the root element of an HTML page
 The <head> element contains meta information about the HTML page
 The <title> element specifies a title for the HTML page (which is shown in the browser's title
bar or in the page's tab)
 The <body> element defines the document's body, and is a container for all the visible
contents, such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
 The <h1> element defines a large heading
 The <p> element defines a paragraph

2 What is an HTML Element?

An HTML element is defined by a start tag, some content, and an end tag:

<tagname>Content goes here...</tagname>


Table 1.1 Types of tags in HTML

Start tag Element content End tag

<h1> My First Heading </h1>

<p> My first paragraph. </p>

<br> none none

The HTML element is everything from the start tag to the end tag:

<h1>My First Heading</h1>


<p>My first paragraph.</p>

Web Browsers

The purpose of a web browser (Chrome, Edge, Firefox, Safari) is to read HTML documents and
display them correctly. A browser does not display the HTML tags, but uses them to determine how to
display the document:

Fig.1.2. Example of a browser window


HTML Page Structure

Below is a visualization of an HTML page structure:

<html>
<head>
<title>Page title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

3 HTML History
Since the early days of the World Wide Web, there have been many versions of HTML:

Table 1.2. Versions of HTML

Year Version

1989 Tim Berners-Lee invented www

1991 Tim Berners-Lee invented HTML

1993 Dave Raggett drafted HTML+

1995 HTML Working Group defined HTML 2.0

1997 W3C Recommendation: HTML 3.2


1999 W3C Recommendation: HTML 4.01

2000 W3C Recommendation: XHTML 1.0

2008 WHATWG HTML5 First Public Draft

2012 WHATWG HTML5 Living Standard

2014 W3C Recommendation: HTML5

2016 W3C Candidate Recommendation: HTML 5.1

2017 W3C Recommendation: HTML5.1 2nd Edition

2017 W3C Recommendation: HTML5.2

HTML Elements

The HTML element is everything from the start tag to the end tag:

<tagname>Content goes here...</tagname>

Examples of some HTML elements:

<h1>My First Heading</h1>


<p>My first paragraph.</p>
Table 1.3 Example of Tags

Start tag Element content End tag

<h1> My First Heading </h1>

<p> My first paragraph. </p>

<br> none none

Nested HTML Elements

HTML elements can be nested (this means that elements can contain other elements).

All HTML documents consist of nested HTML elements.

The following example contains four HTML elements (<html>, <body>, <h1> and <p>):

3.1.1 Example

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

3.1.2 Example Explained

The <html> element is the root element and it defines the whole HTML document.
It has a start tag <html> and an end tag </html>.

Then, inside the <html> element there is a <body> element:

<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>

The <body> element defines the document's body.

It has a start tag <body> and an end tag </body>.

Then, inside the <body> element there are two other elements: <h1> and <p>:

<h1>My First Heading</h1>


<p>My first paragraph.</p>

The <h1> element defines a heading.

It has a start tag <h1> and an end tag </h1>:

<h1>My First Heading</h1>

The <p> element defines a paragraph.

It has a start tag <p> and an end tag </p>:

<p>My first paragraph.</p>

Never Skip the End Tag

Some HTML elements will display correctly, even if you forget the end tag:

3.1.3 Example

<html>
<body>

<p>This is a paragraph
<p>This is a paragraph

</body>
</html>
Empty HTML Elements

HTML elements with no content are called empty elements.

The <br> tag defines a line break, and is an empty element without a closing tag:

3.1.4 Example

<p>This is a <br> paragraph with a line break.</p>

HTML is Not Case Sensitive

HTML tags are not case sensitive: <P> means the same as <p>.

The HTML standard does not require lowercase tags, but W3C recommends lowercase in HTML,
and demands lowercase for stricter document types like XHTML

HTML Tag Reference

W3Schools' tag reference contains additional information about these tags and their attributes.

Table 1.3 Tag description

Tag Description

<html> Defines the root of an HTML document

<body> Defines the document's body

<h1> to <h6> Defines HTML headings


4 HTML Lists
HTML lists allow web developers to group a set of related items in lists.

Example

An unordered HTML list:

 Item
 Item
 Item
 Item

An ordered HTML list:

1. First item
2. Second item
3. Third item
4. Fourth item

Unordered HTML List

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

The list items will be marked with bullets (small black circles) by default:

Example

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

Ordered HTML List

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default:

Example

<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

HTML Description Lists

HTML also supports description lists.

A description list is a list of terms, with a description of each term.

The <dl> tag defines the description list, the <dt> tag defines the term (name), and the <dd> tag
describes each term:

Example

<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>

<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

5 HTML Tables
HTML tables allow web developers to arrange data into rows and columns.

Table 1.4. Example of table in HTML

5.1.1 Example

Company Contact Country


Alfreds Futterkiste Maria Anders Germany

Centro comercial Moctezuma Francisco Chang Mexico

Ernst Handel Roland Mendel Austria

Island Trading Helen Bennett UK

Laughing Bacchus Winecellars Yoshi Tannamuri Canada

Magazzini Alimentari Riuniti Giovanni Rovelli Italy

Define an HTML Table

A table in HTML consists of table cells inside rows and columns

5.1.2 Example

A simple HTML table:

<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
Table Cells

Each table cell is defined by a <td> and a </td> tag.

td stands for table data.

Everything between <td> and </td> are the content of the table cell.

5.1.3 Example

<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>

Table Rows

Each table row starts with a <tr> and end with a </tr> tag.

tr stands for table row.

5.1.4 Example

<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

You can have as many rows as you like in a table, just make sure that the number of cells are the same
in each row.
Table Headers

Sometimes you want your cells to be headers, in those cases use the <th> tag instead of the <td> tag:
5.1.5 Example
Let the first row be table headers:
<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

By default, the text in <th> elements are bold and centered, but you can change that with CSS.

HTML Table Tags

Table 1.5 Example of table tags


Tag Description

<table> Defines a table

<th> Defines a header cell in a table

<tr> Defines a row in a table

<td> Defines a cell in a table

<caption> Defines a table caption

<colgroup> Specifies a group of one or more columns in a table for formatting

<col> Specifies column properties for each column within a <colgroup> element

<thead> Groups the header content in a table

<tbody> Groups the body content in a table

<tfoot> Groups the footer content in a table


6 HTML Iframes
An HTML iframe is used to display a web page within a web page.

HTML Iframe Syntax

The HTML <iframe> tag specifies an inline frame.

An inline frame is used to embed another document within the current HTML document.

6.1.1 Syntax

<iframe src="url" title="description"></iframe>

Tip: It is a good practice to always include a title attribute for the <iframe>. This is used by screen
readers to read out what the content of the iframe is.

Iframe - Set Height and Width

Use the height and width attributes to specify the size of the iframe.

The height and width are specified in pixels by default:

6.1.2 Example

<iframe src="demo_iframe.htm" height="200" width="300" title="Iframe Example"></iframe>

Or you can add the style attribute and use the CSS height and width properties:

6.1.3 Example

<iframe src="demo_iframe.htm" style="height:200px;width:300px;" title="Iframe


Example"></iframe>

Iframe - Remove the Border

By default, an iframe has a border around it.

To remove the border, add the style attribute and use the CSS border property:

6.1.4 Example

<iframe src="demo_iframe.htm" style="border:none;" title="Iframe Example"></iframe>

With CSS, you can also change the size, style and color of the iframe's border:
6.1.5 Example

<iframe src="demo_iframe.htm" style="border:2px solid red;" title="Iframe Example"></iframe>

Iframe - Target for a Link

An iframe can be used as the target frame for a link.

The target attribute of the link must refer to the name attribute of the iframe:

6.1.6 Example

<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe Example"></iframe>

<p><a href="https://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>

HTML iframe Tag

Tag Description

<iframe> Defines an inline frame

7 HTML Forms
An HTML form is used to collect user input. The user input is most often sent to a server for
processing.

7.1.1 Example

First name:

Last name:

The <form> Element

The HTML <form> element is used to create an HTML form for user input:
<form>
.
form elements
.
</form>

The <form> element is a container for different types of input elements, such as: text fields,
checkboxes, radio buttons, submit buttons, etc.

The <input> Element

The HTML <input> element is the most used form element.

An <input> element can be displayed in many ways, depending on the type attribute.

Table1.6. Here are some examples:

Type Description

<input type="text"> Displays a single-line text input field

<input type="radio"> Displays a radio button (for selecting one of many


choices)

<input type="checkbox"> Displays a checkbox (for selecting zero or more of


many choices)

<input type="submit"> Displays a submit button (for submitting the form)

<input type="button"> Displays a clickable button

All the different input types are covered in this chapter: HTML Input Types.
Text Fields

The <input type="text"> defines a single-line input field for text input.

7.1.2 Example

A form with input fields for text:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>

This is how the HTML code above will be displayed in a browser:

First name:

Last name:

The <label> Element

Notice the use of the <label> element in the example above.

The <label> tag defines a label for many form elements.

The <label> element is useful for screen-reader users, because the screen-reader will read out loud the
label when the user focus on the input element.

The <label> element also help users who have difficulty clicking on very small regions (such as radio
buttons or checkboxes) - because when the user clicks the text within the <label> element, it toggles
the radio button/checkbox.

The for attribute of the <label> tag should be equal to the id attribute of the <input> element to bind
them together.

Radio Buttons

The <input type="radio"> defines a radio button.

Radio buttons let a user select ONE of a limited number of choices.

7.1.3 Example
A form with radio buttons:

<p>Choose your favorite Web language:</p>

<form>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
</form>

This is how the HTML code above will be displayed in a browser:

Choose your favorite Web language:

HTML
CSS
JavaScript

Checkboxes

The <input type="checkbox"> defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of choices.

7.1.4 Example

A form with checkboxes:

<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>

This is how the HTML code above will be displayed in a browser:


I have a bike
I have a car
I have a boat

The Submit Button

The <input type="submit"> defines a button for submitting the form data to a form-handler.

The form-handler is typically a file on the server with a script for processing input data.

The form-handler is specified in the form's action attribute.

7.1.5 Example

A form with a submit button:

<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>

This is how the HTML code above will be displayed in a browser:

First name:

Last name:

The Name Attribute for <input>

Notice that each input field must have a name attribute to be submitted.

If the name attribute is omitted, the value of the input field will not be sent at all.

7.1.6 Example

This example will not submit the value of the "First name" input field:

<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" value="John"><br><br>
<input type="submit" value="Submit">
</form>

8 What is XHTML

XHTML stands for EXtensible HyperText Markup Language. It is a cross between HTML and XML
language.

XHTML is almost identical to HTML but it is stricter than HTML. XHTML is HTML defined as an
XML application. It is supported by all major browsers.

Although XHTML is almost the same as HTML but It is more important to create your code correctly,
because XHTML is stricter than HTML in syntax and case sensitivity. XHTML documents are well-
formed and parsed using standard XML parsers, unlike HTML, which requires a lenient HTML-specific
parser.

History

XHTML 1.0 became a World Wide Web Consortium (W3C) Recommendation on January 26, 2000.
XHTML 1.1 became a W3C Recommendation on May 31, 2001. The standard known as XHTML5 is
being developed as an XML adaptation of the HTML5 specification.

Why use XHTML

XHTML was developed to make HTML more extensible and increase interoperability with other data
formats. There are two main reasons behind the creation of XHTML:

o It creates a stricter standard for making web pages, reducing incompatibilities between
browsers. So it is compatible for all major browsers.

o It creates a standard that can be used on a variety of different devices without changes.

Let's take an example to understand it.

HTML is mainly used to create web pages but we can see that many pages on the internet contain "bad"
HTML (not follow the HTML rule).

This HTML code works fine in most browsers (even if it does not follow the HTML rules).

For example:

1. <html>
2. <head>
3. <title>This is an example of bad HTML</title>
4. <body>
5. <h1>Bad HTML
6. <p>This is a paragraph
7. </body>

The above HTML code doesn't follow the HTML rule although it runs. Now a day, there are different
browser technologies. Some browsers run on computers, and some browsers run on mobile phones or
other small devices. The main issue with the bad HTML is that it can't be interpreted by smaller devices.

So, XHTML is introduced to combine the strengths of HTML and XML.

XHTML is HTML redesigned as XML. It helps you to create better formatted code on your site.

9 HTML vs XHTML
There are some changes in XHTML as compared to HTML. These changes can be categorized in three
parts:

Changes in Document Structure

o All documents must have a DOCTYPE.


o The xmlns attribute in <html> is mandatory and must specify the xml namespace for the
document.
o <html>, <head>, <title>, and <body> are mandatory with their respective closing tags.

Changes in XHTML Tags

o All XHTML tags must be in lower case.


o All XHTML tags must be closed.
o All XHTML tags must be properly nested.
o The XHTML documents must have one root element.

Changes in XHTML Tags

o All XHTML attributes must be added properly.


o All XHTML attributes must be in lower case.
o The name attribute has changed.
o XHTML attributes cannot be shortened.
o XHTML attribute values must be quoted.

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


2. <html xmlns="http://www.w3.org/1999/xhtml">
3. <head>
4. <title>Title of document</title>
5. </head>
6. <body>
7. some content
8. </body>
9. </html>

10 XHTML Syntax
XHTML syntax is very similar to HTML syntax and all the valid HTML elements are also valid in
XHTML. But XHTML is case sensitive so you have to pay a bit extra attention while writing an XHTML
document to make your HTML document compliant to XHTML.

You must remember the following important points while writing a new XHTML document or
converting existing HTML document into XHTML document:

o All documents must have a DOCTYPE.

o All tags must be in lower case.

o All documents must be properly formed.

o All tags must be closed.

o All attributes must be added properly.

o The name attribute has changed.

o Attributes cannot be shortened.

o All tags must be properly nested.

DOCTYPE Declaration

All XHTML documents must contain a DOCTYPE declaration at the start. There are three types of
DOCTYPE declarations:

o Strict

o Transitional

o Frameset

Here is an example of using DOCTYPE.

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

Tags must be in lower case

XHTML is case-sensitive markup language. So, all the XHTML tags and attributes must be written in
lower case.

1. <!-- Invalid in XHTML -->


2. <A Href="/xhtml/xhtml_tutorial.html">XHTML Tutorial</A>
3. <!-- Valid in XHTML -->
4. <a href="/xhtml/xhtml_tutorial.html">XHTML Tutorial</a>

Closing Tags are mandatory

An XHTML must have an equivalent closing tag. Even empty elements should also have closing tags.
Let's see an example:

1. <!-- Invalid in XHTML -->


2. <p>This paragraph is not written according to XHTML syntax.
3. <!-- Invalid in XHTML -->
4. <img src="/images/xhtml.gif" >
5. <!-- Valid in XHTML -->
6. <p>This paragraph is not written according to XHTML syntax.</p>
7. <!-- Valid in XHTML-->
8. <img src="/images/xhtml.gif" />

Attribute Quotes

All the XHTML attribute's values must be quoted. Otherwise, your XHTML document is assumed as an
invalid document.

See this example:

1. <!-- Invalid in XHTML -->


2. <img src="/images/xhtml.gif" width=250 height=50 />
3. <!-- Valid in XHTML -->
4. <img src="/images/xhtml.gif" width="250" height="50" />

Attribute Minimization

XHTML doesn't allow you to minimize attributes. You have to explicitly state the attribute and its value.

See this example:

1. <!--Invalid in XHTML -->


2. <option selected>
3. <!-- valid in XHTML-->
4. <option selected="selected">
Table 1.7.A list of minimized attributes in HTML and the way you need to write them in XHTML.

HTML Style XHTML Style

compact compact="compact"

checked checked="checked"

declare declare="declare"

readonly readonly="readonly"

disabled disabled="disabled"

selected selected="selected"

defer defer="defer"

ismap ismap="ismap"

nohref nohref="nohref"

noshade noshade="noshade"

nowrap nowrap="nowrap"

multiple multiple="multiple"

noresize noresize="noresize"

The id Attribute

The id attribute is used to replace the name attribute. Instead of using name = "name", XHTML prefers
to use id = "id".

See this example:

1. <!-- Invalid in XHTML -->


2. <img src="/images/xhtml.gif" name="xhtml_logo" />
3. <!-- Valid in XHTML -->
4. <img src="/images/xhtml.gif" id="xhtml_logo" />

The language attribute


In XHTML, the language attribute of script tag is deprecated so you have to use type attribute instead of
this.

See this example:


1. <!-- Invalid in XHTML -->
2. <script language="JavaScript" type="text/JavaScript">
3. document.write("Hello XHTML!");
4. </script>
5. <!-- Valid in XHTML -->
6. <script type="text/JavaScript">
7. document.write("Hello XHTML!");
8. </script>

Nested Tags

XHTML tags must be nested properly. Otherwise your document is assumed as an incorrect XHTML
document.

See this example:

1. <!-- Invalid in XHTML -->


2. <b><i> This text is bold and italic</b></i>
3. <!-- Valid in XHTML -->
4. <b><i> This text is bold and italic</i></b>

Element Prohibitions

The following elements are not allowed to have any other element inside them. This is applicable for all
the descending elements.

Table 1.8. Elements prohibitions

Element Prohibition

<a> It must not contain other <a> elements.

<pre> It must not contain the <img>, <object>, <big>, <small>, <sub>, or <sup> elements.
<button> It must not contain the <input>, <select>, <textarea>, <label>, <button>, <form>,
<fieldset>, <iframe> or <isindex> elements.

<label> It must not contain other <label> elements.

<form> It must not contain other <form> elements.

11 XHTML Events
When you visit a website, you do things like click on text, images and hyperlinks, hover-over things, etc.
These are examples of what JavaScript calls events.

We can write our event handlers in JavaScript or VBScript and can specify these event handlers as a
value of event tag attribute. The XHTML 1.0 has a similar set of events which is available in HTML 4.01
specification.

The <body> and <frameset> Level Events

There are only two attributes which are used to trigger any JavaScript or VBScript code, when any event
occurs at document level.

Table 1.9. Attributes descriptions

Attribute Value Description

onload Script Script runs when a XHTML document loads.

onunload Script Script runs when a XHTML document unloads.

The <form> Level Events

There are six attributes which are triggered when any event occurs at form level.

Table 1.10 Attributes descriptions

Attribute Value Description

onchange Script It is executed when the element changes.

onsubmit Script It is executed when the form is submitted.


onreset Script It is executed when the form is reset.

onselect Script It is executed when the element is selected.

onblur Script It is executed when the element loses focus.

onfocus Script It is executed when the element gets focus.

Keyboard Events

There are three events which are generated by keyboard. The keyboard events are not valid in base, bdo,
br, frame, frameset, head, html, iframe, meta, param, script, style, and title elements.

Table 1.11. Attributes descriptions

Attribute Value Description

onkeydown Script This is executed when the user


press the keyboard button.

onkeypress Script This is executed when the user press and release the keyboard button.

onkeyup Script This is executed when the user release the keyboard button.

Mouse Events

There are some mouse generated events which executes when it comes in contact with any HTML tag.
These events are not valid in base, bdo, br, frame, frameset, head, html, iframe, meta, param, script, style,
and title elements.

Table 1.12. Attributes descriptions

Attribute Value Description

onclick Script It is executed on a mouse click.

ondblclick Script It is executed on a mouse double-click.

onmousedown Script It is executed when mouse button is pressed.


onmousemove Script It is executed when mouse pointer moves.

onmouseout Script It is executed when mouse pointer moves out of an element.

onmouseover Script It is executed when mouse pointer moves over an element.

onmouseup Script It is executed when mouse button is released.

12 XHTML Doctypes
There are three types of Document Type Definitions (DTDs). The easiest and most commonly used is
the XHTML Transitional document.

A list of the XHTML Doctypes:

o Strict

o Transitional

o Frameset

You should be very careful while writing XHTML document because the few XHTML elements and
attributes, which are available in one DTD but not available in another DTD. So, you should select your
XHTML elements or attribute carefully.

XHTML 1.0 Strict DTD

It is recommended to use when you want to use Cascading Style Sheet (CSS) strictly and avoiding to
write most of the XHTML attributes.

Add the following DTD at the top of your XHTML document.

Syntax:

1. <!DOCTYPE html PUBLIC "-


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

XHTML 1.0 Transitional DTD

It is recommended to use when you want to use many XHTML attributes as well as few Cascading Style
Sheet (CSS) properties.

Add the following DTD at the top of your XHTML document.


Syntax:

1. <!DOCTYPE html PUBLIC "-


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

XHTML 1.0 Frameset DTD

It is recommended to use when you want to use HTML Frames to partition the browser window into two
or more frames.
Add the following DTD at the top of your XHTML document.
Syntax:
1. <!DOCTYPE html PUBLIC "-
//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
frameset.dtd">
Note: You can use anyone of the DTD to write your XHTML document; if it is a valid XHTML
document, then your document is considered as a good quality document.
13 XHTML Attributes
There are some XHTML attributes which are standard and associated to all XHTML tags. The XHTML
attributes can be divided in 3 types:
o Core Attributes
o Language Attributes
o Microsoft Proprietary Attributes
Core Attributes
The core attribute is not valid in base, head, html, meta, param, script, style, and title elements
Table 1.13. Attributes descriptions

Attribute Value Description

class class_rule or style_rule It specifies the class of the element.

id id_name It specifies a unique id for the element.

style style_definition It specifies an inline style definition.

title tooltip_text It specifies a text to display in a mouse tip.

Language Attributes
The lang attribute specifies the language which is used for the enclosed content. It uses the ISO standard
language abbreviations like fr for French, en for English, and so on. The language attribute is not valid
in base, br, frame, frameset, hr, iframe, param, and script elements.
Table 1.14. Attributes descriptions

Attribute Value Description

dir ltr | rtl It is used to set the text direction.

lang language_code It is used to set the language code.


Microsoft Proprietary Attributes
There are some proprietary attributes introduced by Microsoft with the Internet Explorer 4 and higher versions.

Table 1.15. Attributes descriptions

Attribute Value Description

accesskey character It is used to set a keyboard shortcut to access an element.

language String This attribute is specifies the scripting language which is used with the
script bound to the element, typically through an event handler attribute.
Its possible values might include JavaScript, jScript, VBS, and VBScript.

tabindex Number It is used to set the tab order of an element.

contenteditable Boolean It allows users to edit content rendered in internet explorer 5.5 or greater.
Its possible values are true or false.

disabled Boolean The disabled attribute makes the element appear faded and will not
respond to user input. Its possible values are true or false.

hidefocus On or Off This proprietary attribute, introduced with internet explorer 5.5, hides
focus on an element's content. It specifies that focus must be applied to
the element using the tabindex attribute.

unselectable On or Off It is used to prevent content displayed in internet


explorer 5.5 from being selected.

14 Cascading Style Sheets


Cascading Style Sheets, CSS saves a lot of work. It can control the layout of multiple web pages all at
once.

What is CSS?

Cascading Style Sheets (CSS) is used to format the layout of a webpage.

With CSS, we can control the colour, font, and the size of text, the spacing between elements, how
elements are positioned and laid out, what background images or background colours are to be used,
different displays for different devices and screen sizes, and much more.

The word cascading means that a parent element will also apply to all children elements within the
parents. So, if you set the colour of the body text to “blue”, all headings, paragraphs and other text
elements within the body will get the same colour (unless you specify something else).

CSS Syntax

A CSS rule consists of a selector and a declaration block.


Figure.1.2 CSS declaration block

The selector points to the HTML element you want to style.


The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a CSS property name and a value, separated by a colon.
Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly
braces.
Table 1.16 Example of “p” selector
Example Output
<!DOCTYPE html> Hello World!
<html> These paragraphs are styled with CSS.
<head>
<style>
p{
color: red;
text-align: center;
}
</style>
</head>
<body>

<p>Hello World!</p>
<p>These paragraphs are styled with
CSS.</p>

</body>
</html>
Example Explained

 “p” is a selector in CSS (it points to the HTML element you want to style: <p>).
 colour is a property, and red is the property value
 text-align is a property, and center is the property value

CSS Selectors

CSS selectors are used to "find" (or select) the HTML elements you want to style.

We can divide CSS selectors into five categories:

 Simple selectors (select elements based on name, id, class)


 Combinator selectors (select elements based on a specific relationship between them)
 Pseudo-class selectors (select elements based on a certain state)
 Pseudo-elements selectors (select and style a part of an element)
 Attribute selectors (select elements based on an attribute or attribute value)

The CSS element Selector

The element selector selects HTML elements based on the element name.

The CSS id Selector


The id selector uses the id attribute of an HTML element to select a specific element.

The id of an element is unique within a page, so the id selector is used to select one unique element!

To select an element with a specific id, write a hash (#) character, followed by the id of the element.

Table 1.17 Example of id selector in CSS

Example Output
<html> Hello World!
<head> This paragraph is not affected by the style.
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>

<p id="para1">Hello World!</p>


<p>This paragraph is not affected by the
style.</p>

</body>
</html>
The CSS class Selector
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class name.
CSS can be added to HTML documents in 3 ways:
 Inline - by using the style attribute inside HTML elements
 Internal - by using a <style> element in the <head> section
 External - by using a <link> element to link to an external CSS file
The most common way to add CSS, is to keep the styles in external CSS files.
Inline CSS
An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
The following example sets the text color of the <h1> element to blue, and the text color of
the <p> element to red:
Table 1.18 Example of inline CSS

Example Output
<!DOCTYPE html> A Blue Heading
<html> A red paragraph.
<body>
<h1 style="color: blue;">A Blue
Heading</h1>
<p style="color: red;">A red paragraph.</p>
</body>
</html>
Internal CSS
An internal CSS is used to define a style for a single HTML page.
An internal CSS is defined in the <head> section of an HTML page, within a <style> element.
The following example sets the text color of ALL the <h1> elements (on that page) to blue, and the text
color of ALL the <p> elements to red. In addition, the page will be displayed with a "powderblue"
background color:
Table 1.19 Example of Internal CSS
Example Output
<!DOCTYPE html> This is a heading
<html> This is a paragraph.
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

External CSS
An external style sheet is used to define the style for many HTML pages.
To use an external style sheet, add a link to it in the <head> section of each HTML page:
Table 1.20.Example of External CSS
Example Output
<!DOCTYPE html> This is a heading
<html> This is a paragraph.
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
The external style sheet can be written in any text editor. The file must not contain any HTML code, and
must be saved with a .css extension for example:"styles.css":
With an external style sheet, you can change the look of the entire web site, by changing one file.
CSS Colors, Fonts and Sizes
The CSS color property defines the text color to be used.
The CSS font-family property defines the font to be used.
The CSS font-size property defines the text size to be used.
Table 1.21.Example of CSS properties.
Example Output
<!DOCTYPE html> This is a heading
<html> This is a paragraph.
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;

}
p {
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

CSS Border
The CSS border property defines a border around an HTML element.
Use of CSS border property:
p { border: 2px solid powderblue; }

Table 1.22.Example of border in CSS


Example Output
<!DOCTYPE html> This is a heading
<html> This is a paragraph.
<head> This is a paragraph.
<style> This is a paragraph.
p{
border: 2px solid powderblue;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>

</body>
</html>

CSS Padding
The CSS padding property defines a padding (space) between the text and the border.
Example: Use of CSS border and padding properties:
p{
border:2px solid powderblue;
padding: 30px;
}

CSS Margin
The CSS margin property defines a margin (space) outside the border.
Example: Use of CSS border and margin properties:
p{
border:2px solid powderblue;
margin: 50px;
}
Link to External CSS
External style sheets can be referenced with a full URL or with a path relative to the current web page.
Example
This example uses a full URL to link to a style sheet:
<link rel="stylesheet" href="https://www.w3schools.com/html/styles.css">
CSS Solved a Big Problem
HTML was NEVER intended to contain tags for formatting a web page!
HTML was created to describe the content of a web page, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it started a
nightmare for web developers. Development of large websites, where fonts and color information were
added to every single page, became a long and expensive process. To solve this problem, the World Wide
Web Consortium (W3C) created CSS. CSS removed the style formatting from the HTML page!
Cascading Order
What style will be used when there is more than one style specified for an HTML element?
All the styles in a page will "cascade" into a new "virtual" style sheet by the following rules, where
number one has the highest priority:
1. Inline style (inside an HTML element)
2. External and internal style sheets (in the head section)
3. Browser default
So, an inline style has the highest priority, and will override external and internal styles and browser
defaults.
CSS Comments
Comments are used to explain the code, and may help when you edit the source code at a later
date.Comments are ignored by browsers. A CSS comment is placed inside the <style> element, and
starts with /* and ends with */:
/* This is a single-line comment */
p{
color: red;
}
The CSS Box Model
In CSS, the term "box model" is used when talking about design and layout. The CSS box model is
essentially a box that wraps around every HTML element. It consists of: margins, borders, padding,
and the actual content. The image below illustrates the box model:

Fig.1.3: Description of CSS Box model


Explanation of the different parts:
 Content - The content of the box, where text and images appear
 Padding - Clears an area around the content. The padding is transparent
 Border - A border that goes around the padding and content
 Margin - Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space between elements.
Example
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: lightgrey;
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
</style>
</head>
<body>
<h2>Demonstrating the Box Model</h2>
<p>The CSS box model is essentially a box that wraps around every HTML element. It consists of:
borders, padding, margins, and the actual content.</p>
<div>This text is the content of the box. We have added a 50px padding, 20px margin and a 15px green
border. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat
nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit
anim id est laborum.</div>
</body>
</html>

Fig 1.4: Output of box model


Width and Height of an Element
In order to set the width and height of an element correctly in all browsers, you need to know how the
box model works.
Example
This <div> element will have a total width of 350px:
div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
Table 1.23. Example of setting height and weight of figure using CSS
Example Output
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
</style>
</head>
<body>

<h2>Calculate the total width:</h2>

<img src="klematis4_big.jpg"
width="350" height="263"
alt="Klematis">
<div>The picture above is 350px wide.
The total width of this element is also
350px.</div>

</body>
</html>
Here is the calculation:
320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px
The total width of an element should be calculated like this:
Total element width = width + left padding + right padding + left border + right border + left margin +
right margin
The total height of an element should be calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border + top
margin + bottom margin
Text Color
The color property is used to set the color of the text. The color is specified by:
 a color name - like "red"
 a HEX value - like "#ff0000"
 an RGB value - like "rgb(255,0,0)"
Text Color and Background Color
In this example, we define both the background-color property and the color property:
Example
body {
background-color: lightgrey;
color: blue;
}

h1 {
background-color: black;
color: white;
}

div {
background-color: blue;
color: white;
}
Text Alignment
The text-align property is used to set the horizontal alignment of a text. A text can be left or right
aligned, centered, or justified.
The following example shows center aligned, and left and right aligned text (left alignment is default if
text direction is left-to-right, and right alignment is default if text direction is right-to-left):
Example
h1 {
text-align: center;
}

h2 {
text-align: left;
}

h3 {
text-align: right;
}

15 CSS Lists
There are 2 types of lists in CSS: Unordered and ordered.
Unordered Lists:
o Coffee
o Tea
o Coca Cola
 Coffee
 Tea
 Coca Cola
Ordered Lists:
1. Coffee
2. Tea
3. Coca Cola
I. Coffee
II. Tea
III. Coca Cola
HTML Lists and CSS List Properties
In HTML, there are two main types of lists:
 unordered lists (<ul>) - the list items are marked with bullets
 ordered lists (<ol>) - the list items are marked with numbers or letters
The CSS list properties allow you to:
 Set different list item markers for ordered lists
 Set different list item markers for unordered lists
 Set an image as the list item marker
 Add background colors to lists and list items
Different List Item Markers
The list-style-type property specifies the type of list item marker.
The following example shows some of the available list item markers:
Table 1.24. Example of lists in CSS
Example Output
<!DOCTYPE html> The list-
<html> style-type
<head> Property
<style> Example of unordered lists:
ul.a { o Coffee
list-style-type: circle; o Tea
} o Coca Cola
 Coffee
ul.b {  Tea
list-style-type: square;  Coca Cola
} Example of ordered lists:
I. Coffee
ol.c { II. Tea
list-style-type: upper-roman; III. Coca Cola
} a. Coffee
b. Tea
ol.d { c. Coca Cola
list-style-type: lower-alpha;
}
</style>
</head>
<body>

<h2>The list-style-type Property</h2>

<p>Example of unordered lists:</p>


<ul class="a">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>

<ul class="b">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>

<p>Example of ordered lists:</p>


<ol class="c">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
<ol class="d">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>

</body>
</html>

An Image as a List Item Marker


The list-style-image property specifies an image as the list item marker:
ul {
list-style-image: url ('sqpurple.gif');
}
Position of the List Item Markers
The list-style-position property specifies the position of the list-item markers (bullet points).
"list-style-position: outside;" means that the bullet points will be outside the list item. The start of each
line of a list item will be aligned vertically. This is default:

"list-style-position: inside;" means that the bullet points will be inside the list item. As it is part of the
list item, it will be part of the text and push the text at the start:
 Coffee - A brewed drink prepared from roasted coffee beans...
 Tea
 Coca-cola

16 Table Borders
To specify table borders in CSS, use the border property.
The example below specifies a black border for <table>, <th>, and <td> elements:

Example
table, th, td {
border: 1px solid black;
}

Full-Width Table
The table above might seem small in some cases. If you need a table that should span the entire screen
(full-width), add width: 100% to the <table> element:

table {
width: 100%;
}

Collapse Table Borders

The border-collapse property sets whether the table borders should be collapsed into a single
border:

table {
border-collapse: collapse;
}

Table Width and Height

The width and height of a table are defined by the width and height properties.

The example below sets the width of the table to 100%, and the height of the <th> elements to 70px:

table {
width: 100%;
}

th {
height: 70px;
}

Horizontal Alignment

The text-align property sets the horizontal alignment (like left, right, or center) of the content in
<th> or <td>.

By default, the content of <th> elements are center-aligned and the content of <td> elements are left-
aligned.

To center-align the content of <td> elements as well, use text-align: center:

td {
text-align: center;
}
Table Padding

To control the space between the border and the content in a table, use the padding property on <td> and
<th> elements:

Table 1.25. Example of table padding in CSS


Example Output
<!DOCTYPE html>
<html>
<head>
<style>
table, td, th {
border: 1px solid #ddd;
text-align: left;
}

table {
border-collapse: collapse;
width: 100%;
}

th, td {
padding: 15px;
}
</style>
</head>
<body>

<h2>The padding Property</h2>

<p>This property adds space between


the border and the content in a table.</p>

<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Savings</th>
</tr>
<tr>
<td>Peter</td>
<td>Griffin</td>
<td>$100</td>
</tr>
<tr>
<td>Lois</td>
<td>Griffin</td>
<td>$150</td>
</tr>
<tr>
<td>Joe</td>
<td>Swanson</td>
<td>$300</td>
</tr>
<tr>
<td>Cleveland</td>
<td>Brown</td>
<td>$250</td>
</tr>
</table>

</body>
</html>
Horizontal Dividers

First Name Last Name Savings

Peter Griffin $100

Lois Griffin $150

Joe Swanson $300

Add the border-bottom property to <th> and <td> for horizontal dividers:
th, td {
border-bottom: 1px solid #ddd;
}
Hoverable Table
Use the: hover selector on <tr> to highlight table rows on mouse over

tr:hover {background-color: yellow;}

Striped Tables
For zebra-striped tables, use the nth-child () selector and add a background-color to all
even (or odd) table rows:
tr:nth-child(even) {background-color: #f2f2f2;}

Table Color
The example below specifies the background color and text color of <th> elements:
th {
background-color: #04AA6D;
color: white;
}
Output

17 Introduction to XML
XML is a software- and hardware-independent tool for storing and transporting data.
What is XML?
 XML stands for eXtensible Markup Language
 XML is a markup language much like HTML
 XML was designed to store and transport data
 XML was designed to be self-descriptive
 XML is a W3C Recommendation
XML Does Not DO Anything

Maybe it is a little hard to understand, but XML does not DO anything.

This note is a note to Tove from Jani, stored as XML:

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The XML above is quite self-descriptive:

 It has sender information.


 It has receiver information
 It has a heading
 It has a message body.

But still, the XML above does not DO anything. XML is just information wrapped in tags.

Someone must write a piece of software to send, receive, store, or display it:
Fig.1.6. Example of XML document

Difference between XML and HTML

XML and HTML were designed with different goals:

 XML was designed to carry data - with focus on what data is


 HTML was designed to display data - with focus on how data looks
 XML tags are not predefined like HTML tags are

 XML Does Not Use Predefined Tags


 The XML language has no predefined tags.
 The tags in the example above (like <to> and <from>) are not defined in any XML standard.
These tags are "invented" by the author of the XML document.
 HTML works with predefined tags like <p>, <h1>, <table>, etc.
 With XML, the author must define both the tags and the document structure.
 XML is Extensible
 Most XML applications will work as expected even if new data is added (or removed).
 Imagine an application designed to display the original version of note.xml (<to> <from>
<heading> <body>).
 Then imagine a newer version of note.xml with added <date> and <hour> elements, and a
removed <heading>.
 The way XML is constructed, older version of the application can still work:
 <note>
<date>2015-09-01</date>
<hour>08:30</hour>
<to>Tove</to>
<from>Jani</from>
<body>Don't forget me this weekend!</body>
</note>
XML Simplifies Things

 It simplifies data sharing


 It simplifies data transport
 It simplifies platform changes
 It simplifies data availability

Many computer systems contain data in incompatible formats. Exchanging data between incompatible
systems (or upgraded systems) is a time-consuming task for web developers. Large amounts of data must
be converted, and incompatible data is often lost.

XML stores data in plain text format. This provides a software- and hardware-independent way of
storing, transporting, and sharing data.

XML also makes it easier to expand or upgrade to new operating systems, new applications, or new
browsers, without losing data.

With XML, data can be available to all kinds of "reading machines" like people, computers, voice
machines, news feeds, etc.
Question Bank
Multiple objective Questions

1) CSS stands for -

a) Cascade style sheets


b) Color and style sheets
c) Cascading style sheets
d) None of the above

2) Which of the following is the correct syntax for referring the external style sheet?

a) <style src = example.css>


b) <style src = "example.css" >
c) <stylesheet> example.css </stylesheet>
d) <link rel="stylesheet" type="text/css" href="example.css">

3) The property in CSS used to change the background color of an element is -

a) bgcolor
b) color
c) background-color
d) All of the above

4) The property in CSS used to change the text color of an element is -


a) bgcolor
b) color
c) background-color
d) All of the above

5) The CSS property used to control the element's font-size is -

a) text-style
b) text-size
c) font-size
d) None of the above

6) The HTML attribute used to define the inline styles is -

a) style
b) styles
c) class
d) None of the above

7) The HTML attribute used to define the internal stylesheet is -

a) <style>
b) style
c) <link>
d) <script>
8) Which of the following CSS property is used to set the background image of an element?

a) background-attachment
b) background-image
c) background-color
d) None of the above

9) Which of the following is the correct syntax to make the background-color of all paragraph elements
to yellow?

a) p {background-color : yellow;}
b) p {background-color : #yellow;}
c) all {background-color : yellow;}
d) all p {background-color : #yellow;}

10) Which of the following is the correct syntax to display the hyperlinks without any underline?

a) a {text-decoration : underline;}
b) a {decoration : no-underline;}
c) a {text-decoration : none;}
d) None of the above

11) Which of the following property is used as the shorthand property for the padding properties?

a) padding-left
b) padding-right
c) padding
d) All of the above

12) The CSS property used to make the text bold is -

a) font-weight : bold
b) weight: bold
c) font: bold
d) style: bold

13) Are the negative values allowed in padding property?

a) Yes
b) No
c) Can't say
d) May be

14) Which of the following property is used as the shorthand property of margin properties?

a) margin-left
b) margin-right
c) margin
d) None of the above

15) The CSS property used to specify the transparency of an element is -


a) opacity
b) filter
c) visibility
d) overlay

16) Which of the following is used to specify the subscript of text using CSS?

a) vertical-align: sub
b) vertical-align: super
c) vertical-align: subscript
d) None of the above

17) Which of the following CSS property is used to specify the space between every letter inside an
element?

a) alpha-spacing
b) character-spacing
c) letter-spacing
d) alphabet-spacing

18) The CSS property used to specify whether the text is written in the horizontal or vertical direction?

a) writing-mode
b) text-indent
c) word-break
d) None of the above

19) Which of the following syntax is correct in CSS to make each word of a sentence start with a capital
letter?

a) text-style : capital;
b) transform : capitalize;
c) text-transform : capital;
d) text-transform : capitalize;

20) How to select the elements with the class name "example"?

a) example
b) #example
c) .example
d) Class example

21) Which of the following is the correct syntax to select all paragraph elements in a div element?

a) div p
b) p
c) div#p
d) div ~ p

22) Which of the following is the correct syntax to select the p siblings of a div element?

a) p
b) div + p
c) div p
d) div ~ p

23) The CSS property used to draw a line around the elements outside the border?

a) border
b) outline
c) padding
d) line

24) Which of the following CSS property is used to add shadows to the text?

a) text-shadow
b) text-stroke
c) text-overflow
d) text-decoration

25) Which of the following is not a value of the font-variant property in CSS?

a) normal
b) small-caps
c) large-caps
d) inherit

26) Which of the following CSS property is used to specify whether the table cells share the common or
separate border?

a) border-collapse
b) border-radius
c) border-spacing
d) None of the above

27) The CSS property used to make the rounded borders, or rounded corners around an element is -

a) border-collapse
b) border-radius
c) border-spacing
d) None of the above

28) The CSS property used to set the distance between the borders of the adjacent cells in the table is -

a) border-collapse
b) border-radius
c) border-spacing
d) None of the above

29) Which of the following selector in CSS is used to select the elements that do not match the selectors?

a) :! selector
b) :not selector
c) :empty selector
d) None of the above

30) Which of the following is not a type of combinator?

a) >
b) ~
c) +
d) *

31) Which of the following CSS property defines how an image or video fits into container with
established height and width?

a) object-fit
b) object-position
c) position
d) None of the above

32) Which type of CSS is used in the below code?

<p style = "border:2px solid red;">


a. Inline CSS
b. Internal CSS
c. External CSS
d. None of the above

33) Which of the following CSS property specifies the origin of the background-image?

a) background-origin
b) background-attachment
c) background-size
d) None of the above

34) The CSS property used to set the maximum width of the element's content box is -

a) max-width property
b) height property
c) max-height property
d) position property

35) Which if the following CSS function allows us to perform calculations?

a) calc() function
b) calculator() function
c) calculate() function
d) cal() function

36) The CSS property used to set the maximum height of the element's content box is -

a) max-width property
b) height property
c) max-height property
d) position property

37) The CSS property used to set the minimum width of the element's content box is -

a) max-width property
b) min-width property
c) width property
d) All of the above

38) Which of the following CSS property is used to represent the overflowed text which is not visible to
the user?

a) text-shadow
b) text-stroke
c) text-overflow
d) text-decoration

39) The CSS property which is used to define the set the difference between two lines of your content is

a) min-height property
b) max-height property
c) line-height property
d) None of the above

40) The CSS property which is used to define the set the difference between two lines of your content is

a) min-height property
b) max-height property
c) line-height property
d) None of the above

41) Which of the following CSS property is used to add stroke to the text?

1. text-stroke property
2. text-transform property
3. text-decoration property
4. None of the above

42) Which of the following CSS property is used to set the blend mode for each background layer of an
element?

1. background-blend-mode property
2. background-collapse property
3. background-transform property
4. background-origin property

43) The CSS property used to specify the transparency of an element is -

1. Hover
2. opacity
3. clearfix
4. overlay
44) Which of the following CSS property is used to set the horizontal alignment of a table-cell box or
the block element?

1. text-align property
2. text-transform property
3. text-shadow property
4. text-decoration

45) The CSS property which is used to set the text wider or narrower compare to the default width of the
font is -

1. font-stretch property
2. font-weight property
3. text-transform property
4. font-variant property

46) Which of the following CSS property is used to specify the type of quotation mark?

1. quotes property
2. z-index property
3. hyphens property
4. None of the above

47) The CSS property used to specify the order of flex item in the grid container is -

a) order property
b) float property
c) overflow property
d) None of the above

48) The CSS property used to set the indentation of the first line in a block of text is -

a) text-indent property
b) text-stroke property
c) text-decoration property
d) text-overflow property

49) Which of the following CSS property creates a clipping region and specifies the visible area of the
element?

a) visibility property
b) background-clip property
c) clip-path property
d) None of the above

50) The correct syntax to give a line over text is -

a) text-decoration: line-through
b) text-decoration: none
c) text-decoration: overline
d) text-decoration: underline
Answers: 1(c), 2(d), 3(c), 4(b), 5(c), 6(a), 7(a), 8(b), 9(a), 10(c), 11(c), 12(a), 13(b), 14(c), 15(a), 16(a),
17(c), 18a), 19(d), 20(c), 21(a), 22(d), 23(b), 24(a), 25(c), 26(a), 27(b), 28(c), 29(b), 30(d), 31(a), 32(a),
33(a), 34(a), 35(a), 36(c), 37(b), 38(c), 39(c), 40(c), 41(a), 42(a), 43(b), 44(a), 45(a), 46(a), 47(a), 48(a),
49(c), 50(c).

Questions
1. What is the need of CSS?
2. How can we embed CSS in our HTML document? Explain with examples.
3. What is CSS box model? Why it is used?
4. What are the different type of lists used in CSS?
5. Make a class timetable with all the features of “table” in CSS.
6. What is XML?
7. Differentiate between HTML, XHTML and XML
8. What is cell padding? Explain with example.
9. How are the operations of the Internet monitored?
10. What are Web browsers, and why are these programs necessary?
11. How can a domain name reveal clues about an organization?
12. What is ARPANET? What government department created it, and what was its original
purpose?
13. Why might a user select a cable-modem service over a dial-up connection?
14. Where can you access a wireless ISP?
15. Why might users prefer the more heavily trafficked search engines?
16. Name two types of Internet search tools, and explain how they are different.
Unit -2

2.1 Client Side Programming


2.1.1 Introduction to Java Script

JavaScript
JavaScript (js) is a light-weight object-oriented programming language which is used by several websites
for scripting the webpages. It is an interpreted, full-fledged programming language that enables dynamic
interactivity on websites when applied to an HTML document. It was introduced in the year 1995 for
adding programs to the webpages in the Netscape Navigator browser. Since then, it has been adopted by
all other graphical web browsers. With JavaScript, users can build modern web applications to interact
directly without reloading the page every time. The traditional website uses js to provide several forms
of interactivity and simplicity.

Although, JavaScript has no connectivity with Java programming language. The name was suggested
and provided in the times when Java was gaining popularity in the market. In addition to web browsers,
databases such as CouchDB and MongoDB uses JavaScript as their scripting and query language.

Features of JavaScript

There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the
operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than using
classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

History of JavaScript

In 1993, Mosaic, the first popular web browser, came into existence. In the year 1994, Netscape was
founded by Marc Andreessen. He realized that the web needed to become more dynamic. Thus, a 'glue
language' was believed to be provided to HTML to make web designing easy for designers and part-time
programmers. Consequently, in 1995, the company recruited Brendan Eich intending to implement and
embed Scheme programming language to the browser. But, before Brendan could start, the company
merged with Sun Microsystems for adding Java into its Navigator so that it could compete with
Microsoft over the web technologies and platforms. Now, two languages were there: Java and the
scripting language. Further, Netscape decided to give a similar name to the scripting language as Java's.
It led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined the first code of Javascript named
'Mocha'. Later, the marketing team replaced the name with 'LiveScript'. But, due to trademark reasons
and certain other reasons, in December 1995, the language was finally renamed to 'JavaScript'. From
then, JavaScript came into existence.
Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and
prompt dialog box),
o Displaying clocks etc.

JavaScript Example

<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>

Output

o Welcome to JavaScript

Hello JavaScript by JavaScript

Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript code: within body
tag, within head tag and external JavaScript file.

JavaScript example.

<html>
<body>
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
</body>
</html>

Output

JavaScript is a simple language for javatpoint learners


The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the browser about the data.
The document.write() function is used to display dynamic content through JavaScript.
o Places to put JavaScript code

1. Between the body tag of html


2. Between the head tag of html
3. In .js file (external javaScript)

o 1) JavaScript Example : code between the body tag

In the above example, we have displayed the dynamic content using JavaScript. Let’s see the simple
example of JavaScript that displays alert dialog box.

<html>
<body>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
</html>

Output

Alert will appear with


Hello Javatpoint

o 2) JavaScript Example : code between the head tag

Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside the head
tag.

In this example, we are creating a function msg(). To create function in JavaScript, you need to write
function with function_name as given below.

To call function, you need to work on event. Here we are using onclick event to call msg() function.

<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
o Output

Welcome to Javascript

o click
o 3) External JavaScript file

We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in several html pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript
files into a single file. It increases the speed of the webpage.

Let's create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.

<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

Advantages of External JavaScript

There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.


2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further reduces the page
loading time.
4. It enables both web designers and coders to work with html and js files parallelly and separately,
i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the js file.

Disadvantages of External JavaScript

There are the following disadvantages of external files:

1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect the execution
of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its dependent files.
5. We need to check each file that depends on the commonly created external javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.

Javascript Basics

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.

o 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

o 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.

Example

<html>
<body>
<script>
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>
</body>
</html>

Output

30
o 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:

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

Output
example of javascript multiline comment

2.1.2 Javascript Variable

A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

Correct JavaScript variables

1. var x = 10;

2. var _value="sonoo";

Incorrect JavaScript variables

1. var 123=30;

2. var *aa=320;
JavaScript local variable

A JavaScript local variable is declared inside block or function. It is accessible within the function or
block only. For example:

1. <script>

2. function abc(){

3. var x=10;//local variable


4. }

5. </script>

Or,

1. <script>

2. If(10<13){

3. var y=20;//JavaScript local variable

4. }

5. </script>

JavaScript global variable

A JavaScript global variable is accessible from any function. A variable i.e. declared outside the
function or declared with window object is known as global variable. For example:

1. <script>

2. var data=200;//gloabal variable

3. function a(){

4. document.writeln(data);

5. }

6. function b(){

7. document.writeln(data);

8. }

9. a();//calling JavaScript function

10. b();

11. </script>
Output 200 200
A JavaScript global variable is declared outside the function or declared with window object. It can be
accessed from any function.

o Declaring JavaScript global variable within function

To declare JavaScript global variables inside function, you need to use window object. For example:

window.value=90;
Now it can be declared inside any function and can be accessed from any function. For example:
<html>
<body>
<script>
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
m();
n();
</script>
</body>
</html>

Internals of global variable in JavaScript

When you declare a variable outside the function, it is added in the window object internally. You can
access it through window object also. For example:

var value=50;
function a(){
alert(window.value);//accessing global variable
}
o Javascript Data Types

JavaScript provides different data types to hold different types of values. There are two types of data
types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the variable because it
is dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold
any type of values such as numbers, strings etc. For example:

1. var a=40;//holding number

2. var b="Rahul";//holding string

o JavaScript primitive data types

Table 2.1: Primitive data types in JavaScript.

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100


Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

o JavaScript non-primitive data types

Table 2.2: Non- Primitive data types in JavaScript.

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

o JavaScript Operators

JavaScript operators are symbols that are used to perform operations on operands. For example:

1. var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

o JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on the operands. The following operators
are known as JavaScript arithmetic operators.
Table 2.3: Arithmetic Operators in JavaScript.

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

o JavaScript Comparison Operators

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

Table 2.4: Comparison Operators in JavaScript.

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

o JavaScript Bitwise Operators

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

Table 2.5: Bitwise Operators in JavaScript.

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

o JavaScript Logical Operators

The following operators are known as JavaScript logical operators.

Table 2.6: Logical Operators in JavaScript.

Operator Description Example

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


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

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

o JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

Table 2.7: Assignment Operators in JavaScript.

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.

Table 2.8: Special Operators in JavaScript.

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.

2.1.3 Javascript Loops and Functions


o 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

o JavaScript If statement

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

1. if(expression){

2. //content to be evaluated

3. }
o Figure 2.1 Flowchart of JavaScript If statement

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

1. <script>

2. var a=20;

3. if(a>10){

4. document.write("value of a is greater than 10");

5. }

6. </script>

o JavaScript If...else Statement

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

1. if(expression){

2. //content to be evaluated if condition is true

3. }

4. else{

5. //content to be evaluated if condition is false

6. }
Figure 2. 2: 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.

1. <script>

2. var a=20;

3. if(a%2==0){

4. document.write("a is even number");

5. }

6. else{

7. document.write("a is odd number");

8. }

9. </script>

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.

1. if(expression1){

2. //content to be evaluated if expression1 is true


3. }

4. else if(expression2){

5. //content to be evaluated if expression2 is true

6. }

7. else if(expression3){

8. //content to be evaluated if expression3 is true

9. }

10. else{

11. //content to be evaluated if no expression is true

12. }

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

1. <script>

2. var a=20;

3. if(a==10){

4. document.write("a is equal to 10");

5. }

6. else if(a==15){

7. document.write("a is equal to 15");

8. }

9. else if(a==20){

10. document.write("a is equal to 20");

11. }

12. else{

13. document.write("a is not equal to 10, 15 or 20");

14. }

15. </script>

o JavaScript Switch

The JavaScript switch statement is used to execute one code from multiple expressions. It is just like
else if statement that we have learned in previous page. But it is convenient than if..else..if because it can
be used with numbers, characters etc.
The signature of JavaScript switch statement is given below.

1. switch(expression){

2. case value1:

3. code to be executed;

4. break;

5. case value2:

6. code to be executed;

7. break;

8. ......

9.

10. default:

11. code to be executed if above values are not matched;

12. }

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

<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>

o The switch statement is fall-through i.e. all the cases will be evaluated if you don't use break
statement.
o JavaScript Loops

The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops. It
makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop
3. do-while loop
4. for-in loop

o JavaScript For loop

The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number
of iteration is known. The syntax of for loop is given below.

1. for (initialization; condition; increment)

2. {

3. code to be executed

4. }

Let’s see the simple example of for loop in javascript.

1. <script>

2. for (i=1; i<=5; i++)

3. {

4. document.write(i + "<br/>")

5. }

6. </script>

JavaScript while loop

The JavaScript while loop iterates the elements for the infinite number of times. It should be used if
number of iteration is not known. The syntax of while loop is given below.

1. while (condition)

2. {

3. code to be executed

4. }

Let’s see the simple example of while loop in javascript.


1. <script>

2. var i=11;

3. while (i<=15)

4. {

5. document.write(i + "<br/>");

6. i++;

7. }

8. </script>

JavaScript do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like while loop. But,
code is executed at least once whether condition is true or false. The syntax of do while loop is given
below.

1. do{

2. code to be executed

3. }while (condition);

Let’s see the simple example of do while loop in javascript.

1. <script>

2. var i=21;

3. do{

4. document.write(i + "<br/>");

5. i++;

6. }while (i<=25);

7. </script>

o JavaScript Functions

JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.

o Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of code each
time to perform a common task.

o JavaScript Function Syntax

The syntax of declaring function is given below.

1. function functionName([arg1, arg2, ...argN]){

2. //code to be executed

3. }

JavaScript Functions can have 0 or more arguments.

o JavaScript Function Example

Let’s see the simple example of function in JavaScript that does not has arguments.

1. <script>

2. function msg(){

3. alert("hello! this is message");

4. }

5. </script>

6. <input type="button" onclick="msg()" value="call function"/>

o JavaScript Function Arguments

We can call function by passing arguments. Let’s see the example of function that has one argument.

1. <script>

2. function getcube(number){

3. alert(number*number*number);

4. }

5. </script>

6. <form>

7. <input type="button" value="click" onclick="getcube(4)"/>

8. </form>
o Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the example of function that
returns value.

1. <script>

2. function getInfo(){

3. return "hello javatpoint! How r u?";

4. }

5. </script>

6. <script>

7. document.write(getInfo());

8. </script>

o JavaScript Function Object

In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the
code globally. However, if we call the constructor directly, a function is created dynamically but in an
unsecured way.

o Syntax
o new Function ([arg1[, arg2[, ....argn]],] functionBody)
o Parameter

arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

o JavaScript Function Methods

Let's see function methods with description.

Table 2.9: Function Methods in JavaScript.

Method Description

apply() It is used to call a function contains this value and a single array of arguments.

bind() It is used to create a new function.

call() It is used to call a function contains this value and an argument list.
toString() It returns the result in a form of a string.

o JavaScript Function Object Examples


o Example 1

Let's see an example to display the sum of given numbers.

1. <script>

2. var add=new Function("num1","num2","return num1+num2");

3. document.writeln(add(2,5));

4. </script>

Example 2

Let's see an example to display the power of provided value.

1. <script>

2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");

3. document.writeln(pow(2,3));

4. </script>
o JavaScript Objects

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.

o 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)

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.

1. <script>

2. emp={id:102,name:"Shyam Kumar",salary:40000}

3. document.write(emp.id+" "+emp.name+" "+emp.salary);

4. </script>

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.

1. <script>

2. var emp=new Object();

3. emp.id=101;

4. emp.name="Ravi Malik";

5. emp.salary=50000;

6. document.write(emp.id+" "+emp.name+" "+emp.salary);

7. </script>

o 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.

1. <script>

2. function emp(id,name,salary){

3. this.id=id;

4. this.name=name;
5. this.salary=salary;

6. }

7. e=new emp(103,"Vimal Jaiswal",30000);

8.

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

10. </script>

o Defining method in JavaScript Object


o

Table 2.10: Object Methods in JavaScript.


S.N Methods Description
o

1 Object.assign() This method is used to copy enumerable and own properties from
a source object to a target object

2 Object.create() This method is used to create a new object with the specified
prototype object and properties.

3 Object.defineProperty() This method is used to describe some behavioral attributes of the


property.

4 Object.defineProperties() This method is used to create or configure multiple object


properties.

5 Object.entries() This method returns an array with arrays of the key, value pairs.

6 Object.freeze() This method prevents existing properties from being removed.

7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the specified


property of the specified object.

8 Object.getOwnPropertyDescriptors() This method returns all own property descriptors of a given


object.

9 Object.getOwnPropertyNames() This method returns an array of all properties (enumerable or


not) found.

10 Object.getOwnPropertySymbols() This method returns an array of all own symbol key properties.

11 Object.getPrototypeOf() This method returns the prototype of the specified object.

12 Object.is() This method determines whether two values are 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.


16 Object.keys() This method returns an array of a given object's own property
names.

17 Object.preventExtensions() This method is used to prevent any extensions of an object.

18 Object.seal() This method prevents new properties from being added and
marks all existing properties as non-configurable.

19 Object.setPrototypeOf() This method sets the prototype of a specified object to another


object.

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

o JavaScript Object Methods

The various methods of Object are as follows:

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.

1. <script>

2. function emp(id,name,salary){

3. this.id=id;

4. this.name=name;

5. this.salary=salary;

6. this.changeSalary=changeSalary;

7. function changeSalary(otherSalary){

8. this.salary=otherSalary;

9. }

10. }

11. e=new emp(103,"Sonoo Jaiswal",30000);

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

13. e.changeSalary(45000);

14. document.write("<br>"+e.id+" "+e.name+" "+e.salary);

15. </script>
o 2.1.4 JavaScript Array

JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

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

o 1) JavaScript array literal

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

1. var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by , (comma).

Let's see the simple example of creating and using array in JavaScript.

1. <script>

2. var emp=["Sonoo","Vimal","Ratan"];

3. for (i=0;i<emp.length;i++){

4. document.write(emp[i] + "<br/>");

5. }

6. </script>

o The .length property returns the length of an array.

2) JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

1. var arrayname=new Array();

Here, new keyword is used to create instance of array.

Let's see the example of creating array directly.

1. <script>

2. var i;

3. var emp = new Array();

4. emp[0] = "Arun";

5. emp[1] = "Varun";
6. emp[2] = "John";

7.

8. for (i=0;i<emp.length;i++){

9. document.write(emp[i] + "<br>");

10. }

11. </script>

o 3) JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.

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

1. <script>

2. var emp=new Array("Jai","Vijay","Smith");

3. for (i=0;i<emp.length;i++){

4. document.write(emp[i] + "<br>");

5. }

6. </script>

o JavaScript Array Methods

Let's see the list of JavaScript array methods with their description.

Table 2.11: Array Methods in JavaScript.

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the
modified array.

entries() It creates an iterator object and a loop that iterates over each key/value pair.

every() It determines whether all the elements of an array are satisfying the provided
function conditions.
flat() It creates a new array carrying sub-array elements concatenated recursively till
the specified depth.

flatMap() It maps all array elements via mapping function, then flattens the result into a
new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another array element.

filter() It returns the new array containing the elements that pass the provided function
conditions.

find() It returns the value of the first element in the given array that satisfies the
specified condition.

findIndex() It returns the index value of the first element in the given array that satisfies the
specified condition.

forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index of the
first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then loops
through these keys.

lastIndexOf() It searches the specified element in the given array and returns the index of the
last match.

map() It calls the specified function for every array element and returns the new array

of() It creates a new array from a variable number of arguments, holding any type of
argument.
pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right and reduces the
initial) array to a single value.

reduceRight() It executes a provided function for each value from right to left and reduces the
array to a single value.

some() It determines if any element of the array passes the test of the implemented
function.

shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.

toString() It converts the elements of a specified array into string form, without affecting
the original array.

unshift() It adds one or more elements in the beginning of the given array.

values() It creates a new iterator object carrying values for each index in the array.

o JavaScript String

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. By string object (using new keyword)
o 1) By string literal

The string literal is created using double quotes. The syntax of creating string using string literal is given
below:

1. var stringname="string value";

1. <script>

2. var str="This is string literal";

3. document.write(str);

4. </script>

2) By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

1. var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

Let's see the example of creating string in JavaScript by new keyword.

1. <script>

2. var stringname=new String("hello javascript string");

3. document.write(stringname);

4. </script>

o JavaScript String Methods

Let's see the list of JavaScript string methods with examples.

Table 2.12: String Methods in JavaScript.

Methods Description

charAt() It provides the char value present at the specified index.

charCodeAt() It provides the Unicode value of a character present at the specified


index.
concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.

search() It searches a specified regular expression in a given string and returns


its position if a match occurs.

match() It searches a specified regular expression in a given string and returns


that regular expression if a match occurs.

replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis of the
specified starting position and length.

substring() It is used to fetch the part of the given string on the basis of the
specified index.

slice() It is used to fetch the part of the given string. It allows us to assign
positive as well negative index.

toLowerCase() It converts the given string into lowercase letter.

toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s
current locale.

toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s
current locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

split() It splits a string into substring array, then returns that newly created
array.
trim() It trims the white space from the left and right side of the string.

o Document Object Model

1. Document Object
2. Properties of document object
3. Methods of document object
4. Example of document object

The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object. It is the root element that
represents the html document. It has properties and methods. By the help of document object, we can
add dynamic content to our web page.

As mentioned earlier, it is the object of window. So

1. window.document

According to W3C - "The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the content, structure, and
style of a document."

o Properties of document object

o Figure 2.3 Properties Of Document Object


o Methods of document object

We can access and change the contents of document by its methods.

o Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we are
using document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with welcome message.

1. <script type="text/javascript">

2. function printvalue(){

3. var name=document.form1.name.value;

4. alert("Welcome: "+name);

5. }

6. </script>

7.

8. <form name="form1">

9. Enter Name:<input type="text" name="name"/>

10. <input type="button" onclick="printvalue()" value="print name"/>

11. </form>

o Javascript - document.getElementById() method

1. getElementById() method
2. Example of getElementById()

The document.getElementById() method returns the element of specified id.

In the previous page, we have used document.form1.name.value to get the value of the input value.
Instead of this, we can use document.getElementById() method to get value of the input text. But we
need to define id for the input field.

Let's see the simple example of document.getElementById() method that prints cube of the given
number.

1. <script type="text/javascript">

2. function getcube(){

3. var number=document.getElementById("number").value;
4. alert(number*number*number);

5. }

6. </script>

7. <form>

8. Enter No:<input type="text" id="number" name="number"/><br/>

9. <input type="button" value="cube" onclick="getcube()"/>

10. </form>

o Javascript - document.getElementsByName() method

1. getElementsByName() method
2. Example of getElementsByName()

The document.getElementsByName() method returns all the element of specified name.

The syntax of the getElementsByName() method is given below:

1. document.getElementsByName("name")

Here, name is required.

Example of document.getElementsByName() method

In this example, we going to count total number of genders. Here, we are using getElementsByName()
method to get all the genders.

1. <script type="text/javascript">

2. function totalelements()

3. {

4. var allgenders=document.getElementsByName("gender");

5. alert("Total Genders:"+allgenders.length);

6. }

7. </script>

8. <form>

9. Male:<input type="radio" name="gender" value="male">

10. Female:<input type="radio" name="gender" value="female">

11.

12. <input type="button" onclick="totalelements()" value="Total Genders">


13. </form>
o Javascript - document.getElementsByTagName() method

1. getElementsByTagName() method
2. Example of getElementsByTagName()

The document.getElementsByTagName() method returns all the element of specified tag name.

The syntax of the getElementsByTagName() method is given below:

1. document.getElementsByTagName("name")

Here, name is required.

Example of document.getElementsByTagName() method

In this example, we going to count total number of paragraphs used in the document. To do this, we have
called the document.getElementsByTagName("p") method that returns the total paragraphs.

1. <script type="text/javascript">

2. function countpara(){

3. var totalpara=document.getElementsByTagName("p");

4. alert("total p tags are: "+totalpara.length);

5.

6. }

7. </script>

8. <p>This is a pragraph</p>

9. <p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p>

10. <p>Let's see the simple example</p>

11. <button onclick="countpara()">count paragraph</button>

Another example of document.getElementsByTagName() method

In this example, we going to count total number of h2 and h3 tags used in the document.

1. <script type="text/javascript">

2. function counth2(){

3. var totalh2=document.getElementsByTagName("h2");

4. alert("total h2 tags are: "+totalh2.length);

5. }
6. function counth3(){

7. var totalh3=document.getElementsByTagName("h3");

8. alert("total h3 tags are: "+totalh3.length);

9. }

10. </script>

11. <h2>This is h2 tag</h2>

12. <h2>This is h2 tag</h2>

13. <h3>This is h3 tag</h3>

14. <h3>This is h3 tag</h3>

15. <h3>This is h3 tag</h3>

16. <button onclick="counth2()">count h2</button>

17. <button onclick="counth3()">count h3</button>

o Javascript - innerHTML

1. javascript innerHTML
2. Example of innerHTML property

The innerHTML property can be used to write the dynamic html on the html document.

It is used mostly in the web pages to generate the dynamic html such as registration form, comment form,
links etc.

o Example of innerHTML property

In this example, we are going to create the html form when user clicks on the button.

In this example, we are dynamically writing the html form inside the div name having the id mylocation.
We are identifing this position by calling the document.getElementById() method.

1. <script type="text/javascript" >

2. function showcommentform() {

3. var data="Name:<input type='text' name='name'><br>Comment:<br><textarea rows='5' cols='80'><


/textarea>

4. <br><input type='submit' value='Post Comment'>";

5. document.getElementById('mylocation').innerHTML=data;

6. }

7. </script>
8. <form name="myForm">

9. <input type="button" value="comment" onclick="showcommentform()">

10. <div id="mylocation"></div>

11. </form>

Show/Hide Comment Form Example using innerHTML

1. <!DOCTYPE html>

2. <html>

3. <head>

4. <title>First JS</title>

5. <script>

6. var flag=true;

7. function commentform(){

8. var cform="<form action='Comment'>Enter Name:<br><input type='text' name='name'/><br/>

9. Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<br/>

10. <textarea rows='5' cols='70'></textarea><br><input type='submit' value='Post Comment'/></form>


";

11. if(flag){

12. document.getElementById("mylocation").innerHTML=cform;

13. flag=false;

14. }else{

15. document.getElementById("mylocation").innerHTML="";

16. flag=true;

17. }

18. }

19. </script>

20. </head>

21. <body>

22. <button onclick="commentform()">Comment</button>

23. <div id="mylocation"></div>

24. </body>
25. </html>

Javascript Form Design

o JavaScript Form Validation

1. JavaScript form validation


2. Example of JavaScript validation
3. JavaScript email validation

It is important to validate the form submitted by the user because it can have inappropriate values. So,
validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing will be faster than
server-side validation. Most of the web developers prefer JavaScript form validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

o JavaScript Form Validation Example

In this example, we are going to validate the name and password. The name can’t be empty and password
can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the next page until
given values are correct.

1. <script>

2. function validateform(){

3. var name=document.myform.name.value;

4. var password=document.myform.password.value;

5.

6. if (name==null || name==""){

7. alert("Name can't be blank");

8. return false;

9. }else if(password.length<6){

10. alert("Password must be at least 6 characters long.");

11. return false;

12. }

13. }

14. </script>
15. <body>

16. <form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >

17. Name: <input type="text" name="name"><br/>

18. Password: <input type="password" name="password"><br/>

19. <input type="submit" value="register">

20. </form>

JavaScript Retype Password Validation

1. <script type="text/javascript">

2. function matchpass(){

3. var firstpassword=document.f1.password.value;

4. var secondpassword=document.f1.password2.value;

5.

6. if(firstpassword==secondpassword){

7. return true;

8. }

9. else{

10. alert("password must be same!");

11. return false;

12. }

13. }

14. </script>

15.

16. <form name="f1" action="register.jsp" onsubmit="return matchpass()">

17. Password:<input type="password" name="password" /><br/>

18. Re-enter Password:<input type="password" name="password2"/><br/>

19. <input type="submit">

20. </form>

o JavaScript Number Validation


Let's validate the textfield for numeric value only. Here, we are using isNaN() function.

1. <script>

2. function validate(){

3. var num=document.myform.num.value;

4. if (isNaN(num)){

5. document.getElementById("numloc").innerHTML="Enter Numeric value only";

6. return false;

7. }else{

8. return true;

9. }

10. }

11. </script>

12. <form name="myform" onsubmit="return validate()" >

13. Number: <input type="text" name="num"><span id="numloc"></span><br/>

14. <input type="submit" value="submit">

15. </form>

o JavaScript validation with image

Let’s see an interactive JavaScript form validation example that displays correct and incorrect image if
input is correct or incorrect.

1. <script>

2. function validate(){

3. var name=document.f1.name.value;

4. var password=document.f1.password.value;

5. var status=false;

6.

7. if(name.length<1){

8. document.getElementById("nameloc").innerHTML=

9. " <img src='unchecked.gif'/> Please enter your name";

10. status=false;

11. }else{
12. document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";

13. status=true;

14. }

15. if(password.length<6){

16. document.getElementById("passwordloc").innerHTML=

17. " <img src='unchecked.gif'/> Password must be at least 6 char long";

18. status=false;

19. }else{

20. document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";

21. }

22. return status;

23. }

24. </script>

25.

26. <form name="f1" action="#" onsubmit="return validate()">

27. <table>

28. <tr><td>Enter Name:</td><td><input type="text" name="name"/>

29. <span id="nameloc"></span></td></tr>

30. <tr><td>Enter Password:</td><td><input type="password" name="password"/>

31. <span id="passwordloc"></span></td></tr>

32. <tr><td colspan="2"><input type="submit" value="register"/></td></tr>

33. </table>

34. </form>

o
JavaScript email validation

We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

o email id must contain the @ and . character


o There must be at least one character before and after the @.
o There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.

1. <script>

2. function validateemail()

3. {

4. var x=document.myform.email.value;

5. var atposition=x.indexOf("@");

6. var dotposition=x.lastIndexOf(".");

7. if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){

8. alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);

9. return false;

10. }

11. }

12. </script>

13. <body>

14. <form name="myform" method="post" action="#" onsubmit="return validateemail();">

15. Email: <input type="text" name="email"><br/>

16.

17. <input type="submit" value="register">

18. </form>

2.2 Server-side Programming

2.2.1 JAVA Servlets

Servlet technology is used to create a web application (resides at server side and generates a dynamic
web page).

Servlet technology is robust and scalable because of java language. Servlets provide a component-based,
platform-independent method for building Webbased applications, without the performance limitations
of CGI programs. Before Servlet, CGI (Common Gateway Interface) scripting language was common as
a server-side programming language. However, there were many disadvantages to this technology. We
have discussed these disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet,
ServletRequest, ServletResponse, etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.

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

o Servlet is an API that provides many interfaces and classes including documentation.

o Servlet is an interface that must be implemented for creating any Servlet.

o Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.

o Servlet is a web component that is deployed on the server to create a dynamic web page.

Fig. 2.4 Client Server figure

2.2.2 Servlets Architecture

The following Figure shows the position of Servlets in a Web Application.

Fig. 2.5 Position of Servlets in a Web Application

Servlets Tasks
Servlets perform the following major tasks −

 Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.

 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media
types and compression schemes the browser understands, and so forth.

 Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.

 Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent
in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.

 Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.

Web application

A web application is an application accessible from the web. A web application is composed of web
components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The
web components typically execute in Web Server and respond to the HTTP request.

CGI (Common Gateway Interface)

CGI technology enables the web server to call an external program and pass HTTP request information
to the external program to process the request. For each request, it starts a new process.

Disadvantages of CGI

There are many problems in CGI technology:

1. If the number of clients increases, it takes more time for sending the response.

2. For each request, it starts a process, and the web server is limited to start processes.

3. It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for handling the
multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a
common memory area, lightweight, cost of communication between the threads are low. The advantages
of Servlet are as follows:

1. Better performance: because it creates a thread for each request, not process.

2. Portability: because it uses Java language.

3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.

4. Secure: because it uses java language.

Applications of Servlet

 Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.

 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media
types and compression schemes the browser understands, and so forth.

 Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.

 Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent
in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.

 Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.

Web Terminology

Table: 2.13

Terminology Description
Website: static vs dynamic It is a collection of related web pages that may contain text,
images, audio and video.

HTTP It is the data communication protocol used to establish communication between


client and server.

HTTP Requests It is the request send by the computer to a web server that contains all sorts of
potentially interesting information.

Get vs Post It gives the difference between GET and POST request.

Container It is used in java for dynamically generating the web pages on the server side.

Server: Web vs It is used to manage the network resources and for running the program or software
Application that provides services.

Content Type It is HTTP header that provides the description about what are you sending to the
browser.

o Servlet API

1. Servlet API
2. Interfaces in javax.servlet package
3. Classes in javax.servlet package
4. Interfaces in javax.servlet.http package
5. Classes in javax.servlet.http package

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.HTML Tutorial

o 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

o 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

o 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)

o 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)
o 2.2.3 Servlet Interface

Servlet interface provides common behavior to all the servlets. Servlet interface defines methods that
all servlets must implement.

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It
provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to destroy
the servlet and 2 non-life cycle methods.

o Methods of Servlet interface

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of
servlet. These are invoked by the web container.

Table:-2.14

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet
and invoked by the web container only once.

public void service(ServletRequest provides response for the incoming request. It is invoked
request,ServletResponse response) at each request by the web container.

public void destroy() is invoked only once and indicates that servlet is being
destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such as writer,


copyright, version etc.

o Servlet Example by implementing Servlet interface

Let's see the simple example of servlet by implementing the servlet interface.

File: First.java

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

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
}

o GenericServlet class

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the
implementation of all the methods of these interfaces except the service method.

GenericServlet class can handle any type of request so it is protocol-independent.

You may create a generic servlet by inheriting the GenericServlet class and providing the implementation
of the service method.

o Methods of GenericServlet class

There are many methods in GenericServlet class. They are as follows: a Try Catch

1. public void init(ServletConfig config) is used to initialize the servlet.


2. public abstract void service(ServletRequest request, ServletResponse response) provides
service for the incoming request. It is invoked at each time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet
is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no need
to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file
and a stack trace.

o Servlet Example by inheriting the GenericServlet class

Let's see the simple example of servlet by inheriting the GenericServlet class.

File: First.java

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

public class First extends GenericServlet{


public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}

HttpServlet class

The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides
http specific methods such as doGet, doPost, doHead, doTrace etc.

Methods of HttpServlet class

There are many methods in HttpServlet class. They are as follows:

1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the


protected service method by converting the request and response object into http type.

2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the


request from the service method, and dispatches the request to the doXXX() method depending
on the incoming http request type.

3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET


request. It is invoked by the web container.

4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the


POST request. It is invoked by the web container.

5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the


HEAD request. It is invoked by the web container.

6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the


OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT
request. It is invoked by the web container.

8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the


TRACE request. It is invoked by the web container.

9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the


DELETE request. It is invoked by the web container.

10. protected long getLastModified(HttpServletRequest req) returns the time when


HttpServletRequest was last modified since midnight January 1, 1970 GMT.

Life Cycle of a Servlet (Servlet Life Cycle)

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

1. Servlet class is loaded.

2. Servlet instance is created.

3. init method is invoked.

4. service method is invoked.

5. destroy method is invoked.

Fig.2.6 Stages of Servlet

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()

Steps to create a servlet example

There are given 6 steps to create a servlet example. These steps are required for all the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,

2. By inheriting GenericServlet class, (or)

3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific method
such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1. Create a directory structure


2. Create a Servlet

3. Compile the Servlet

4. Create a deployment descriptor

5. Start the server and deploy the project

6. Access the servlet

1) Create a directory structures

The directory structure defines that where to put the different types of files so that web container may
get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see the
directory structure that must be followed to create the servlet.

As you can see that the servlet class file must be in the classes folder. The web.xml file must be under
the WEB-INF folder.

2)Create a Servlet

There are three ways to create the servlet.

1. By implementing the Servlet interface

2. By inheriting the GenericServlet class

3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to handle http
requests such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this example, we
are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice
that get request is the default request.

DemoServlet.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data

//writing html in the stream


pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");

pw.close();//closing the stream


}}

3) Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:

Table: 2.14

Jar file Server

1) servlet-api.jar Apache Tomcat

2) weblogic.jar Weblogic

3) javaee.jar Glassfish

4) javaee.jar JBoss

Two ways to load the jar file

1. set classpath

2. paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-
INF/classes directory.

4) Create the deployment descriptor (web.xml file)

The deployment descriptor is an xml file, from which Web Container gets the information about the
servet to be invoked.

The web container uses the Parser to get the information from the web.xml file. There are many xml
parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run the simple
servlet program.

web.xml file

<web-app>

<servlet>

<servlet-name>sonoojaiswal</servlet-name>

<servlet-class>DemoServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>sonoojaiswal</servlet-name>

<url-pattern>/welcome</url-pattern>

</servlet-mapping>

</web-app>

Description of the elements of web.xml file

There are too many elements in the web.xml file. Here is the illustration of some elements that is used in
the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.

5) Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory.

One Time Configuration for Apache Tomcat Server

You need to perform 2 tasks:

1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).


2. Change the port number of tomcat (optional). It is required if another server is running on same
port (8080).

1) How to set JAVA_HOME in environment variable?

To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment variables.

Go to My Computer properties -> Click on advanced tab then environment variables -> Click on the new
tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable
value -> ok -> ok -> ok.

Go to My Computer properties:

Click on advanced system settings tab then environment variables:


Click on the new tab of user variable or system variable:

Write JAVA_HOME in variable name and paste the path of jdk folder in variable value:

There must not be semicolon (;) at the end of the path.

After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin.

Note: There are two types of tomcat available:


1. Apache tomcat that needs to extract only (no need to install)

2. Apache tomcat that needs to install

It is the example of apache tomcat that needs to extract only.

Now server is started successfully.

2) How to change port number of apache tomcat

Changing the port number is required if there is another server running on the same system with same
port number.Suppose you have installed oracle, you need to change the port number of apache tomcat
because both have the default port number 8080.

Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change the
Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us replace it by
9999 and save this file.

5) How to deploy the servlet project

Copy the project and paste it in the webapps folder under apache tomcat.
But there are several ways to deploy the project. They are as follows:

o By copying the context(project) folder into the webapps directory

o By copying the war folder into the webapps directory

o By selecting the folder path from the server

o By selecting the war file from the server

Here, we are using the first approach.

You can also create war file, and paste it inside the webapps directory. To do so, you need to use jar tool
to create the war file. Go inside the project directory (before the WEB-INF), then write:

1. projectfolder> jar cvf myproject.war *

Creating war file has an advantage that moving the project from one location to another takes less time.

6) How to access the servlet

Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. For example:

1. http://localhost:9999/demo/welcome
How Servlet works?

It is important to learn how servlet works for understanding the servlet well. Here, we are going to get
the internal detail about the first servlet program.

The server checks if the servlet is requested for the first time.

If yes, web container does the following tasks:

o loads the servlet class.

o instantiates the servlet class.

o calls the init method passing the ServletConfig object

else

o calls the service method passing request and response objects

The web container calls the destroy method when it needs to remove the servlet such as at time of
stopping server or undeploying the project.

How web container handles the servlet request?

The web container is responsible to handle the request. Let's see how it handles the request.

o maps the request with the servlet in the web.xml file.

o creates request and response objects for this request

o calls the service method on the thread

o The public service method internally calls the protected service method

o The protected service method calls the doGet method depending on the type of request.

o The doGet method generates the response and it is passed to the client.
o After sending the response, the web container deletes the request and response objects. The
thread is contained in the thread pool or deleted depends on the server implementation.

What is written inside the public service method?

The public service method converts the ServletRequest object into the HttpServletRequest type and
ServletResponse object into the HttpServletResponse type. Then, calls the service method passing these
objects. Let's see the internal code:

public void service(ServletRequest req, ServletResponse res)


throws ServletException, IOException
{
HttpServletRequest request;
HttpServletResponse response;
try
{
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
}
catch(ClassCastException e)
{
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}

What is written inside the protected service method?

The protected service method checks the type of request, if request type is get, it calls doGet method, if
request type is post, it calls doPost method, so on. Let's see the internal code:

protected void service(HttpServletRequest req, HttpServletResponse resp)


throws ServletException, IOException
{
String method = req.getMethod();
if(method.equals("GET"))
{
long lastModified = getLastModified(req);
if(lastModified == -1L)
{
doGet(req, resp);
}
....
//rest of the code
}
}
Parameter data

You must have come across many situations when you need to pass some information from your browser
to web server and ultimately to your backend program. The browser uses two methods to pass this
information to web server. These methods are GET Method and POST Method.

GET Method
The GET method sends the encoded user information appended to the page request. The page and the
encoded information are separated by the ? (question mark) symbol as follows −

http://www.test.com/hello?key1 = value1&key2 = value2

The GET method is the default method to pass information from browser to web server and it produces
a long string that appears in your browser's Location:box. Never use the GET method if you have
password or other sensitive information to pass to the server. The GET method has size limitation: only
1024 characters can be used in a request string.

This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using doGet() method.

POST Method

A generally more reliable method of passing information to a backend program is the POST method.
This packages the information in exactly the same way as GET method, but instead of sending it as a
text string after a ? (question mark) in the URL it sends it as a separate message. This message comes to
the backend program in the form of the standard input which you can parse and use for your processing.
Servlet handles this type of requests using doPost() method.

Reading Form Data using Servlet

Servlets handles form data parsing automatically using the following methods depending on the situation

 getParameter() − You call request.getParameter() method to get the value of a form parameter.

 getParameterValues() − Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.

 getParameterNames() − Call this method if you want a complete list of all parameters in the
current request.

GET Method Example using URL

Here is a simple URL which will pass two values to HelloForm program using GET method.

http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI

Given below is the HelloForm.java servlet program to handle input given by web browser. We are going
to use getParameter() method which makes it very easy to access passed information −

// Import required java libraries


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

// Extend HttpServlet class


public class HelloForm extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>" +
"</html>"
);
}
}
Assuming your environment is set up properly, compile HelloForm.java as follows −

$ javac HelloForm.java

If everything goes fine, above compilation would produce HelloForm.class file. Next you would have
to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create
following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-
INF/

<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your browser's
Location:box and make sure you already started tomcat server, before firing above command in the
browser. This would generate following result −

Using GET Method to Read Form Data

 First Name: ZARA

 Last Name: ALI

GET Method Example Using Form


Here is a simple example which passes two values using HTML FORM and submit button. We are going
to use same Servlet HelloForm to handle this input.

<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Keep this HTML in a file Hello.htm and put it in <Tomcat-installationdirectory>/webapps/ROOT
directory. When you would access http://localhost:8080/Hello.htm, here is the actual output of the above
form.

First Name: Last Name:

Try to enter First Name and Last Name and then click submit button to see the result on your local
machine where tomcat is running. Based on the input provided, it will generate similar result as
mentioned in the above example.

POST Method Example Using Form

Let us do little modification in the above servlet, so that it can handle GET as well as POST methods.
Below is HelloForm.java servlet program to handle input given by web browser using GET or POST
methods.

// Import required java libraries


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

// Extend HttpServlet class


public class HelloForm extends HttpServlet {

// Method to handle GET method request.


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

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
}

// Method to handle POST method request.


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}
Now compile and deploy the above Servlet and test it using Hello.htm with the POST method as follows

<html>
<body>
<form action = "HelloForm" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Here is the actual output of the above form, Try to enter First and Last Name and then click submit button
to see the result on your local machine where tomcat is running.

First Name: Last Name:


Based on the input provided, it would generate similar result as mentioned in the above examples.
Passing Checkbox Data to Servlet Program
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<html>
<body>
<form action = "CheckBox" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" />
Chemistry
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
The result of this code is the following form
Maths Physics Chemistry
Given below is the CheckBox.java servlet program to handle input given by web browser for checkbox
button.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class CheckBox extends HttpServlet {

// Method to handle GET method request.


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

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Reading Checkbox Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>Maths Flag : </b>: "
+ request.getParameter("maths") + "\n" +
" <li><b>Physics Flag: </b>: "
+ request.getParameter("physics") + "\n" +
" <li><b>Chemistry Flag: </b>: "
+ request.getParameter("chemistry") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
}

// Method to handle POST method request.


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}
For the above example, it would display following result −
Reading Checkbox Data
 Maths Flag : : on

 Physics Flag: : null

 Chemistry Flag: : on

Reading All Form Parameters

Following is the generic example which uses getParameterNames() method of HttpServletRequest to


read all the available form parameters. This method returns an Enumeration that contains the parameter
names in an unspecified order

Once we have an Enumeration, we can loop down the Enumeration in standard way by,
using hasMoreElements() method to determine when to stop and using nextElement() method to get each
parameter name.

// Import required java libraries


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

// Extend HttpServlet class


public class ReadParams extends HttpServlet {

// Method to handle GET method request.


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

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Reading All Form Parameters";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
Enumeration paramNames = request.getParameterNames();

while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);

// Read single valued data


if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");

for(int i = 0; i < paramValues.length; i++) {


out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}

// Method to handle POST method request.


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doGet(request, response);
}
}
Now, try the above servlet with the following form −
<html>
<body>
<form action = "ReadParams" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chem
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>

Now calling servlet using the above form would generate the following result −

Reading All Form Parameters


Param Name Param Value(s)

maths on

chemistry on

You can try the above servlet to read any other form's data having other objects like text box, radio button
or drop down box etc.

Session Tracking in Servlets

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of a 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 a
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

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.

Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.

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

Table: 2.15

Constructor Description

Cookie() constructs a cookie.

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


String value)

Useful Methods of Cookie class

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

Table: 2.16

Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot be
changed after creation.

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

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

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.

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


ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

How to get Cookies?

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

Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
}
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

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


Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

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

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object


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

//creating submit button


out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

out.close();

}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

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

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

out.close();

}catch(Exception e){System.out.println(e);}
}

}
web.xml

<web-app>
<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>FirstServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>s2</servlet-name>

<servlet-class>SecondServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s2</servlet-name>

<url-pattern>/servlet2</url-pattern>

</servlet-mapping>

</web-app>

Output
Servlet Capabilities

Of these, HTTP servlets have some additional objects that provide session-tracking capabilities, the
servlet writer can use the HttpSession interface to maintain the state of a client between client requests
upto some time period. The capability of maintaining cookies is also provided by the HTTP servlets, The
servlet writer uses the Cookie class to save small bits of information within the client machine, which
can be retrieved at request processing time

Servlet Concurrency

A Java servlet container / web server is typically multithreaded. That means, that multiple requests to the
same servlet may be executed at the same time. Therefore, you need to take concurrency into
consideration when you implement your servlet.

To make sure that a servlet is thread safe, there are a few basic rules of thumb you must follow:

Your servlet service() method should not access any member variables, unless these member variables
are thread safe themselves.

Your servlet service() should not reassign member variables, as this may affect other threads executing
inside the service() method. If you really, really need to reassign a member variable, make sure this is
done inside a synchronized block.

Rule 1 and 2 also counts for static variables.

Local variables are always thread safe. Keep in mind though, that the object a local variable points to,
may not be so. If the object was instantiated inside the method, and never escapes, there will be no
problem. On the other hand, a local variable pointing to some shared object, may still cause problems.
Just because you assign a shared object to a local reference, does not mean that object automatically
becomes thread safe.

The request and response objects are of course thread safe to use. A new instance of these are created for
every request into your servlet, and thus for every thread executing in your servlet.

Here is a diagram which illustrates the servlet concurrency rules / issues mentioned above. The red boxes
represent state (variables) that your servlet's service() method should be careful about accessing.
Fig.: 2.7 Servlet concurrency rule

Java Servlet Concurrency Rules.

Other Shared Resources

Of course it is not only the member variables and static variables inside the servlet class itself, that you
need to be careful about accessing. Static variables in any other class which are accessed by your servlet,
must also be thread safe. The same is true for member variables of any shared objects accessed by your
servlet.

Code Example

Here is a code example that shows you some of the rules.

public class SimpleHttpServlet extends HttpServlet {


// Not thread safe, static.
protected static List list = new ArrayList();

// Not thread safe


protected Map map = new HashMap();

// Thread safe to access object, not thread safe to reassign variable.


protected Map map = new ConcurrentHashMap();

// Thread safe to access object (immutable), not thread safe to reassign variable.
protected String aString = "a string value";

protected void doGet( HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// Not thread safe, unless the singleton is 100% thread safe.


SomeClass.getSomeStaticSingleton();

// Thread safe, locally instantiated, and never escapes method.


Set set = new HashSet();

}
}

JSP (Java Server Pages):


JSP refers to the java server pages. 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 defines a structure which is java code inside HTML code.
With this structure it simplifies the web development.

Problems in servlet:
1. In servlet presentation logic and dynamic content generation logic are intermixed which result
into maintains problem.

2. Every time when presentation is changed servlet needs to compile and deploy again.

3. A developer needs to write HTML code to the output stream of the servlet.

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.

The Lifecycle of a JSP Page

The JSP pages follow these phases:


o Translation of JSP Page

o Compilation of JSP Page

o Classloading (the classloader loads class file)

o Instantiation (Object of the Generated Servlet is created).

o Initialization ( the container invokes jspInit() method).


o Request processing ( the container invokes _jspService() method).

o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

Fig.: 2.8 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.

<html>
<body>
<% out.print(2*5); %>
</body>
</html>

It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:


o Start the server

o Put the JSP file in a folder and deploy on the server

o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,


http://localhost:8888/myapplication/index.jsp
Do I need to follow the directory structure to run a simple JSP?

No, there is no need of directory structure if you don't have class files or TLD files. For example, put
JSP files in a folder directly and deploy that folder. It will be running fine. However, if you are using
Bean class, Servlet or TLD file, the directory structure is required.
The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB-INF
folder or in any directory.

The JSP API

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:


o JspWriter

o PageContext

o JspFactory

o JspEngineInfo

o JspException

o 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

JSP Scriptlet tag (Scripting elements)

In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what the scripting
elements are first.

JSP Scripting elements

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

o expression tag
o declaration tag

JSP scriptlet tag

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

Example of JSP scriptlet tag

In this example, we are displaying a welcome message.

<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</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

<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

File: welcome.jsp

<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</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
<%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</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

<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</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

<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>

File: welcome.jsp

<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>

JSP Declaration Tag

The JSP declaration tag is used to declare fields and methods.


The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet. So it doesn't get memory at each request.

Syntax of JSP declaration tag


The syntax of the declaration tag is as follows:
<%! field or method declaration %>
Difference between JSP Scriptlet tag and Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variables as
methods. well as methods.

The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is placed
_jspService() method. outside the _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the declared
field using the jsp expression tag.

index.jsp

<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of given
number and calling this method from the jsp expression tag. But we can also use jsp scriptlet tag to call
the declared method.

index.jsp

<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

JSP Implicit Objects

There are 9 jsp implicit objects. These objects are created by the web container that are available to all
the jsp pages. The available implicit objects are out, request, config, session, application etc.

Table 2.15 list of the 9 implicit objects

Object Type

out JspWriter
request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

1. exception 2. 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:
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

<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

Output

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:
o page directive
o include directive

o taglib directive

Syntax of JSP Directive


<%@ directive attribute="value" %>

JSP page directive


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

Syntax of JSP page directive


<%@ page attribute="value" %>

Attributes of JSP page directive


o import

o contentType

o extends

o info

o buffer

o language

o isELIgnored

o isThreadSafe

o autoFlush

o session

o pageEncoding

o errorPage

o 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
interface.
Example of import attribute
<html>
<body>

<%@ page import="java.util.Date" %>


Today is: <%= new Date() %>

</body>
</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
<html>
<body>

<%@ page contentType=application/msword %>


Today is: <%= new java.util.Date() %>

</body>
</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
<html>
<body>

<%@ page info="composed by Sonoo Jaiswal" %>


Today is: <%= new java.util.Date() %>

</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet.For example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}

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
<html>
<body>

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


Today is: <%= new java.util.Date() %>

</body>
</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. Express
enabled by default. We see Expression Language later.
<%@ 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 a
directive.The value of isThreadSafe value is true.If you make it false, the web container will serialize the multiple requests
until the JSP finishes responding to a request before passing another request to it.If you make the value of isThreadSafe at
<%@ page isThreadSafe="false" %>

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

public class SimplePage_jsp extends HttpJspBase


implements SingleThreadModel{
.......
}

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
//index.jsp
<html>
<body>

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

<%= 100/0 %>

</body>
</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
//myerrorpage.jsp
<html>
<body>

<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>


The exception is: <%= exception %>

</body>
</html>

Jsp 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

<%@ 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.
<html>
<body>

<%@ include file="header.html" %>

Today is: <%= java.util.Calendar.getInstance().getTime() %>

</body>
</html>

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

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 of JSP Taglib directive
<%@ 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.
<html>
<body>

<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>

<mytag:currentDate/>

</body>
</html>

Custom Tags in JSP

Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and separates the
business logic from the JSP page.
The same business logic can be used many times by the use of custom tag.
Advantages of Custom Tags
The key advantages of Custom tags are as follows:
1. Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet tag which
is considered bad programming approach in JSP.

2. Separation of business logic from JSP The custom tags separate the the business logic from
the JSP page so that it may be easy to maintain.

3. Re-usability The custom tags makes the possibility to reuse the same business logic again and
again.

Syntax to use custom tag


There are two ways to use the custom tag. They are given below:

<prefix:tagname attr1=value1....attrn=valuen />

<prefix:tagname attr1=value1....attrn=valuen >


body code
</prefix:tagname>

JSP Custom Tag API

The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom tag API. The JspTag
is the root interface in the Custom Tag hierarchy.

Fig.2.9 Jsp Tag

JspTag interface
The JspTag is the root interface for all the interfaces and classes used in custom tag. It is a marker
interface.

Tag interface
The Tag interface is the sub interface of JspTag interface. It provides methods to perform action at the
start and end of the tag.

Fields of Tag interface


There are four fields defined in the Tag interface. They are:
Table: 2.16 Tag Interface

Field Name Description

public static int EVAL_BODY_INCLUDE it evaluates the body content.

public static int EVAL_PAGE it evaluates the JSP page content after the custom tag.

public static int SKIP_BODY it skips the body content of the tag.

public static int SKIP_PAGE it skips the JSP page content after the custom tag.

Fig. 2.17 : Methods of Tag interface

Method Name Description

public void it sets the given PageContext object.


setPageContext(PageContext pc)

public void setParent(Tag t) it sets the parent of the tag handler.

public Tag getParent() it returns the parent tag handler object.

public int doStartTag()throws it is invoked by the JSP page implementation object. The JSP
JspException programmer should override this method and define the
business logic to be performed at the start of the tag.

public int doEndTag()throws it is invoked by the JSP page implementation object. The JSP
JspException programmer should override this method and define the
business logic to be performed at the end of the tag.

public void release() it is invoked by the JSP page implementation object to release
the state.

IterationTag interface
The IterationTag interface is the sub interface of the Tag interface. It provides an additional method to
reevaluate the body.

Field of IterationTag interface


There is only one field defined in the IterationTag interface.
o public static int EVAL_BODY_AGAIN it reevaluates the body content.

Method of Tag interface


There is only one method defined in the IterationTag interface.
o public int doAfterBody()throws JspException it is invoked by the JSP page implementation
object after the evaluation of the body. If this method returns EVAL_BODY_INCLUDE, body
content will be reevaluated, if it returns SKIP_BODY, no more body cotent will be evaluated.
TagSupport class
The TagSupport class implements the IterationTag interface. It acts as the base class for new Tag
Handlers. It provides some additional methods also.

Example of JSP Custom Tag

In this example, we are going to create a custom tag that prints the current date and time. We are
performing action at the start of tag.
For creating any custom tag, we need to follow following steps:
1. Create the Tag handler class and perform action at the start or at the end of the tag.

2. Create the Tag Library Descriptor (TLD) file and define tags

3. Create the JSP file that uses the Custom tag defined in the TLD file

Understanding flow of custom tag in jsp

1) Create the Tag handler class

To create the Tag Handler, we are inheriting the TagSupport class and overriding its
method doStartTag().To write data for the jsp, we need to use the JspWriter class.
The PageContext class provides getOut() method that returns the instance of JspWriter class.
TagSupport class provides instance of pageContext bydefault.

File: MyTagHandler.java

package com.javatpoint.sonoo;
import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class MyTagHandler extends TagSupport{

public int doStartTag() throws JspException {


JspWriter out=pageContext.getOut();//returns the instance of JspWriter
try{
out.print(Calendar.getInstance().getTime());//printing date and time using JspWriter
}catch(Exception e){System.out.println(e);}
return SKIP_BODY;//will not evaluate the body content of the tag
}
}

2) Create the TLD file

Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be
contained inside the WEB-INF directory.

File: mytags.tld

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


<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>

<tag>
<name>today</name>
<tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>
</tag>
</taglib>

3) Create the JSP file

Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But it is recommended
to use the uri name instead of full path of tld file. It uses taglib directive to use the tags defined in the tld
file.

File: index.jsp

<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>


Current Date and Time is: <m:today/>

Output
Question Bank

1. What is JavaScript?

JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages
and is understood by web browsers. JavaScript is also an Object based Programming language

2. Enumerate the differences between Java and JavaScript?

Java is a complete programming language. In contrast, JavaScript is a coded program that can be
introduced to HTML pages. These two languages are not at all inter-dependent and are designed for the
different intent. Java is an object - oriented programming (OOPS) or structured programming language
like C++ or C whereas JavaScript is a client-side scripting language.

3. What are JavaScript Data Types?

Following are the JavaScript Data types:

 Number
 String
 Boolean
 Object
 Undefined

4. What is the use of isNaN function?

isNan function returns true if the argument is not a number otherwise it is false.

5. Between JavaScript and an ASP script, which is faster?

JavaScript is faster. JavaScript is a client-side language and thus it does not need the assistance of the
web server to execute. On the other hand, ASP is a server-side language and hence is always slower than
JavaScript. Javascript now is also a server side language (nodejs).

6. What is negative infinity?

Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.

7. Is it possible to break JavaScript Code into several lines?

Breaking within a string statement can be done by the use of a backslash, '\', at the end of the first line

Example:

8. Which company developed JavaScript?

Netscape is the software company who developed JavaScript.

9. What are undeclared and undefined variables?


Undeclared variables are those that do not exist in a program and are not declared. If the program tries
to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the
program tries to read the value of an undefined variable, an undefined value is returned.

10. Write the code for adding new elements dynamically?

<html>
<head>
<title>t1</title>
<script type="text/javascript">
function addNode() { var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); }
</script> </head>
<body> <p id="firstP">firstP<p> </body>
</html>

11. What are global variables? How are these variable declared and what are the problems
associated with using them?

Global variables are those that are available throughout the length of the code, that is, these have no
scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a
global variable is declared.

Example:

// Declare a global globalVariable = "Test";

The problems that are faced by using global variables are the clash of variable names of local and global
scope. Also, it is difficult to debug and test the code that relies on global variables.

12. What is a prompt box?

A prompt box is a box which allows the user to enter input by providing a text box. Label and box will
be provided to enter the text or number.

13. What is 'this' keyword in JavaScript?

'This' keyword refers to the object from where it was called.

14. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer,
if any?

Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of
time. This is done by using the functions setTimeout, setInterval and clearInterval.

The setTimeout(function, delay) function is used to start a timer that calls a particular function after the
mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given
function in the mentioned delay and only halts when cancelled. The clearInterval(id) function instructs
the timer to stop.
Timers are operated within a single thread, and thus events might queue up, waiting to be executed.

15. Which symbol is used for comments in Javascript?

// for Single line comments and

/* Multi

Line

Comment

*/

16. What is the difference between ViewState and SessionState?

'ViewState' is specific to a page in a session.

'SessionState' is specific to user specific data that can be accessed across all pages in the web application.

17. What is === operator?

=== is called as strict equality operator which returns true when the two operands are having the same
value without any type conversion.

18. Explain how can you submit a form using JavaScript?

To submit a form using JavaScript use document.form[0].submit();

document.form[0].submit();

19. Does JavaScript support automatic type conversion?

Yes JavaScript does support automatic type conversion, it is the common way of type conversion used
by JavaScript developers

20. How can the style/class of an element be changed?

It can be done in the following way:

document.getElementById("myText").style.fontSize = "20?;

or

document.getElementById("myText").className = "anyclass";

21. Explain how to read and write a file using JavaScript?

There are two ways to read and write a file using JavaScript

 Using JavaScript extensions


 Using a web page and Active X objects

22. What are all the looping structures in JavaScript?

Following are looping structures in Javascript:

 For
 While
 do-while loops

23. What is called Variable typing in Javascript?

Variable typing is used to assign a number to a variable and the same variable can be assigned to a string.

Example

i = 10;
i = "string";

This is called variable typing.

24. How can you convert the string of any base to integer in JavaScript?

The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to
be converted as its first parameter, and the second parameter is the base of the given string.

In order to convert 4F (of base 16) to integer, the code used will be -

parseInt ("4F", 16);

25. Explain the difference between "==" and "==="?

"==" checks only for equality in value whereas "===" is a stricter equality test and returns false if either
the value or the type of the two variables are different.

26. What would be the result of 3+2+"7"?

Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will
be done. So the result would be 57.

27. Explain how to detect the operating system on the client machine?

In order to detect the operating system on the client machine, the navigator.platform string (property)
should be used.

28. What do mean by NULL in Javascript?

The NULL value is used to represent no value or no object. It implies no object or null string, no valid
boolean value, no number and no array object.

29. What is the function of delete operator?


The delete keyword is used to delete the property as well as its value.

Example

var student= {age:20, batch:"ABC"};


delete student.age;

30. What is an undefined value in JavaScript?

Undefined value means the

 Variable used in the code doesn't exist


 Variable is not assigned to any value
 Property doesn't exist

31. What are all the types of Pop up boxes available in JavaScript?

 Alert
 Confirm and
 Prompt

32. What is the use of Void(0)?

Void(0) is used to prevent the page from refreshing and parameter "zero" is passed while calling.

Void(0) is used to call another method without refreshing the page.

33. How can a page be forced to load another page in JavaScript?

The following code has to be inserted to achieve the desired effect:

<script language="JavaScript" type="text/javascript" >

<!-- location.href="http://newhost/newpath/newfile.html"; //--></script>

34. What is the data type of variables of in JavaScript?

All variables in the JavaScript are object data types.

35. What is the difference between an alert box and a confirmation box?

An alert box displays only one button which is the OK button.

But a Confirmation box displays two buttons namely OK and cancel.

36. What are escape characters?

Escape characters (Backslash) is used when working with special characters like single quotes, double
quotes, apostrophes and ampersands. Place backslash before the characters to make it display.

Example:
document.write "I m a "good" boy"
document.write "I m a \"good\" boy"

37. What are JavaScript Cookies?

Cookies are the small test files stored in a computer and it gets created when the user visits the websites
to store information that they need. Example could be User Name details and shopping cart information
from the previous visits.

38. Explain what is pop()method in JavaScript?

The pop() method is similar as the shift() method but the difference is that the Shift method works at the
start of the array. Also the pop() method take the last element off of the given array and returns it. The
array on which is called is then altered.

Example:

var cloths = ["Shirt", "Pant", "TShirt"];


cloths.pop();

//Now cloth becomes Shirt,Pant

39. Whether JavaScript has concept level scope?

No. JavaScript does not have concept level scope. The variable declared inside the function has scope
inside the function.

40. Mention what is the disadvantage of using innerHTML in JavaScript?

If you use innerHTML in JavaScript the disadvantage is

 Content is replaced everywhere


 We cannot use like "appending to innerHTML"
 Even if you use +=like "innerHTML = innerHTML + 'html'" still the old content is replaced by
html
 The entire innerHTML content is re-parsed and build into elements, therefore its much slower
 The innerHTML does not provide validation and therefore we can potentially insert valid and
broken HTML in the document and break it

41. What is break and continue statements?

Break statement exits from the current loop.

Continue statement continues with next statement of the loop.

42. What are the two basic groups of dataypes in JavaScript?

They are as –

 Primitive
 Reference types.
Primitive types are number and Boolean data types. Reference types are more complex types like strings
and dates.

43. How generic objects can be created?

Generic objects can be created as:

var I = new object();

44. What is the use of type of operator?

'Typeof' is an operator which is used to return a string description of the type of a variable.

45. Which keywords are used to handle exceptions?

Try… Catch---finally is used to handle exceptions in the JavaScript

Try{
Code
}
Catch(exp){
Code to throw an exception
}
Finally{
Code runs either it finishes successfully or after catch
}

46. Which keyword is used to print the text in the screen?

document.write("Welcome") is used to print the text – Welcome in the screen.

47. What is the use of blur function?

Blur function is used to remove the focus from the specified object.

48. What is variable typing?

Variable typing is used to assign a number to a variable and then assign string to the same variable.
Example is as follows:

i= 8;
i="john";

49. How to find operating system in the client machine using JavaScript?

The 'Navigator.appversion' is used to find the name of the operating system in the client machine.

50. What are the different types of errors in JavaScript?

There are three types of errors:


 Load time errors: Errors which come up when loading a web page like improper syntax errors
are known as Load time errors and it generates the errors dynamically.
 Run time errors: Errors that come due to misuse of the command inside the HTML language.
 Logical Errors: These are the errors that occur due to the bad logic performed on a function
which is having different operation.

51. What is the use of Push method in JavaScript?

The push method is used to add or append one or more elements to the end of an Array. Using this
method, we can append multiple elements by passing multiple arguments

52. What is unshift method in JavaScript?

Unshift method is like push method which works at the beginning of the array. This method is used to
prepend one or more elements to the beginning of the array.

53. What is the difference between JavaScript and Jscript?

Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft .

54. How are object properties assigned?

Properties are assigned to objects in the following way -

obj["class"] = 12;

or

obj.class = 12;

55. What is the 'Strict' mode in JavaScript and how can it be enabled?

Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for
a piece of codes, which did not show an error before, but might be problematic and potentially unsafe.
Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.

Strict mode can be enabled by adding the string literal "use strict" above the file. This can be illustrated
by the given example:

function myfunction() {
"use strict";
var v = "This is a strict mode function";
}

56. What is the way to get the status of a CheckBox?

The status can be acquired as follows -

alert(document.getElementById('checkbox1').checked);

If the CheckBox will be checked, this alert will return TRUE.


57. How can the OS of the client machine be detected?

The navigator.appVersion string can be used to detect the operating system on the client machine.

58. Explain window.onload and onDocumentReady?

The onload function is not run until all the information on the page is loaded. This leads to a substantial
delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the
code.

59. How will you explain closures in JavaScript? When are they used?

Closure is a locally declared variable related to a function which stays in memory when the function has
returned.

For example:

function greet(message) {

console.log(message);

function greeter(name, age) {

return name + " says howdy!! He is " + age + " years old";

// Generate the message

var message = greeter("James", 23);

// Pass it explicitly to greet

greet(message);

This function can be better represented by using closures

function greeter(name, age) {

var message = name + " says howdy!! He is " + age + " years old";

return function greet() {

console.log(message);

};

}
// Generate the closure

var JamesGreeter = greeter("James", 23);

// Use the closure

JamesGreeter();

60. How can a value be appended to an array?

A value can be appended to an array in the given manner -

arr[arr.length] = value;

61. Explain the for-in loop?

The for-in loop is used to loop through the properties of an object.

The syntax for the for-in loop is -

for (variable name in object){


statement or block to execute
}

In each repetition, one property from the object is associated to the variable name, and the loop is
continued till all the properties of the object are depleted.

62. Describe the properties of an anonymous function in JavaScript?

A function that is declared without any named identifier is known as an anonymous function. In general,
an anonymous function is inaccessible after its declaration.

Anonymous function declaration -

var anon = function() {


alert('I am anonymous');
};
anon();

63. What is the difference between .call() and .apply()?

The function .call() and .apply() are very similar in their usage except a little difference. .call() is used
when the number of the function's arguments are known to the programmer, as they have to be mentioned
as arguments in the call statement. On the other hand, .apply() is used when the number is not known.
The function .apply() expects the argument to be an array.

The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their
usage can be illustrated by the given example.

var someObject = {
myProperty : 'Foo',

myMethod : function(prefix, postfix) {

alert(prefix + this.myProperty + postfix);


}
};
someObject.myMethod('<', '>'); // alerts '<Foo>'
var someOtherObject = {

myProperty : 'Bar'

};
someObject.myMethod.call(someOtherObject, '<', '>'); // alerts '<Bar>'

someObject.myMethod.apply(someOtherObject, ['<', '>']); // alerts '<Bar>'

64. Define event bubbling?

JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child
is clicked, the handler of parent will also work as if it were clicked too.

65. Is JavaScript case sensitive? Give an example?

Yes, JavaScript is case sensitive. For example, a function parseInt is not same as the function Parseint.

66. What boolean operators can be used in JavaScript?

The 'And' Operator (&&), 'Or' Operator (||) and the 'Not' Operator (!) can be used in JavaScript.

*Operators are without the parenthesis.

67. How can a particular frame be targeted, from a hyperlink, in JavaScript?

This can be done by including the name of the required frame in the hyperlink using the 'target' attribute.

<a href="/newpage.htm" target="newframe">>New Page</a>

68. What is the role of break and continue statements?

Break statement is used to come out of the current loop while the continue statement continues the current
loop with a new recurrence.

69. Write the point of difference between web-garden and a web-farm?

Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a
setup that includes many processors in a single server while web-farm is a larger setup that uses more
than one server.

70. How are object properties assigned?


Assigning properties to objects is done in the same way as a value is assigned to a variable. For example,
a form object's action value is assigned as 'submit' in the following manner -
Document.form.action="submit"

71. What is the method for reading and writing a file in JavaScript?

This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of
a file -

fh = fopen(getScriptPath(), 0);

72. How are DOM utilized in JavaScript?

DOM stands for Document Object Model and is responsible for how various objects in a document
interact with each other. DOM is required for developing web pages, which includes objects like
paragraph, links, etc. These objects can be operated to include actions like add or delete. DOM is also
required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over
other existing models.

73. How are event handlers utilized in JavaScript?

Events are the actions that result from activities, such as clicking a link or filling a form, by the user. An
event handler is required to manage proper execution of all these events. Event handlers are an extra
attribute of the object. This attribute includes event's name and the action taken if the event takes place.

74. Explain the role of deferred scripts in JavaScript?

By default, the parsing of the HTML code, during page loading, is paused until the script has not stopped
executing. It means, if the server is slow or the script is particularly heavy, then the webpage is displayed
with a delay. While using Deferred, scripts delays execution of the script till the time HTML parser is
running. This reduces the loading time of web pages and they get displayed faster.

75. What are the various functional components in JavaScript?

The different functional components in JavaScript are-

First-class functions: Functions in JavaScript are utilized as first class objects. This usually means that
these functions can be passed as arguments to other functions, returned as values from other functions,
assigned to variables or can also be stored in data structures.

Nested functions: The functions, which are defined inside other functions, are called Nested functions.
They are called 'everytime' the main function is invoked.

76. Write about the errors shown in JavaScript?

JavaScript gives a message if it encounters an error. The recognized errors are -

 Load-time errors: The errors shown at the time of the page loading are counted under Load-time
errors. These errors are encountered by the use of improper syntax, and thus are detected while
the page is getting loaded.
 Run-time errors: This is the error that comes up while the program is running. It is caused by
illegal operations, for example, division of a number by zero, or trying to access a non-existent
area of the memory.
 Logic errors: It is caused by the use of syntactically correct code, which does not fulfill the
required task. For example, an infinite loop.

77. What are Screen objects?

Screen objects are used to read the information from the client's screen. The properties of screen objects
are -

 AvailHeight: Gives the height of client's screen


 AvailWidth: Gives the width of client's screen.
 ColorDepth: Gives the bit depth of images on the client's screen
 Height: Gives the total height of the client's screen, including the taskbar
 Width: Gives the total width of the client's screen, including the taskbar

78. Explain the unshift() method ?

This method is functional at the starting of the array, unlike the push(). It adds the desired number of
elements to the top of an array. For example -

var name = [ "john" ];


name.unshift( "charlie" );
name.unshift( "joseph", "Jane" );
console.log(name);

The output is shown below:

[" joseph "," Jane ", " charlie ", " john "]

79. Define unescape() and escape() functions?

The escape () function is responsible for coding a string so as to make the transfer of the information
from one computer to the other, across a network.

For Example:

<script>
document.write(escape("Hello? How are you!"));
</script>

Output: Hello%3F%20How%20are%20you%21

The unescape() function is very important as it decodes the coded string.

It works in the following way. For example:

<script>
document.write(unescape("Hello%3F%20How%20are%20you%21"));
</script>
Output: Hello? How are you!

80. What are the decodeURI() and encodeURI()?

EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the
encoded URL back to normal.

<script>
var uri="my test.asp?name=ståle&car=saab";

document.write(encodeURI(uri)+ "<br>");

document.write(decodeURI(uri));
</script>

Output -

my%20test.asp?name=st%C3%A5le&car=saab

my test.asp?name=ståle&car=saab

81. Why it is not advised to use innerHTML in JavaScript?

innerHTML content is refreshed every time and thus is slower. There is no scope for validation in
innerHTML and, therefore, it is easier to insert rouge code in the document and, thus, make the web page
unstable.

82. What does the following statement declares?

var myArray = [[[]]];

It declares a three dimensional array.

83. How are JavaScript and ECMA Script related?

ECMA Script are like rules and guideline while Javascript is a scripting language used for web
development.

84. What is namespacing in JavaScript and how is it used?

Namespacing is used for grouping the desired functions, variables etc. under a unique name. It is a name
that has been attached to the desired functions, objects and properties. This improves modularity in the
coding and enables code reuse.

85. How can JavaScript codes be hidden from old browsers that don't support JavaScript?

For hiding JavaScript codes from old browsers:

Add "<!--" without the quotes in the code just after the <script> tag.

Add "//-->" without the quotes in the code just before the <script> tag.
Old browsers will now treat this JavaScript code as a long HTML comment. While, a browser that
supports JavaScript, will take the "<!--" and "//-->" as one-line comments.

Q86. What are Servlets?


Ans. Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a request coming from a Web browser or other HTTP client and databases or applications
on the HTTP server.

Q87. What are the advantages of servlets over CGI? What are the major tasks of servlets?
Ans. Servlets perform the following major tasks:
 Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.

 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media
types and compression schemes the browser understands, and so forth.

 Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response directly.

 Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent
in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.

 Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or
other clients what type of document is being returned (e.g., HTML), setting cookies and caching
parameters, and other such tasks.

Q88. Explain servlet life cycle.


Ans. A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet.
 The servlet is initialized by calling the init () method.

 The servlet calls service() method to process a client's request.

 The servlet is terminated by calling the destroy() method.

 Finally, servlet is garbage collected by the garbage collector of the JVM.

Q89. When init() method of servlet gets called?


Ans. The init method is designed to be called only once. It is called when the servlet is first created, and
not called again for each user request. So, it is used for one-time initializations, just as with the init
method of applets.

Q90. When service() method of servlet gets called?


Ans. Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Q91. When doGet() method of servlet to be called?


Ans. A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.

Q92. For what purpose init() method of a servlet is used?


Ans. The init() method simply creates or loads some data that will be used throughout the life of the
servlet.
Q93. For what purpose doGet() method of a servlet is used?
Ans. This method should be used to get data from server.

Q94. Explain working of service() method of a servlet.


Ans. The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write
the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls service.
The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGe, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from the client.

Q95. How to read form data in servlet?


Ans. Servlets handles form data parsing automatically using the following methods depending on the
situation:
 getParameter(): You call request.getParameter() method to get the value of a form parameter.

 getParameterValues(): Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.

 getParameterNames(): Call this method if you want a complete list of all parameters in the
current request.

Q96. How to read name of all parameters in servlet?


Ans. getParameterNames() method of HttpServletRequest returns complete list of all parameters in the
current request. This method returns an Enumeration that contains the parameter names in an unspecified
order.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using
hasMoreElements() method to determine when to stop and using nextElement() method to get each
parameter name.

Q97. How to read http header information in servlet?What is HTTPServletRequest class?


Ans. When a browser requests for a web page, it sends lot of information to the web server which can
not be read directly because this information travel as a part of header of HTTP request.
HTTPServletRequest represents this HTTP Request.

Q98. What is HTTPServletResponse class?


Ans. When a Web server responds to a HTTP request to the browser, the response typically consists of
a status line, some response headers, a blank line, and the document. HTTPServletResponse represents
this HTTP Response.

Q99. How to redirect a request from a servlet to another servlet?


Ans. Page redirection is generally used when a document moves to a new location and we need to send
the client to this new location or may be because of load balancing, or for simple randomization. The
simplest way of redirecting a request to another page is using method sendRedirect() of response object.

Q100. How to create a cookie using servlet?


Ans. Setting cookies with servlet involves three steps:
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value,
both of which are strings.
Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of the following
characters: [ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should
be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in
the HTTP response header as follows:
response.addCookie(cookie);

Q101. What is session?


Ans. Session provides a way to identify a user across more than one page request or visit to a Web site
and to store information about that user. The session persists for a specified time period, across more
than one connection or page request from the user.

Q102. What is URL rewriting?


Ans. You can append some extra data on the end of each URL that identifies the session, and the server
can associate that session identifier with data it has stored about that session. For example, with
http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345
which can be accessed at the web server to identify the client.

Q103. How to update an attribute in session in servlet?


Ans. setAttribute(String name, Object value) of HTTPSession object binds an object to this session,
using the name specified and can be used to update an attribute in session.

Q104. What is JSP?


Ans. JavaServer Pages (JSP) is a technology for developing Webpages that support dynamic content
which helps developers insert java code in HTML pages by making use of special JSP tags, most of
which start with <% and end with %>.

Q105. What are advantages of using JSP?


Ans. JSP offer several advantages as listed below −
 Performance is significantly better because JSP allows embedding Dynamic Elements in HTML
Pages itself.

 JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the
server to load an interpreter and the target script each time the page is requested.

 JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access
to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.

 JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.

Q106. What are the advantages of JSP over Active Server Pages (ASP)?
Ans. The advantages of JSP are twofold.
First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more
powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.

Q107.What are the advantages of JSP over Pure Servlets?


Ans. It is more convenient to write (and to modify!) regular HTML than to have plenty of println
statements that generate the HTML. Other advantages are −
 Embedding of Java code in HTML pages.

 Platform independence.

 Creation of database-driven Web applications.

 Server-side programming capabilities.

Q108. What are the advantages of JSP over Server-Side Includes (SSI)?
Ans. SSI is really only intended for simple inclusions, not for "real" programs that use form data, make
database connections, and the like.

Q109.What are the advantages of JSP over JavaScript?


Ans. JavaScript can generate HTML dynamically on the client but can hardly interact with the web
server to perform complex tasks like database access and image processing etc.

Q110.What are the advantages of JSP over Static HTML?


Ans. Regular HTML, of course, cannot contain dynamic information.

Q111. Explain lifecycle of a JSP.


Ans. A JSP Lifecycle consists of following steps −
 Compilation − When a browser asks for a JSP, the JSP engine first checks to see whether it
needs to compile the page. If the page has never been compiled, or if the JSP has been modified
since it was last compiled, the JSP engine compiles the page.

The compilation process involves three steps −


o Parsing the JSP.

o Turning the JSP into a servlet.

o Compiling the servlet.

 Initialization − When a container loads a JSP it invokes the jspInit() method before servicing
any requests

 Execution − Whenever a browser requests a JSP and the page has been loaded and initialized,
the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP
is invoked once per a request and is responsible for generating the response for that request and
this method is also responsible for generating responses to all seven of the HTTP methods ie.
GET, POST, DELETE etc.

 Cleanup − The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method
for servlets.

Q112. What is a sciptlet in JSP and what is its syntax?


Ans. A scriptlet can contain any number of JAVA language statements, variable or method declarations,
or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet −
<% code fragment %>

Q113. What are JSP declarations?


Ans. A declaration declares one or more variables or methods that you can use in Java code later in the
JSP file. You must declare the variable or method before you use it in the JSP file.
<%! declaration; [ declaration; ]+ ... %>

Q114. What are JSP expressions?


Ans. A JSP expression element contains a scripting language expression that is evaluated, converted to
a String, and inserted where the expression appears in the JSP file.
The expression element can contain any expression that is valid according to the Java Language
Specification but you cannot use a semicolon to end an expression.
Its syntax is −
<%= expression %>

Q115. What are JSP comments?


Ans. JSP comment marks text or statements that the JSP container should ignore. A JSP comment is
useful when you want to hide or "comment out" part of your JSP page.
Following is the syntax of JSP comments −
<%-- This is JSP comment --%>

Q116. What are JSP Directives?


Ans. A JSP directive affects the overall structure of the servlet class. It usually has the following form

<%@ directive attribute = "value" %>

Q117. What are the types of directive tags?


Ans. The types directive tags are as follows −
 <%@ page ... %> − Defines page-dependent attributes, such as scripting language, error page,
and buffering requirements.

 <%@ include ... %> − Includes a file during the translation phase.

 <%@ taglib ... %> − Declares a tag library, containing custom actions, used in the page.

Q118. What are JSP actions?


Ans. JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.
Its syntax is as follows −
<jsp:action_name attribute = "value" />

Q119. What is the difference between include action and include directive?
Ans. Unlike the include directive, which inserts the file at the time the JSP page is translated into a
servlet, include action inserts the file at the time the page is requested.

Exercises

1. When doPost() method of servlet to be called?


2. When destroy() method of servlet gets called?
3. For what purpose destroy() method of a servlet is used?
4. For what purpose doPost() method of a servlet is used?
5. How to write html contents using servlets?
6. How to send an authentication error from a servlet?
7. How sendRedirect method works?
8. How sendError method works?
9. What are servlets filters?
10. How to configure a central error handling page in servlets?
11. How to configure a central error handler in servlets?
12. What are cookies?
13. How to read a cookie using servlet?
14. How to delete a cookie using servlet?
15. How to create a session in servlet?
16. How to delete a session in servlet?

Objective Type Questions

Q 1 - Which of the following is true about init() method of servlet?

A - The init() method simply creates or loads some data that will be used throughout the life of
the servlet.
B - The init() method is not called again and again for each user request.
C - Both of the above.
D - None of the above.

Q 2 - Which of the following code is used to set content type of a page to be serviced using servlet?

A - response.setContentType()
B - request.setContentType()
C - writer.setContentType()
D - None of the above.

Q 3 - Which of the following code is used to get names of the headers in servlet?

A - response.getHeaderNames()
B - request.getHeaderNames()
C - Header.getHeaderNames()
D - None of the above.

Q 4 - Which of the following code retrieves the name of the HTTP Method?

A - Header.getMethod()
B - response.getMethod()
C - request.getMethod()
D - None of the above.

Q 5 - Which of the following code returns the port number on which this request was received?

A - response.getServerPort()
B - request.getServerPort()
C - Header.getServerPort()
D - None of the above.

Q 6 - Which of the following code can be used to send an error response to the client using the specified
status code and clearing the buffer.

A - request.sendError(statusCode)
B - response.sendError(statusCode)
C - header.sendError(statusCode)
D - None of the above.

Q 7 - Which of the following code can be used to set the character encoding for the body of the response?

A - response.setCharacterEncoding(charset)
B - request.setCharacterEncoding(charset)
C - header.setCharacterEncoding(charset)
D - None of the above.

Q 8 - Which of the following request attributes that an error-handling servlet can access to analyse the
nature of error/exception?

A - javax.servlet.error.status_code
B - javax.servlet.error.exception_type
C - javax.servlet.error.message
D - All of the above.

Q 9 - Which of the following code is used to get an attribute in a HTTP Session object in servlets?

A - session.getAttribute(name)
B - session.alterAttribute(name)
C - session.updateAttribute(name)
D - None of the above.

Q 10 - Which of the following code is used to get three-letter abbreviation for this locale's language in
servlets?

A - response.getISO3Language()
B - Locale.getISO3Language()
C - request.getISO3Language()
D - None of the above.

Q 11 - Which of the following is true about init() method of servlet?

A - The init() method simply creates or loads some data that will be used throughout the life of
the servlet.
B - The init() method is not called again and again for each user request.
C - Both of the above.
D - None of the above.

Q 12 - Which of the following code is used to set content type of a page to be serviced using servlet?

A - response.setContentType()
B - request.setContentType()
C - writer.setContentType()
D - None of the above.

Q 13 - Which of the following code is used to get names of the headers in servlet?

A - response.getHeaderNames()
B - request.getHeaderNames()
C - Header.getHeaderNames()
D - None of the above.

Q 14 - Which of the following code retrieves the name of the HTTP Method?

A - Header.getMethod()
B - response.getMethod()
C - request.getMethod()
D - None of the above.

Q 15 - Which of the following code returns the port number on which this request was received?

A - response.getServerPort()
B - request.getServerPort()
C - Header.getServerPort()
D - None of the above.

Q 16 - Which of the following code can be used to send an error response to the client using the specified
status code and clearing the buffer.

A - request.sendError(statusCode)
B - response.sendError(statusCode)
C - header.sendError(statusCode)
D - None of the above.

Q 17 - Which of the following code can be used to set the character encoding for the body of the response?

A - response.setCharacterEncoding(charset)
B - request.setCharacterEncoding(charset)
C - header.setCharacterEncoding(charset)
D - None of the above.

Q 18 - Which of the following request attributes that an error-handling servlet can access to analyse the
nature of error/exception?

A - javax.servlet.error.status_code
B - javax.servlet.error.exception_type
C - javax.servlet.error.message
D - All of the above.

Q 19 - Which of the following code is used to get an attribute in a HTTP Session object in servlets?

A - session.getAttribute(name)
B - session.alterAttribute(name)
C - session.updateAttribute(name)
D - None of the above.

Q 20 - Which of the following code is used to get three-letter abbreviation for this locale's language in
servlets?

A - response.getISO3Language()
B - Locale.getISO3Language()
C - request.getISO3Language()
D - None of the above.

Q 21 - _jspService() method of HttpJspPage class should not be overridden.

A - True
B - False

Q 22 - Which of the following is not a valid attribute of a page directives?

A - language
B - extend
C - export
D - import

Q 23 - Which of the following attributes are mandatory in <jsp:useBean /> tag?

A - id, type
B - id, class
C - type, class
D - type,property

Q 24 - Which of the following is true about page scope?

A - Object created with request scope are accessible only from the page in which they are created.
B - Object created with request scope are accessible only from the pages which are in same session.
C - Object created with request scope are accessible only from the pages which are processing the
same request.
D - Object created with request scope are accessible only from the pages which reside in same
application.

Q 25 - Which of the following method can be used to read a form parameter in JSP?

A - request.getParameter()
B - response.getParameter()
C - request.getValue()
D - response.getValue()

Q 26 - Which of the following is true about buffer Attribute?

A - The buffer attribute specifies the size of buffer.


B - The buffer attribute specifies buffering characteristics for the server output response object.
C - Both of the above.
D - None of the above.

Q 27 - Which of the following is true about isScriptingEnabled Attribute?

A - The isScriptingEnabled attribute determines if scripting elements are allowed for use.
B - The default value (true) enables scriptlets, expressions, and declarations.
C - Both of the above.
D - None of the above.

Q 28 - Which of the following is true about Initialization phase in JSP life cycle?
A - When a container loads a JSP it invokes the jspInit() method before servicing any requests.
B - Container invokes _jspService() method during Initialization phase.
C - Both of the above.
D - None of the above.

Q 29 - How to pass information from JSP to included JSP?

A - Using <%jsp:param> tag.


B - Using <%jsp:page> tag.
C - Using <%jsp:import> tag.
D - Using <%jsp:useBean> tag.

Q 30 - Which of the following is true about <c:url> tag

A - The <c:url> tag formats a URL into a string and stores it into a variable.
B - The <c:url> tag automatically performs URL rewriting when necessary.
C - Both of the above.
D - None of the above.

Answers: 1 (c), 2 (a), 3 (b), 4 (c), 5 (b), 6 (b), 7 (a), 8 (d), 9 (a), 10 (c), 11 (c), 12 (a), 13 (b), 14 (c), 15
(b), 16 (b), 17 (a), 18 (d), 19 (a), 20(c), 21(a), 22(c), 23(b), 24(a), 25(a), 26(c), 27(c), 28(a), 29(a), 30(c).
Unit-3
Web Security
3.1 Introduction

Malicious users trying to access information over internet.

A threat is a possible danger that might exploit a vulnerability to breach security and therefore cause
possible harm.

Security Threat is defined as a risk that can potentially harm computer systems and organization. The
cause could be physical such as someone stealing a computer that contains vital data. The cause could
also be non-physical such as a virus attack

Web threats definition


Web-based threats, or online threats, are a category of cybersecurity risks that may cause an undesirable
event or action via the internet. Internet-based threats expose people and computer systems to harm
online. A broad scope of dangers fits into this category, including well-known threats like phishing and
computer viruses. However, other threats, like offline data theft, can also be considered part of this group.

Web threats are made possible by end-user vulnerabilities, web service developers/operators, or web
services themselves. Regardless of intent or cause, the consequences of a web threat may damage both
individuals and organizations.

This term typically applies to — but is not limited to — network-based threats in the following categories:

 Private network threats - impact sub-networks connected to the wider global internet. Typical
examples can include home Wi-Fi or ethernet networks, corporate intranets, and national
intranets.

 Host threats - impact specific network host devices. The term host often refers to corporate
endpoints and personal devices, such as mobile phones, tablets, and traditional computers.

 Web server threats - impact dedicated hardware and software that serve web infrastructure and
services.

How do web threats work?


When a web threat arises, certain circumstances align to make it a point-of-concern.

Namely, there are a few basic components to any web threat:

1. Threat motives give an intentional threat agent a reason or goal to cause harm. Some threat
agents don’t act intentionally or act autonomously and may, therefore, be absent of motive.

2. Threat agents are anything or anyone that can negatively impact — with the internet either as
a threat vector or a target itself.

3. Vulnerabilities include any human behavior weakness, technology systems, or other resources
that can lead to a damaging exploit or incident.

4. Threat outcomes are the negative results of a threat agent acting against one or more
vulnerabilities.
As these components interact, a threat becomes an attack on computer systems. Threat motives can
include any of the following: financial, surveillance, information, retaliation, sabotage, and more.

Threat agents are typically people with malicious intent. By extension, agents may also be anything that
is manipulated into acting in favor of the original threat agent. However, some threat agents
— such as destructive nature events — act entirely without human intervention.

The types of threat agents include:

 Non-human agents: Examples include malicious code (viruses, malware, worms, scripts),
natural disasters (weather, geological), utility failure (electrical, telecom), technology failure
(hardware, software), and physical hazards (heat, water, impact).

 Intentional human agents: Based on malicious intent. Can be internal (employees, contractors,
family, friends, acquaintances) and external (professional and amateur hackers, nation-state
actors and agencies, competitor corporations)

 Accidental human agents: Based on human error. Similar to intentional threats, this type can
include internal and external agents.

 Negligence-based human agents: Based on careless behaviors or safety oversights. Again, this
category can also include internal and external agents.

Vulnerabilities may be points of weakness where someone or something can be manipulated.


Vulnerabilities can be considered a web threat and a concern that enables other threats. This area typically
includes some form of human or technical weakness that can lead to penetration, misuse, or destruction
of a system.

Threat outcomes may lead to disclosed private info, deceived users, disrupted computer system use, or
seized access privileges. Web threats often result in, but are not limited to, causing:

 Reputation damage: Loss of trust from clients and partners, search engine blacklisting,
humiliation, defamation, etc.

 Operations disruption: Operational downtime, access denial to web-based services such as


blogs or message boards, etc.

 Theft: Financial, identity, sensitive consumer data, etc.

Cybercriminals will use almost any vulnerability within an operating system (OS) or an application to
conduct an attack. However, most cybercriminals will develop web threats that deliberately target some
of the most common operating systems/applications, including:

 Java: Because Java is installed on over 3 billion devices (that are running under various
operating systems) exploits can be created to target specific Java vulnerabilities on several
different platforms/operating systems.

 Adobe Reader: Although many attacks have targeted Adobe Reader, Adobe has implemented
tools to protect the program against exploit activity. However, Adobe Reader is still a common
target.

 Windows and Internet Explorer: Active exploits still target vulnerabilities that were detected
as far back as 2010 – including MS10-042 in Windows Help and Support Center, and MS04-
028, which is associated with incorrect handling of JPEG files.

 Android: Cybercriminals use exploits to gain root privileges. Then, they can achieve almost
complete control over the targeted device.
How do internet web threats spread?

The most concerning internet threats travel the web to attack more systems. These threat agents often use
a mix of human manipulation and technical commands to reach their targets.

Web threats of this nature use the internet's many communications channels to spread. Larger threats use
the global internet to respond to threats, while more targeted threats may directly infiltrate private
networks.

Typically, these threats are distributed through web-based services. Malicious actors prefer to place these
threats in locations where users will often engage with them. Public websites, social media, web forums,
and email are often ideal for spreading a web threat.

Users are affected when they engage with malicious URLs, downloads, or provide sensitive info to
websites and message senders. This engagement may also trigger infection and spread of web threats to
other users and networks. It’s not uncommon for innocent users to unknowingly become threat agents
themselves.

How to spot web threats

Despite the unending scope of web-based dangers, it is possible to spot some general traits of web threats.
However, spotting a web threat requires a vigilant eye to catch subtle details.

Some web threats are clearly of concern to web infrastructure hardware, such as water and heat. While
those are easier to spot, others require careful attention. Any time you are browsing websites and
receiving digital messages are when you should be most cautious.

Here are some tips to guide you:

 Grammar: Malicious actors may not always carefully craft their messages or web content
when assembling an attack. Look for typos, odd punctuation, and unusual phrasing.

 URLs: Harmful links can be masked under decoy anchor text — the visible text that’s
displayed. You can hover over a link to inspect its true destination.

 Poor quality images: The use of low-resolution or unofficial images may indicate a malicious
webpage or message.

Cybercrime
Cybercrime refers to any unlawful activity conducted via computer systems. These threats often use the
web to enact their plans.

 Cyberbullying: Mental abuse of victims using threats and harassment.

 Unauthorized data disclosure involves the release of private information, such as email leaks,
intimate photos, and significant corporate data leaks.

 Cyber libel: Also known as online defamation, this can involve attacking individuals or
organizations' reputations. This can be done through disinformation (deliberate distribution of
inaccurate information) or misinformation (mistaken distribution of inaccurate information).

 Advanced Persistent Threats (APTs): Malicious actors gain access to a private network and
establish ongoing access. They combine social engineering, malicious code, and other threats
to exploit vulnerabilities and gain this access.

Examples of web threats

Among the many examples of web threats, here are some of the more well-known examples:
WannaCry ransomware

In May 2017, the WannaCry ransomware spread to many networks and locked down countless Windows
PCs. This threat was particularly dangerous because of its worm functionality, allowing it to spread
completely autonomously. WannaCry exploited a native communication language within Windows to
spread this malicious code.

Celebrity iCloud phishing

A spear-phishing attack led to the breach of numerous celebrity iCloud accounts. This breach ultimately
resulted in the unauthorized leak of countless private photos from these accounts.

While the attacker was eventually located and prosecuted, the victims are still suffering from their
intimate photos being made public — without their permission. This has become one of the most well-
known phishing attacks of the decade.

How to protect yourself against web threats


Most threats are successful due to two main weaknesses:

 Human error

 Technical error

Full protection from web threats means you will need to find ways to cover these weak points.

General tips to follow for both end-users and web service providers include:

1. Always create backups: All valuable data should be copied and stored safely to prevent data
loss in case of an incident. Websites, device drives, and even web servers can be backed up.

2. Enable multi-factor authentication (MFA): MFA allows for additional layers of user
authentication on top of traditional passwords. Organizations should enable this protection for
users, while end-users should be sure to make use of it.

3. Scan for malware: Regular scans for infections will keep your computer devices secured.
Personal devices can all be covered through an antivirus solution like Kaspersky Total
Security. Enterprise endpoint machines and computer networks should use this protection as
well.

4. Keep all tools, software, and OS up to date: Computer systems are more vulnerable when
they’ve been unpatched against undiscovered holes in their programming. Software developers
regularly probe for weaknesses and issue updates for this purpose. Protect yourself by
downloading these updates.

Service providers like website owners and server operators are where true comprehensive security starts.
These parties will need to take precautions for better protection. They can do this by:

1. Monitoring web traffic to gauge for normal volumes and patterns.

2. Implementing firewalls to filter and restrict unpermitted web connections.

3. Network infrastructure distribution to decentralize data and services. This includes aspects
like backups for various resources and geo server rotations.

4. Internal probing to investigate for unpatched vulnerabilities. This might, for example, involve
self-attacking with SQL injection attack tools.

5. Proper security configuration for access rights and session management.


Users should protect themselves by doing the following:

1. Scan downloads for malware.

2. Vet links before clicking, only clicking links if you are positive the destination is safe and
trusted.

3. Make strong, secure passwords, and avoid duplicates. Use a secure Password Manager to help
manage all of your accounts and passwords.

4. Throttle login attempts by triggering account lockdown after a limited number of tries.

5. Look out for phishing red flags in texts, email, and other communications.

3.2 Website security vulnerabilities


1. Sql Injections

SQL injection is a type of web application security vulnerability in which an attacker attempts to use
application code to access or corrupt database content. If successful, this allows the attacker to create,
read, update, alter, or delete data stored in the back-end database. SQL injection is one of the most
prevalent types of web application security vulnerabilities.

2. Cross Site Scripting (Xss)


Cross-site scripting (XSS) targets an application's users by injecting code, usually a client-side script
such as JavaScript, into a web application's output. The concept of XSS is to manipulate client-side
scripts of a web application to execute in the manner desired by the attacker. XSS allows attackers to
execute scripts in the victim's browser which can hijack user sessions, deface websites or redirect the
user to malicious sites.

3. Broken Authentication & Session Management


Broken authentication and session management encompass several security issues, all of them having to
do with maintaining the identity of a user. If authentication credentials and session identifiers are not
protected at all times, an attacker can hijack an active session and assume the identity of a user.

4. Cross-Site Request Forgery (Csrf)


Cross-Site Request Forgery (CSRF) is a malicious attack where a user is tricked into performing an
action he or she didn't intend to do. A third-party website will send a request to a web application that a
user is already authenticated against (e.g. their bank). The attacker can then access functionality via the
victim's already authenticated browser. Targets include web applications like social media, in browser
email clients, online banking, and web interfaces for network devices.

5. Spoofing
Spoofing is when someone hides their identity to evade detection for their wrong acts and pretends to be
someone else in an attempt to gain trust and get sensitive system information. The common spoofing
done by changing the hardware or MAC address is called MAC cloning, changing the IP address or the
unique identity on the network is called IP spoofing, and impersonating as someone else in their digital
communication is called email spoofing.

6. Information-gathering attacks
Information gathering is the practice of attacker gaining priceless details about probable targets. This is
not an attack but only a pre-phase of an attack and is totally passive as there is no explicit attack. Systems
including computers, servers, and network infrastructure, including communication links and inter
networking devices, are sniffed, scanned, and probed for information like whether the target system is
up and running, what all ports are open, details regarding the operating system and its version, etc. Some
of the information-gathering attacks are sniffing, mapping, vulnerability scanning, phishing, etc.

7. Password attacks
The simplest way to achieve control of a system, or any user account, is through a password attack. If
the personal and behavioral details of the victim are known, the attacker starts with guessing password.
Frequently, the attacker uses some form of social engineering to trace and find the password. Dictionary
attack is the next step in password attacks and is automated.

8. Malware
After gaining access to a system, the attacker takes the support of malware or malicious software that
clandestinely acts against the interests of the computer user.

9. Virus
Computer viruses are the most communal threat to the computer users. Computer viruses are malicious
software designed to blow out from one computer to another through file transfer, piggybacks on genuine
programs and OS, or e-mails. The email attachments or downloads from particular websites contaminate
the computer and also other computers on its list of contacts by using the communication network.
Viruses influence the system security by changing the settings, accessing confidential data, displaying
unwanted advertisements, sending spam to contacts, and taking control of the web browser. The viruses
are identified as executable viruses, boot sector viruses, or e-mail viruses.

10. Worms
Computer worms are fragments of malicious software that reproduce swiftly and blow out from one
computer to another through its contacts, again spreading to the contacts of these other computers and so
on and reaching out to a large number of systems in no time. Captivatingly, worms are prepared for
spreading by exploiting software vulnerabilities. Worms display unwanted advertisements. It uses up
tremendous CPU time and network bandwidth in this process thereby denying access to the systems or
network of the victim, creating chaos and trust issues on a communication network.

11. Bots
Bots can be seen as advanced form of worms. They are automated processes that are designed to interact
over the internet without the need of human interaction. They can be good or bad. Malicious bot can
infect one host and after infecting will create connection to the central server which will provide
commands to all infected hosts attached to that network called Botnet.

12. Trojans
Trojans are programs that appear as perfectly genuine but, in reality, have a malicious part embedded in
it. Trojans are spread usually through email attachment from the trustworthy contacts and also on clicking
on fake advertisements. The payload of Trojans is an executable file that will install a server program on
the victim’s system by opening a port and always listening to that port whereas the server is run on the
attacker’s system. Hence, whenever the attacker wants to login to the victim machine, they can do so by
means of the backdoor entry making it hidden from the user.

13. Spyware and adware


Spyware and adware are software with a common property of collecting personal information of users
without their knowledge. Adware is intended to track data of the user’s surfing behaviors, and, based on
that, pop-ups and advertisements are displayed. The adware clause in the agreement during the
installation process is often skipped with least seriousness. Spyware on the other hand gets installed on
a computer and gathers information about the user’s online activities without their knowledge. Spyware
contains keyloggers that record everything typed on the keyboard, making it unsafe due to the high threat
of identity mugging.

14. Scareware
Scareware is yet another malware that tricks victims by displaying fake alerts and forcing the victim to
buy protective software that is fraudulent. The alerts or the pop-up messages sound like warning
messages along with proper protective measures, which if followed creates security issues.

15. Rootkit
Rootkit is a pool of software tools that gets mounted in stealth along with some genuine software. Rootkit
allows remote access and administrative control on a system. With these privileges, the rootkit performs
malicious activities like disabling of antivirus, password sniffing, keylogging, etc.

16. Keylogger
Keylogger software has the ability to record keystrokes and also capture screenshots and save it to a log
file in encrypted form. Keylogger software can record all the information that is typed on the keyboard
including passwords, e-mail, and instant messages. The log file created by the keylogger is saved and
mailed to the attacker on a remote machine with the motive to extract password and banking details for
financial fraud.

17. Ransomware
Ransomware is a malicious software that hampers admission to computer or files on the computer. The
computers may be locked or files encrypted. Accordingly, the two common types of ransomware are
lock screen ransomware and encryption ransomware. The victim will be demanded ransom for the
restriction to be removed, and this gets displayed on victim’s system. There can also be notification
stating that establishments have detected illicit activity on this computer and demands ransom as fine to
avoid prosecution.

18. Rogue security software


Rogue security software is another malicious program that deceives users to believe that there is malware
installed on their system or the security measures are outdated and hence of concern. They offer installing
or updating users’ security settings. Then it is an actual malware that gets installed on the computer.

19. Botnets
A collection of compromised systems or bots acts as a team of infected computers under the control of a
bot master to remotely control and send synchronized attacks on a victim host. This army of bots, agents,
and bot master constitute a botnet. Botnets are used for sending spams and also for distributed denial of
service attacks.

20. Denial-of-service attacks


Denial-of-service (DoS) attacks as the name suggests deny users from accessing or using the service or
system. This is mainly done by overwhelming the bandwidth, CPU, or memory wherein the access to the
network of the victim machine or server offering the service gets denied. DoS attacks thus interrupt the
service of a computer or network systems, making it inaccessible or too inferior in performance.
21. Distributed DoS
In distributed DoS (DDoS) attacks, the victim is targeted from a large number of individual compromised
systems simultaneously. The DDoS attacks are normally done with the help of botnets. The botmaster is
the attacker who indirectly attacks the victim machine using the army of bots or zombies. The DDoS
attacks occur when a large number of compromised systems act synchronously and are being coordinated
under the control of an attacker in order to totally exhaust its resources and force it to deny service to its
genuine users. It is the upsurge in the traffic volume that loads the website or server causing it to appear
sluggish [2].

22. IoT-based attacks


The last decade has seen exponential increase in the use of Internet of Things (IoT) that are smart devices
used at home, organizations, and businesses. The issue with these IoT is its weak security as these devices
are often overlooked when it comes to applying security patches that create lead-ins for attackers to seize
these devices to infiltrate the networks. An IoT-based attack is any cyberattack that leverages a victim’s
use of IoT to sneak malware onto a network.

23. Session hijacking


In session hijacking, the hacker takes control of a session going on between two hosts. Session hijacking
usually takes place in applications that use TCP with a sequence number prediction. With that sequence
number, the attacker sends a TCP packet.

24. Zombies
They work similar to Spyware. Infection mechanism is same but they don’t spy and steal information
rather they wait for the command from hackers.

25. Blended attacks


A blended attack is a software exploit that encompasses a mixture of exploit techniques to attack and
propagate threats, for example, viruses, worms, and Trojan horses.

26. Website attacks


Website attacks are targeting browser components that are at risk of being unpatched even when the
browser is patched. SQL injection attacks are intended to target any website or web application that uses
an SQL database such as MySQL, Oracle, etc. by taking advantage of the security flaws in the
application’s software. This attack is used to obtain and corrupt user’s sensitive data.

27. Mobile phone and VOIP threats


Malware target mobile phones, VoIP systems, and the IP PBXs as these devices have plentiful published
vulnerabilities. There are attack tools freely available on the Internet, and misusing these vulnerabilities
makes these attacks too common and simple even for a script kiddie.

28. Wi-Fi eavesdropping


Wi-Fi eavesdropping is an attack used by network attackers to grab sensitive information of a target
system. It is the act of silently listening on an unencrypted Wi-Fi network.

29. WPA2 handshake vulnerabilities


The key reinstallation attack (KRACK) lets an attacker to decipher the network traffic on Wi-Fi routers.
Every device connected to Wi-Fi, such as computers, smartphones, smart devices, and wearables, can be
identified by the hacker.
30. Insider attacks
One of the prevalent all-time computer security threats faced by any organization is from its own
employees. Insider attacks are initiated by disgruntled employees of an organization. Insider usually has
certain privileges to the data as well as rights on the systems and networks that they attack, giving them
an advantage over external attackers. These attacks can be hard to prevent with firewalls, which are the
first level of defense.

31. Supply chain attacks


A supply chain attack seeks to cause harm by targeting the least secured elements in the supply network.

32. Buffer overflows


Buffer overflows are used to exploit programming glitches that do not take care of the buffer size. If a
buffer is jam-packed beyond its size, the data overflows into the contiguous memory. This flaw gets
smartly used by hackers to change the execution of the program.

33. User to root attack


User to root attack is a case of privilege escalation where a user gains a higher privilege than that
authorized. This is not a class of attack as such, and it is the process of any attack. Every attack will do
activities the attacker is not privileged to do.

34. Man-in-the-middle attacks


Man-in-the-middle attacks allow the hacker to snoop on the communication between two systems,
affecting the privacy. A common method of doing this is to place the attacker at a point and redirect all
the communication through the route that includes that hacker so that eavesdropping is possible by the
hacker.

35. Pharming
Pharming is a widespread online fraud that will automatically point to a nasty and illicit website by
relaying the authentic URL. Even when the URL is correctly entered, the redirection happens to some
forged website looking similar to the actual one. This fake site prompts one to enter personal information
that gets to someone with a wicked intent.

36. Spam
Spams are unsolicited bulk e-mail messages that annoy the user with unwanted and junk mails. It gives
burden for communications service providers, organizations and individuals alike. These emails can be
commercial ones like an advertisement or noncommercial one like chain letters or anecdotes. Spam is
considered an active vehicle for virus propagation, scams, fraud and is a threat to computer privacy.
Spam also phishes for interesting information with offers and promotions that trick victims into following
links or entering details.

3.3 Web attacks and their prevention

Now let’s take a look at some of the most common attacks that hackers might attempt on your website.
Knowing these common web application vulnerabilities will help you identify them faster and fix them
more easily.
3.3.1: SQL Injection

Many hackers start with an attempt to gain access to the database through SQL injection attacks. This is
when the attacker inserts malicious SQL statements into form fields and other injection points, with the
intention of gathering information from and controlling the database. They can use this information to
access and modify or even destroy the information, and to attack the underlying system.

Attackers typically use these attacks to collect vital customer information such as their contact
information, passwords, or even credit card info. They may even exploit these web security
vulnerabilities to change the price of a product, for instance. Advanced attacks can even allow them to
control the database server and the operating system.

How to Prevent It
1. Prepared statements with parameterized queries can mitigate SQL-related web application
vulnerabilities. A prepared statement helps to sanitize the input and ensures that it is considered
as a string literal in SQL rather than as part of the SQL query. In other words, the database can
tell the difference between SQL data and SQL code. So the code is no longer vulnerable to SQL
injection attacks as the query is less vulnerable to tampering.

2. Migrating to Object Relational Mapping Tools (ORMs) is another excellent option. However,
most ORMs allow non-parameterized queries in addition to performing parameterized queries.
As such, it’s crucial to carefully use the frameworks keeping this in mind.

3. Make the most of LIMIT and other SQL controls within your queries so that even if an SQL
injection attack does occur, it can prevent the mass disclosure of records.

3.3.2: Cross-Site Scripting (XSS)

As mentioned earlier, cross-site scripting or XSS is one of the most popular web application
vulnerabilities that could put your users’ security at risk. These attacks inject malicious code into the
running application and executes it on the client-side.

The goal of XSS attacks is to send this malicious code to other users, sometimes infecting their devices
with malware or stealing sensitive information. This type of website application vulnerability can give
the attacker full control of the user’s browser and can be extremely dangerous to any website.

How to Prevent It
1. Modern frameworks have made it a lot easier to escape untrusted user input and mitigate XSS
attacks. AngularJS, React JS, and Ruby on Rails are some of the latest, most effective
frameworks to prevent these web application vulnerabilities. These frameworks can
automatically escape user input and help mitigate XSS attacks by design, although they do have
limitations.

2. Avoid implementing a blacklist, instead favor of a whitelist, because blacklists are less effective
at preventing web security vulnerabilities. An attacker who knows what they’re doing can easily
bypass a blacklist filter.

3. The ultimate solution to prevent these web application vulnerabilities is output encoding. This
involves converting untrusted user input into a safe form so the input is displayed to the user as
data without being executed as code in the browser. This means that special characters will be
translated into an equivalent form that the browser will no longer find significant.
4. It’s also important to understand that output encoding depends on the context of where data is
being output. For instance, you may have HTML contexts, HTML entity contexts, HTML
attribute contexts, CSS contexts, JavaScript contexts, and more. As such, you will need to apply
context-sensitive encoding when render the page for the browser.

5. Enable a Content Security Policy (CSP), which can be very effective to help mitigate Cross-
Site Scripting vulnerabilities.

3.3.3: Authentication Failure

Authentication-related web application vulnerabilities occur when there’s an improper implementation


of adequate user authentication controls. This puts user accounts at risk of being breached. Attackers
may exploit these web security vulnerabilities to gain control over any user account or even over the
entire system.

One of these vulnerabilities is Credential Stuffing, where an attacker will test a list of valid passwords
and usernames gleaned from another breach or attack until they manage to find a valid combination and
gain access.

Another common vulnerability is a Brute Force attack, in which the attacker tries every possible character
combination until they find a valid one.

Session hijacking is another common attack that can occur as a result of authentication failure. This is
when there is a failure to properly invalidate session IDs, allowing attackers to exploit an authenticated
session of a legitimate user.

How to Prevent It
1. One of the essential steps to avoid these web application vulnerabilities is to allow enough time
for developers to test the code before it gets deployed to production. External security audits
can also help ensure that you apply the best practices of website security.

2. Avoid deploying with default credentials, especially for admins.

3. Wherever possible, make sure you implement multi-factor authentication to make your system
less vulnerable to the attacks mentioned above.

4. Put a limitation or delay on failed login attempts. Make sure you log all failures and notify
administrators when there’s an attack attempt.

5. Avoid unnecessarily restricting input size. If you allow more characters, there are fewer chances
for attackers to guess the right password.

6. Have some form of lockout in place to prevent brute force attacks and minimize these web
application vulnerabilities.

7. Use adaptive hashing algorithms like bcrypt, pbkdf2, argon2, etc. to salt passwords and hash
them before storing them in the database

8. Implement weak-password checks for better password security. This would include testing new
or changed passwords and comparing them against a list of compromised or weak passwords.
Use of a service to check for compromised passwords (such as Have I Been Pwned) helps to
automate this functionality and keeps the list of compromised passwords up to date as new
attacks occur.
3.3.4: Security Misconfiguration

Security misconfigurations provide attackers with an easy way into your website, making it one of the
most critical web application vulnerabilities that you need to prevent.

Unused pages, unpatched flaws, unprotected files and directories, and default configurations, are some
of the security misconfigurations that attackers can leverage to gain unauthorized access.

Every level of your application stack can be vulnerable to security misconfigurations. This includes your
web server, platform, database, network services, storage, frameworks, application server, and more.

If attackers manage to exploit these web application vulnerabilities, they can access sensitive information
and take control of user and admin accounts.

How to Prevent It
1. Make sure you use encrypted (HTTPS) connections to transfer data and information between
the users and the application.

2. Have a repeatable hardening process that you can quickly and easily deploy on another
environment. This will save time in setting up a new and secure environment as you’ll be able
to automate the process.

3. Perform all remote admin tasks through secured channels to minimize these web application
vulnerabilities. Even if you do have to use protocols that don’t support strong encryption, make
sure you activate them over a secondary encryption channel such as IPSEC, or TLS.

4. Regularly conduct file integrity checking to ensure that there haven’t been any unauthorized
changes to critical files. Use file integrity checking tools that can accept routine and expected
changes while alerting you of any unexpected or unusual changes.

5. Have an automated process in place to regularly verify the effectiveness of your settings and
configurations in every environment. You can use an automated configuration monitoring tool
that can alert you of any unauthorized changes. This will help you identify these web application
vulnerabilities before they cause any damage.

6. Keep your platform minimal and avoid adding unnecessary features, samples, documentation,
and components. If you have unused features and frameworks in the platform, it’s best to
remove them to prevent web application vulnerabilities.

3.3.5: XML External Entities

An XML external entity attack, also known as an XXE, or an XML injection attack, is another class of
vulnerabilities you should watch out for. These types of attacks occur when attackers exploit a weakly-
configured XML parser. Through such attacks, attackers can inject additional data, access confidential
data, and execute applications and create remote tunnels (shells).

XML external entity attacks can also result in remote code execution, Server Side Request Forgery
(SSRF), and more. By default, most XML parsers are prone to these attacks. This leaves it up to the
developers to ensure that their web application is free from these web application vulnerabilities.
How to Prevent It
1. Completely disabling Document Type Definitions (DTD’s), also known as External Entities, is
the safest way to prevent XXE attacks. This secures the parser against DoS attacks. However,
it may not always be possible to completely disable DTDs. In this case, you need to disable
external document type declarations and external entities in a specific way for each parser.

2. Whenever possible, you should try using less complex data formats like JSON. It’s also good
to avoid serialization of sensitive data to avoid these website application vulnerabilities.

3. Implement a positive, server-side method to validate, sanitize, and filter input. This will help
prevent the occurrence of hostile data within your XML documents, nodes, and/or headers and
help you avoid XXE-related web application vulnerabilities.

4. Patch or upgrade all the XML processors and libraries that the application or its underlying OS
is using.

5. While the best solution is to use manual code review for critical functionality in large and
complex applications, you should also use SAST tools to detect XXE in source code.

6. Use XSD validation or an equivalent alternative to validate the incoming XML structure.

3.3.6: Broken Access Control (Authorization Failure)

Access control helps you control what sections of a website and what application data different visitors
can access.

For instance, if your website is a platform for different sellers to list their products, they will need some
kind of access to add new products and manage their sales. However, not every visitor will need that
level of access since most of them are visiting your site to buy products.

As such, having a broken access control opens up your site to web application vulnerabilities, which
attackers can exploit to access sensitive information or unauthorized functionality. They might even use
these attacks to make modifications to access rights and user data.

How to Prevent It
1. It’s crucial to maintain a security-first policy when developing and configuring software.

2. Except for public resources, deny access by default.

3. Make sure you apply protection horizontally (across all data) and vertically (across all levels of
access privileges). Vertical protection involves employing the least privilege concept wherein
access is granted only in accordance to their

4. Centralize all authorization decisions to minimize the occurrence of access-related web


application vulnerabilities.

5. Instead of letting users freely create, read, modify, or delete any record, use model access
controls to enforce record ownership. Remove their ability to read or modify data from other
users.

6. Implement a one-time access control mechanism that you can reuse through the 1.

7. Set limitations to API and controller access to reduce the risk of attacks by automated tools.

8. Invalidate JWT tokens and user sessions on the server after logout.
9. Disable webserver directory listing and also prevent web roots from storing backup files and
file metadata.

These are some of the most common web application vulnerabilities that you should watch out for and
try to prevent. Doing so will help you avoid a large number of web application security threats.

Combined with your regular tests and automated scans, you should be able to utilize this list to minimize
the risk of security threats and ensure better security of sensitive information.

However, it’s important to note that these aren’t the only vulnerabilities you should be aware of. There
are plenty of other harmful web application vulnerabilities such as insecure cryptography, insufficient
logging and monitoring, and using components with known vulnerabilities.

Being aware of all of them will help you enhance security and protect valuable data against security
threats.
3.4 Web security models

1. Access Control Models


Information systems security refers to protection of information systems against unauthorized access to
or modification of information, whether in storage, processing or transit, and against denial of service to
authorized users, including measures necessary to detect, document, and counter such threats. The main
goals of information security are confidentiality or secrecy, integrity, availability, accountability, and
assurance. The goal of confidentiality is to ensure the information is not accessed by an unauthorized
person. The goal of information integrity is to protect information from unauthorized modification.
Information availability ensures the information is available when needed and is not made inaccessible
by malicious data-denial activities. Information accountability ensures that every action of an entity can
be uniquely traced back to the entity. Security assurance is the degree of confidence in the security of the
system with respect to predefined security goals.

Several models have been proposed to address the access control requirements of distributed
applications. Traditional access control models are broadly categorized as discretionary access control
(DAC) and mandatory access control (MAC) models. New models such as role-based access control
(RBAC) or task-based access control (TBAC) models have been proposed to address the security
requirements of a wider range of applications. We briefly highlight the main differences among these
models and provide an assessment of their suitability for supporting Web-based applications.

2. Discretionary Access Control (DAC) Model


In DAC models, all the subjects and objects in a system are enumerated and the access authorization
rules for each subject and object in the system are specified. Subjects can be users, groups, or processes
that act on behalf of other subjects. If a subject is the owner of an object, the subject is authorized to
grant or revoke access rights on the object to other subjects at his discretion. DAC policies are flexible
and the most widely used for Web-based applications. However, these policies do not provide high
security assurance. For example, DAC allows copying of data from one object to another, which can
result in allowing access to a copy of data to a user who does not have access to the original data. Such
risks can propagate to the entire Web environment, causing serious violation of security goals.

Among the existing representations of DAC models, a noticeable one is the HRU (Harrison, Ruzzo and
Ullman) access control matrix (ACM) model. The matrix specifies access rights of subjects for accessing
objects in the system. In conjunction with ACM, the HRU model uses a set of commands to construct
the overall authorization scheme. Safety in HRU is in general undecidable. The basic safety problem is
to determine whether there exists a reachable state in which a particular subject possesses a particular
privilege that it did not previously possess.
Several new models have recently been proposed for systems for which safety problems are decidable
and tractable. Most of these models are based on the notion of security type, and include the Schematic
Protection Model (SPM), the Typed Access Matrix (TAM) model, and the Dynamically Typed Access
Control (DTAC) model. Unlike SPM and TAM, which have subject types and object types, DTAC makes
no distinction between subjects and objects. The DTAC model uses a dynamic typing mechanism that
makes it suitable for a dynamic environment such as the Internet. In DTAC, a safety invariant is
maintained by carrying out static analysis and dynamic checks on the security aspects of the system. This
feature gives DTAC the power to model task-based security. By grouping entities into types, this model
can reduce the size of the configuration and can enhance the administrative functions. While these
extensions are intended to broaden the scope of ACM-based models, they are still in the theoretical
development stage, with little or no experimental results.
3. Mandatory Access Control (MAC) Model

In a MAC model, all subjects and objects are classified based on predefined sensitivity levels that are
used in the access decision process. An important goal of a MAC model is to control information flow
in order to ensure confidentiality and integrity of the information, which is not addressed by DAC
models. For example, to ensure information confidentiality in defense applications, a MAC model can
be implemented using a multilevel security mechanism that uses no read-up and no write-down rules,
also known as Bell-LaPadula restrictions. These rules are designed to ensure that information does not
flow from a higher sensitivity level to a lower sensitivity level. To achieve information integrity, the
access rules are formulated as no-read-down and no-write-up. The goal in this case is not to allow the
flow of low integrity information to high integrity objects. The Chinese Wall policy, which addresses
conflict of interest issues relevant to financial industries, can also be implemented using a MAC model.
For Web-based applications, multilevel classification of information may be an essential requirement
that can be enforced by a service provider to distinguish among the users and the type of information
being accessed.
Unlike DAC, MAC models provide more robust protection mechanisms for data, and deal with more
specific security requirements, such as an information flow control policy. However, enforcement of
MAC policies is often a difficult task, and in particular for Web-based applications, they do not provide
viable solutions because they lack adequate flexibility. Furthermore, organizational security needs are
often a mixture of policies that may need to use both DAC and MAC models, which necessitates seeking
solutions beyond those provided by DAC and MAC models only. Originally, these models were not
intended for Web-based applications. In particular, their design philosophy was not intended to serve
hypertext-based systems, which is common in a Web-based environment. The hypertext information
model uses special objects such as links, frames or slots, document nodes, and so forth, all of which need
to be protected. Hypertext systems are characterized by three features, which include information about
the connections among data items, their unique navigational aspects, and the absence of a schema.
Although extensions enabling these models to address security concerns have been proposed in the
literature, more challenging issues such as control of copy and dissemination of information, active object
management, and support for multiple data types and complex interrelationships have yet to be explored
in order to develop viable solutions for Web-based applications.

4. Role-based Access Control (RBAC) Model

Role-based access control (RBAC) models are receiving increased attention as a generalized approach
to access control because they provide several well-recognized advantages. As roles represent
organizational responsibilities and functions, a role-based model directly supports arbitrary,
organization-specific security policies. The RBAC models have been shown to be "policy-neutral" in the
sense that using role hierarchies and constraints, a wide range of security policies can be expressed,
including traditional DAC and MAC, and user-specific ones. Security administration is also greatly
simplified by the use of roles to organize access privileges. For example, if a user moves to a new function
within the organization, the user can simply be assigned to the new role and removed from the old one,
whereas in the absence of an RBAC model, the user's old privileges would have to be individually
revoked, and new privileges would have to be granted. Special administrative roles can be designated to
manage other roles. Such administrative roles can be hierarchically organized to provide a well-organized
security management structure, which is desirable in large Web-based enterprises where security
management becomes a complex task. Several authorization-constraints may need to be enforced in an
organization to protect information misuse and prevent fraudulent activities. A typical authorization
constraint, which is relevant and well-known in the security area, is separation of duties (SOD). Reducing
the risk of fraud by not allowing any individual to have sufficient authority within the system to single-
handedly perpetrate fraud is the intent of SOD. Such constraints can be easily expressed using an RBAC
model through SOD constraints on roles, user-role assignments and role-privilege assignments.
Furthermore, using assigned roles, users can sign on with the least privilege set required for any access.
In case of inadvertent errors, such least privilege assignment can ensure minimal damage.
An important consideration in RBAC systems is the possible temporal constraints that may exist on roles,
such as the time and duration of role activations, and timed-triggering of a role by an activation of another
role. Using an RBAC model is a highly desirable goal for addressing the key security requirements of
Web-based applications in general, and WFMSs in particular. Roles can be assigned to workflow tasks
so that a user with any of the roles related to a task may be authorized to execute it. However, the
challenge is to develop a robust RBAC framework to handle the complex security needs of a WFMS,
where temporal, nontemporal, and dependency constraints among roles and tasks exist.
A recent implementation of an RBAC system for the Web environment (RBAC/Web) has been reported
in. The implementation consists of a Web server to enforce RBAC policies and an administrative tool to
allow security administration. The system places no requirements on the browser. When a user issues an
access request, a role is assigned to the requester after establishing a session using the available
authentication and confidentiality services. These services include the Secure Socket Layer (SSL),
Secure HTTP (SHTTP), and an authentication mechanism that uses username/passwords. To ensure
better administration, RBAC/Web can be integrated with an administrative model such as URA97 (User-
Role Assignment '97), which uses administrative roles to manage other roles.
Several other RBAC implementations have been developed, including the hyper Drive System developed
by the Internal Revenue Service, Trusted Web, get Access by en Commerce, and SESAME. Trusted Web
requires specific software in the client machine. The I-RBAC (RBAC for an intranet) model uses
software agents to distinguish between the local role hierarchies and the global role hierarchy of the
entire intranet. The local network objects are known only to the local servers, whereas the global network
objects are known throughout the intranet. Information about mapping between the global roles and local
roles is kept in a database and is used when a global network object needs to access an object on another
server. The disadvantage of I-RBAC is that maintaining consistent information about the roles becomes
difficult as the number of roles increases.

A key feature of RBAC is its potential support for a multidomain environment, which makes it an
attractive candidate for Web-based applications. Role-hierarchy mapping between two RBAC-based
policy domains can be used to define a metapolicy for secure interoperation.

5. Access Control Models for Tasks and Workflows


The models discussed previously use the subject-object view toward security. These models have a
limited scope and are not flexible enough to allow access policies based on the content of information or
the nature of tasks/transactions in a WFMS. WFMSs have emerged as a key technology for enabling
activity-intensive Web applications that require extensive automated transactional functions. Such
applications typically constitute a complex mix of tasks and transactions that span departmental,
organizational, geographical and cultural boundaries, further exacerbating the complexity of Web
security. Although there exists a pressing need to develop access control models that can provide strong
support for activity and task-intensive applications, no existing access control models have the capability
to address the major security issues related to these applications.

Several authorization models related to WFMSs have been proposed. A viable approach to enforce
arbitrary security requirements during the execution of workflow tasks is to assign roles to workflow
tasks. The workflow tasks of Web-based applications can be distributed over multiple heterogeneous
security domains, and may have strict temporal and inter-task dependency constraints. In addition, roles
assigned to tasks may have their own temporal and nontemporal constraints that may be static or dynamic
in nature. Although the use of an RBAC framework for ensuring workflow security has been proposed
in the literature, substantial extensions are needed to address security issues related to Web applications
and WFMSs.
To address the security issues related to task-oriented systems and to effectively serve the unique needs
of such systems, researchers in propose a family of task-based access control (TBAC) models that
constitutes four models arranged in form of a hierarchy. The TBAC0 model represents the base model
that provides the basic or the minimum facilities, such as tasks, authorization steps, and their
dependencies. The TBAC1 model is an extension of TBAC0 that includes the composite authorizations
of two or more authorization steps. The TBAC2 model is another extension of TBAC0 that allows both
static and dynamic constraints. The TBAC3 model is a consolidated model that has features of both the
TBAC1 and TBAC2 models.

6. Agent-based Approach
With the increase of Internet applications, software agents are becoming popular as an emerging system-
building paradigm. This paradigm can be effectively used to provide security features for Web
applications. An agent is a process characterized by adaptation, cooperation, autonomy, and mobility.
Some agent communication language can be used to negotiate policies during conflicts for secure
interoperation among participating policy domains. Agents can be assigned security enforcement tasks
at the servers and client machines. Although mobility and adaptability are essential to the efficient use
of Internet resources, they pose several security threats. For example, an agent can engage in malicious
behavior, thus disrupting normal operation of the host. Similarly, a host may be able to affect the activity
of an agent by denying required access to local information resources.

7. Certificate-based Approach

Public-key infrastructure technology is maturing, and the use of PKI certificates is expected to be
ubiquitous in the near future. Certificates issued by a PKI facility can be used for enforcing access control
in the Web environment. An example is the use of an extended X.509 certificate that carries role
information about a user. These certificates are issued by a certification authority that acts as a trust
center in the global Web environment.

The use of public-key certificates is suitable for simple applications. These techniques can be used to
either support a host's access control method by carrying access control information or provide a separate
access control mechanism based on trust centers.

We have discussed several access control models and approaches that can be used to disseminate and
exchange information securely, and allow secure execution of WFMSs. However, comprehensive
frameworks are needed to address the multifaceted security issues related to Web-based applications. In
particular, robust access control models are needed to allow: controlled access, dissemination and sharing
of information based on content, context, or time; secure execution of tasks and workflows; secure
interoperation in a dynamic distributed enterprise environment; and efficient management and
administration of security.

The DAC and MAC models lack capabilities needed to support security requirements of emerging
enterprises and Web-based applications. Newer models such as SPM, TAM, and DTAC have the
potential to support Web-based applications. In particular, DTAC's feature of using safety invariants in
a dynamic environment is highly desirable for dynamic and transaction-intensive workflow-based
applications. Hypertext-based authorization models are essential for secure composition and distribution
of complex Web documents. However, these security models are yet to be fully developed and assessed
for their efficacy and viability to support Web-based applications.

Achieving secure interoperation in a heterogeneous Web environment is a difficult task, because of the
inherent dynamism and evolving security requirements of the underlying autonomous administrative
domains. Using RBAC models and software security agents are suitable approaches for such
environments. The RBAC models have several desirable features such as flexibility, policy-neutrality,
better support for security management and administration, the principle of least privilege, and other
aspects that make them attractive candidates for developing secure Web-based applications. In addition,
they can represent traditional DAC and MAC as well as user-defined or organization-specific security
policies. Furthermore, an RBAC model provides a natural mechanism for addressing the security issues
related to the execution of tasks and workflows. A key advantage of RBAC models is the ease of their
deployment over the Internet. The use of RBAC in conjunction with PKI facilities can provide a
pragmatic approach to addressing issues related to security of distributed Web-based applications and
WFMSs. The TBAC models represent efforts toward finding effective security solutions for the unique
needs of task-based systems. However, they are still in the early stages of development.

The RBAC models are expected to provide a viable framework for addressing a wide range of security
requirements for large enterprises. However, several extensions to the existing RBAC models are needed
to develop workable solutions to adequately address such needs.

3.5 Session Management


Session management is used to facilitate secure interactions between a user and some service or
application and applies to a sequence of requests and responses associated with that particular user.

18 What is session management and why is it important?

Session management is used to facilitate secure interactions between a user and some service or
application and applies to a sequence of requests and responses associated with that particular user. When
a user has an ongoing session with a web application, they are submitting requests within their session
and often times are providing potentially sensitive information. The application may retain this
information and/or track the status of the user during the session across multiple requests. More
importantly, it is critical that the application has a means of protecting private data belonging to each
unique user, especially within authenticated sessions.

Session tokens serve to identify a user’s session within the HTTP traffic being exchanged between the
application and all of its users. HTTP traffic on its own is stateless, meaning each request is processed
independently, even if they are related to the same session. Thus, session management is crucial for
directing these web interactions and these tokens are vital as they’re passed back and forth between the
user and the web application. Each request and response made will have an associated session token
which allows the application to remember distinct information about the client using it. Session cookies
were designed to help manage sessions, however there are several properties of the cookie that must be
configured and implemented correctly to prevent potential compromises.

It should be noted that cookies are not the only means of carrying out a session, it is also possible to
include headers that contain session tokens. Moreover, while session tokens can be embedded within a
URL this should not be implemented as URLs are often logged in various places and cached, increasingly
the likelihood of disclosure.

What are the vulnerabilities introduced with lack of session management?

Enforcing correct session management often boils down to the protection and security of the session
keys. There is a plethora of vulnerabilities introduced with insecure session cookies, which can be
leveraged by an attacker to take advantage of an authenticated user session. Adversaries can take
measures to brute force, predict, and expose session tokens which ultimately can lead to session
hijacking where the malicious party can then impersonate the victim and perform actions from their
account.

Session fixation can also take place if the properties of a session token allows an attacker to fixate the
token of the user once authenticated, it can then also be used to hijack the session. Alternatively, this
issue may arise if the application fails to check for consistent user information throughout the session,
reuses session tokens across all forms of access to the service, and sets cookies without proper validity
periods.
Once a user’s session is hijacked, an adversary now has the opportunity to make changes permitted to
the victim from their account and perform actions that could be dangerous as well as administrative tasks
such as adding/removing users, assigning privileges, etc. The more privileges the victim has within the
service, the more severe the attack can be.

What are the best practices for implementing session management?


There are many aspects to enforcing proper session management, all best practices should be
implemented for mitigating potential compromise.

1. Set Secure/HttpOnly Flags on your Cookies


Refrain from sending sensitive traffic and tokens over an unencrypted channel (HTTP). This can be
enforced by setting the Secure flag which ensures that data will only be transported over HTTPS.
The HttpOnly flag should also be set for session cookies as this will prevent client-side JavaScript
from accessing it which could result in session hijacking.

2. Generate New Session Cookies


New session tokens should be generated at every stage of a session; as soon as a user visits the
application, when they provide correct credentials, and when a user logs out of their account. A
cookie should also expire if the account is inactive for a long period of time and force the user to
re-authenticate. This also applies for changes in state, meaning the cookie should automatically be
destroyed when the session changes from anonymous to authenticated or vice versa.

3. Configure Session Cookies Properly


Session tokens should be long, unpredictable, and unique. These properties can help to ensure that
an attacker cannot guess or brute force the value of the token. The expiration on persistent cookies
should be set for no longer than 30 minutes, which prevents from session fixation and further
hijacking. This can be achieved by modifying the Expire and Max-Age attributes. If no value is
specified for the Expire or Max-Age attributes the cookie does not persist in the user’s browser and
is removed when the tab or browser is closed, this is commonly used for session cookies. It is also
recommended that the scope of domains that are able to access the session cookie is limited and
restrictive. This is controlled by the Domain and Path attributes.
3.6 HTTPS and Certificates
HTTPS’ stands for hypertext transfer protocol secure, the secure variety of the hypertext transfer
protocol, which, in turn, is the basis of how we move data on the World Wide Web. Basically, connecting
to a website via ‘HTTPS’ (rather than the standard ‘HTTP’) means that any data that you trade with that
website – whether you’re entering account login information, leaving a comment on a blog, or paying a
parking ticket – will pass over the encrypted transport layer security (TLS) or its predecessor, the secure
sockets layer (SSL).

Hypertext Transfer Protocol Secure (HTTPS) is an extension of the Hypertext Transfer


Protocol (HTTP). It is used for secure communication over a computer network, and is widely used on
the Internet.[1][2] In HTTPS, the communication protocol is encrypted using Transport Layer
Security (TLS) or, formerly, Secure Sockets Layer (SSL). The protocol is therefore also referred to
as HTTP over TLS,[3] or HTTP over SSL.

The principal motivations for HTTPS are authentication of the accessed website, and protection of
the privacy and integrity of the exchanged data while in transit. It protects against man-in-the-middle
attacks, and the bidirectional encryption of communications between a client and server protects the
communications against eavesdropping and tampering.[4][5] The authentication aspect of HTTPS
requires a trusted third party to sign server-side digital certificates. This was historically an expensive
operation, which meant fully authenticated HTTPS connections were usually found only on secured
payment transaction services and other secured corporate information systems on the World Wide Web.
In 2016, a campaign by the Electronic Frontier Foundation with the support of web browser developers
led to the protocol becoming more prevalent.[6] HTTPS is now used more often by web users than the
original non-secure HTTP, primarily to protect page authenticity on all types of websites; secure
accounts; and to keep user communications, identity, and web browsing private. The Uniform Resource
Identifier (URI) scheme HTTPS has identical usage syntax to the HTTP scheme. However, HTTPS
signals the browser to use an added encryption layer of SSL/TLS to protect the traffic. SSL/TLS is
especially suited for HTTP, since it can provide some protection even if only one side of the
communication is authenticated. This is the case with HTTP transactions over the Internet, where
typically only the server is authenticated (by the client examining the server's certificate).

HTTPS creates a secure channel over an insecure network. This ensures reasonable protection
from eavesdroppers and man-in-the-middle attacks, provided that adequate cipher suites are used and
that the server certificate is verified and trusted.

Because HTTPS piggybacks HTTP entirely on top of TLS, the entirety of the underlying HTTP protocol
can be encrypted. This includes the request URL (which particular web page was requested), query
parameters, headers, and cookies (which often contain identifying information about the user). However,
because website addresses and port numbers are necessarily part of the underlying TCP/IP protocols,
HTTPS cannot protect their disclosure. In practice this means that even on a correctly configured web
server, eavesdroppers can infer the IP address and port number of the web server, and sometimes even
the domain name (e.g. www.example.org, but not the rest of the URL) that a user is communicating with,
along with the amount of data transferred and the duration of the communication, though not the content
of the communication.

Web browsers know how to trust HTTPS websites based on certificate authorities that come pre-
installed in their software. Certificate authorities are in this way being trusted by web browser creators
to provide valid certificates. Therefore, a user should trust an HTTPS connection to a website if and only
if all of the following are true:
The user trusts that the browser software correctly implements HTTPS with correctly pre-installed
certificate authorities.

The user trusts the certificate authority to vouch only for legitimate websites.

The website provides a valid certificate, which means it was signed by a trusted authority.

The certificate correctly identifies the website (e.g., when the browser visits "https://example.com", the
received certificate is properly for "example.com" and not some other entity).

The user trusts that the protocol's encryption layer (SSL/TLS) is sufficiently secure against
eavesdroppers.

HTTPS is especially important over insecure networks and networks that may be subject to tampering.
Insecure networks, such as public Wi-Fi access points, allow anyone on the same local network to packet-
sniff and discover sensitive information not protected by HTTPS. Additionally, some free-to-use and
paid WLAN networks have been observed tampering with webpages by engaging in packet injection in
order to serve their own ads on other websites. This practice can be exploited maliciously in many ways,
such as by injecting malware onto webpages and stealing users' private information.[7]

HTTPS is also important for connections over the Tor network, as malicious Tor nodes could otherwise
damage or alter the contents passing through them in an insecure fashion and inject malware into the
connection. This is one reason why the Electronic Frontier Foundation and the Tor Project started the
development of HTTPS Everywhere,[4] which is included in Tor Browser.[8]

As more information is revealed about global mass surveillance and criminals stealing personal
information, the use of HTTPS security on all websites is becoming increasingly important regardless of
the type of Internet connection being used.[9][10] Even though metadata about individual pages that a
user visits might not be considered sensitive, when aggregated it can reveal a lot about the user and
compromise the user's privacy.[11][12][13]

Deploying HTTPS also allows the use of HTTP/2 (or its predecessor, the now-deprecated protocol SPDY),
which is a new generation of HTTP designed to reduce page load times, size, and latency.

It is recommended to use HTTP Strict Transport Security (HSTS) with HTTPS to protect users from man-
in-the-middle attacks, especially SSL stripping.[13][14]

HTTPS should not be confused with the seldom-used Secure HTTP (S-HTTP) specified in RFC 2660.

3.7 Digital Certificate


A digital certificate, also known as a public key certificate, is used to cryptographically link ownership
of a public key with the entity that owns it. Digital certificates are for sharing public keys to be used for
encryption and authentication.

Digital certificates include the public key being certified, identifying information about the entity that
owns the public key, metadata relating to the digital certificate and a digital signature of the public key
the certificate issuer created.

The distribution, authentication and revocation of digital certificates are the primary functions of the
public key infrastructure (PKI), the system that distributes and authenticates public keys.

Public key cryptography depends on key pairs: one private key to be held by the owner and used for
signing and decrypting and one public key that can be used for encrypting data sent to the public key
owner or authenticating the certificate holder's signed data. The digital certificate enables entities to share
their public key so it can be authenticated.
Digital certificates are used in public key cryptography functions most commonly for initializing Secure
Sockets Layer (SSL) connections between web browsers and web servers. Digital certificates are also
used for sharing keys used for public key encryption and authentication of digital signatures.

All major web browsers and web servers use digital certificates to provide assurance that unauthorized
actors have not modified published content and to share keys for encrypting and decrypting web content.
Digital certificates are also used in other contexts, online and offline, for providing cryptographic
assurance and data privacy.

Digital certificates that are supported by mobile operating environments, laptops, tablet
computers, internet of things (IoT) devices, and networking and software applications help protect
websites, wireless networks and virtual private networks.

Digital certificates are used in the following ways:

Credit and debit cards use chip-embedded digital certificates that connect with merchants and banks to
ensure that the transactions performed are secure and authentic.

Digital payment companies use digital certificates to authenticate their automated teller machines, kiosks
and point-of-sale equipment in the field with a central server in their data center.

Websites use digital certificates for domain validation to show they are trusted and authentic.

Digital certificates are used in secure email to identify one user to another and may also be used for
electronic document signing. The sender digitally signs the email, and the recipient verifies the signature.

Computer hardware manufacturers embed digital certificates into cable modems to help prevent the theft
of broadband service through device cloning.

As cyberthreats increase, more companies are considering attaching digital certificates to all of the IoT
devices that operate at the edge and within their enterprises. The goals are to prevent cyberthreats
and protect intellectual property.

Issue of Digital Certificate


An entity can create its own PKI and issue its own digital certificates, creating a self-signed certificate.
This approach might be reasonable when an organization maintains its own PKI to issue certificates for
its own internal use. But certificate authorities (CAs) -- considered trusted third parties in the context of
a PKI -- issue most digital certificates. Using a trusted third party to issue digital certificates enables
individuals to extend their trust in the CA to the digital certificates it issues.

Digital certificates vs. digital signatures


Public key cryptography supports several different functions, including encryption and authentication,
and enables a digital signature. Digital signatures are generated using algorithms for signing data so a
recipient can irrefutably confirm the data was signed by a particular public key holder.

Digital signatures are generated by hashing the data to be signed with a one-way cryptographic hash; the
result is then encrypted with the signer's private key. The digital signature incorporates this encrypted
hash, which can only be authenticated, or verified, by using the sender's public key to decrypt the digital
signature and then running the same one-way hashing algorithm on the content that was signed. The two
hashes are then compared. If they match, it proves that the data was unchanged from when it was signed
and that the sender is the owner of the public key pair used to sign it.
A digital signature can depend on the distribution of a public key in the form of a digital certificate, but
it is not mandatory that the public key be transmitted in that form. However, digital certificates are signed
digitally, and they should not be trusted unless the signature can be verified.

Types of Digital Certificates


Web servers and web browsers use three types of digital certificates to authenticate over the internet.
These digital certificates are used to link a web server for a domain to the individual or organization that
owns the domain. They are usually referred to as SSL certificates even though the Transport Layer
Security protocol has superseded SSL. The three types are the following:

Domain-validated (DV) SSL certificates offer the least amount of assurance about the holder of the
certificate. Applicants for DV SSL certificates need only demonstrate that they have the right to use the
domain name. While these certificates can ensure the certificate holder is sending and receiving data,
they provide no guarantees about who that entity is.

Organization-validated (OV) SSL certificates provide additional assurances about the certificate holder.
They confirm that the applicant has the right to use the domain. OV SSL certificate applicants also
undergo additional confirmation of their ownership of the domain.

Extended validation (EV) SSL certificates are issued only after the applicant proves their identity to the
CA's satisfaction. The vetting process verifies the existence of the entity applying for the certificate,
ensures that identity matches official records and is authorized to use the domain, and confirms that the
domain owner has authorized issuance of the certificate.

The exact methods and criteria CAs follow to provide these types of SSL certificates for web domains is
evolving as the CA industry adapts to new conditions and applications.

There are also other types of digital certificates used for different purposes:

Code signing certificates may be issued to organizations or individuals who publish software. These
certificates are used to share public keys that sign software code, including patches and software updates.
Code signing certificates certify the authenticity of the signed code.

Client certificates, also called a digital ID, are issued to individuals to bind their identity to the public
key in the certificate. Individuals can use these certificates to digitally sign messages or other data. They
can also use their private keys to encrypt data that recipients can decrypt using the public key in the client
certificate.

Digital certificate benefits


Digital certificates provide the following benefits:

Privacy. When you encrypt communications, digital certificates safeguard sensitive data and prevent the
information from being seen by those unauthorized to view it. This technology protects companies and
individuals with large troves of sensitive data.

Ease of use. The digital certification process is largely automated.

Cost effectiveness. Compared to other forms of encryption and certification, digital certificates are
cheaper. Most digital certificates cost less than $100 annually.

Flexibility. Digital certificates do not have to be purchased from a CA. For organizations that are
interested in creating and maintaining their own internal pool of digital certificates, a do-it-yourself
approach to digital certificate creation is feasible.
Digital certificate limitations
Some limitations of digital certificates include the following:

Security. Like any other security deterrent, digital certificates can be hacked. The most logical way for a
mass hack to occur is if the issuing digital CA is hacked. This gives bad actors an on-ramp into
penetrating the repository of digital certificates the authority hosts.

Slow performance. It takes time to authenticate digital certificates and to encrypt and decrypt. The wait
time can be frustrating.

Integration. Digital certificates are not standalone technology. To be effective, they must be properly
integrated with systems, data, applications, networks and hardware. This is no small task.

Management. The more digital certificates a company uses, the greater the need to manage them and to
track which ones are expiring and need to be renewed. Third parties can provide these services, or
companies can opt to do the job themselves. But it can be expensive.

3.8 Application Vulnerabilities and Defenses


How Web Application Vulnerabilities Affect Companies

First, let’s try to gain a better understanding of how exactly these website application vulnerabilities can
affect a company. This will help you understand just how harmful these security attacks can be and why
you should prioritize preventing them.

One of the biggest, most harmful web application security threats is sensitive data exposure. It even ranks
among the OWASP top 10 vulnerabilities. It involves compromising important data that should have been
protected. This includes data like passwords, credentials, personally identifiable information, social
security numbers, credit card numbers, health information, etc.

This is one of the most targeted web application vulnerabilities by hackers since there’s a prospect for
financial gain for them. They could sell this data or use it themselves to conduct fraud, identity theft, etc.

There are tons of ways for hackers to steal sensitive data through web security vulnerabilities:

They may look for SQL injection flaws to retrieve decrypted credit card numbers.

They could exploit insecure wireless networks to seal a user’s session cookie.

Attackers could even retrieve sensitive files from the server using a file download vulnerability, or upload
malicious files to target your users!

In some cases, you may even encounter Cross-Site Scripting (XSS). This is one of the most widespread
website application vulnerabilities and involves utilizing the website as a propagation method. Hackers
would inject malicious client-side scripts and modify how the website functions or how it is displayed.

An XSS attack could infect your visitors’ devices with malware or have them recruited into large botnets.
It could mislead your visitors and damage your credibility and reputation, which can be extremely
difficult to rebuild.

These are just a few ways in which hackers can exploit web application vulnerabilities and cause serious
harm to your company and its customers. But even from this, you can clearly see just how damaging
these attacks can be and how crucial it is to prevent them. We need to take web application security
threats seriously and turn our development teams into security champions.
Understanding the Common Web Application Vulnerabilities
Now let’s take a look at some of the most common attacks that hackers might attempt on your website.
Knowing these common web application vulnerabilities will help you identify them faster and fix them
more easily.

1: SQL Injection
Many hackers start with an attempt to gain access to the database through SQL injection attacks. This is
when the attacker inserts malicious SQL statements into form fields and other injection points, with the
intention of gathering information from and controlling the database. They can use this information to
access and modify or even destroy the information, and to attack the underlying system.

Attackers typically use these attacks to collect vital customer information such as their contact
information, passwords, or even credit card info. They may even exploit these web security
vulnerabilities to change the price of a product, for instance. Advanced attacks can even allow them to
control the database server and the operating system.

How to Prevent It
Prepared statements with parameterized queries can mitigate SQL-related web application
vulnerabilities. A prepared statement helps to sanitize the input and ensures that it is considered as a
string literal in SQL rather than as part of the SQL query. In other words, the database can tell the
difference between SQL data and SQL code. So the code is no longer vulnerable to SQL injection attacks
as the query is less vulnerable to tampering.

Migrating to Object Relational Mapping Tools (ORMs) is another excellent option. However, most
ORMs allow non-parameterized queries in addition to performing parameterized queries. As such, it’s
crucial to carefully use the frameworks keeping this in mind.

Make the most of LIMIT and other SQL controls within your queries so that even if an SQL injection
attack does occur, it can prevent the mass disclosure of records.

2: Cross-Site Scripting (XSS)


As mentioned earlier, cross-site scripting or XSS is one of the most popular web application
vulnerabilities that could put your users’ security at risk. These attacks inject malicious code into the
running application and executes it on the client-side.

The goal of XSS attacks is to send this malicious code to other users, sometimes infecting their devices
with malware or stealing sensitive information. This type of website application vulnerability can give
the attacker full control of the user’s browser and can be extremely dangerous to any website.

How to Prevent It
Modern frameworks have made it a lot easier to escape untrusted user input and mitigate XSS attacks.
AngularJS, React JS, and Ruby on Rails are some of the latest, most effective frameworks to prevent
these web application vulnerabilities. These frameworks can automatically escape user input and help
mitigate XSS attacks by design, although they do have limitations.

Avoid implementing a blacklist, instead favor of a whitelist, because blacklists are less effective at
preventing web security vulnerabilities. An attacker who knows what they’re doing can easily bypass a
blacklist filter.

The ultimate solution to prevent these web application vulnerabilities is output encoding. This involves
converting untrusted user input into a safe form so the input is displayed to the user as data without being
executed as code in the browser. This means that special characters will be translated into an equivalent
form that the browser will no longer find significant.

It’s also important to understand that output encoding depends on the context of where data is being
output. For instance, you may have HTML contexts, HTML entity contexts, HTML attribute contexts,
CSS contexts, JavaScript contexts, and more. As such, you will need to apply context-sensitive encoding
when render the page for the browser.

Enable a Content Security Policy (CSP), which can be very effective to help mitigate Cross-Site Scripting
vulnerabilities.

3: Authentication Failure
Authentication-related web application vulnerabilities occur when there’s an improper implementation
of adequate user authentication controls. This puts user accounts at risk of being breached. Attackers
may exploit these web security vulnerabilities to gain control over any user account or even over the
entire system.

One of these vulnerabilities is Credential Stuffing, where an attacker will test a list of valid passwords
and usernames gleaned from another breach or attack until they manage to find a valid combination and
gain access.

Another common vulnerability is a Brute Force attack, in which the attacker tries every possible character
combination until they find a valid one.

Session hijacking is another common attack that can occur as a result of authentication failure. This is
when there is a failure to properly invalidate session IDs, allowing attackers to exploit an authenticated
session of a legitimate user.

How to Prevent It
One of the essential steps to avoid these web application vulnerabilities is to allow enough time for
developers to test the code before it gets deployed to production. External security audits can also help
ensure that you apply the best practices of website security.

Avoid deploying with default credentials, especially for admins.

Wherever possible, make sure you implement multi-factor authentication to make your system less
vulnerable to the attacks mentioned above.

Put a limitation or delay on failed login attempts. Make sure you log all failures and notify administrators
when there’s an attack attempt.

Avoid unnecessarily restricting input size. If you allow more characters, there are fewer chances for
attackers to guess the right password.

Have some form of lockout in place to prevent brute force attacks and minimize these web application
vulnerabilities.

Use adaptive hashing algorithms like bcrypt, pbkdf2, argon2, etc. to salt passwords and hash them before
storing them in the database

Implement weak-password checks for better password security. This would include testing new or
changed passwords and comparing them against a list of compromised or weak passwords. Use of a
service to check for compromised passwords (such as Have I Been Pwned) helps to automate this
functionality and keeps the list of compromised passwords up to date as new attacks occur.
4: Security Misconfiguration
Security misconfigurations provide attackers with an easy way into your website, making it one of the
most critical web application vulnerabilities that you need to prevent.

Unused pages, unpatched flaws, unprotected files and directories, and default configurations, are some
of the security misconfigurations that attackers can leverage to gain unauthorized access.

Every level of your application stack can be vulnerable to security misconfigurations. This includes your
web server, platform, database, network services, storage, frameworks, application server, and more.

If attackers manage to exploit these web application vulnerabilities, they can access sensitive information
and take control of user and admin accounts.

How to Prevent It
Make sure you use encrypted (HTTPS) connections to transfer data and information between the users
and the application.

Have a repeatable hardening process that you can quickly and easily deploy on another environment.
This will save time in setting up a new and secure environment as you’ll be able to automate the process.

Perform all remote admin tasks through secured channels to minimize these web application
vulnerabilities. Even if you do have to use protocols that don’t support strong encryption, make sure you
activate them over a secondary encryption channel such as IPSEC, or TLS.

Regularly conduct file integrity checking to ensure that there haven’t been any unauthorized changes to
critical files. Use file integrity checking tools that can accept routine and expected changes while alerting
you of any unexpected or unusual changes.

Have an automated process in place to regularly verify the effectiveness of your settings and
configurations in every environment. You can use an automated configuration monitoring tool that can
alert you of any unauthorized changes. This will help you identify these web application vulnerabilities
before they cause any damage.

Keep your platform minimal and avoid adding unnecessary features, samples, documentation, and
components. If you have unused features and frameworks in the platform, it’s best to remove them to
prevent web application vulnerabilities.

5: XML External Entities


An XML external entity attack, also known as an XXE, or an XML injection attack, is another class of
vulnerabilities you should watch out for. These types of attacks occur when attackers exploit a weakly-
configured XML parser. Through such attacks, attackers can inject additional data, access confidential
data, and execute applications and create remote tunnels (shells).

XML external entity attacks can also result in remote code execution, Server Side Request Forgery
(SSRF), and more. By default, most XML parsers are prone to these attacks. This leaves it up to the
developers to ensure that their web application is free from these web application vulnerabilities.

How to Prevent It
Completely disabling Document Type Definitions (DTD’s), also known as External Entities, is the safest
way to prevent XXE attacks. This secures the parser against DoS attacks. However, it may not always
be possible to completely disable DTDs. In this case, you need to disable external document type
declarations and external entities in a specific way for each parser.
Whenever possible, you should try using less complex data formats like JSON. It’s also good to avoid
serialization of sensitive data to avoid these website application vulnerabilities.

Implement a positive, server-side method to validate, sanitize, and filter input. This will help prevent the
occurrence of hostile data within your XML documents, nodes, and/or headers and help you avoid XXE-
related web application vulnerabilities.

Patch or upgrade all the XML processors and libraries that the application or its underlying OS is using.

While the best solution is to use manual code review for critical functionality in large and complex
applications, you should also use SAST tools to detect XXE in source code.

Use XSD validation or an equivalent alternative to validate the incoming XML structure.

6: Broken Access Control (Authorization Failure)


Access control helps you control what sections of a website and what application data different visitors
can access.

For instance, if your website is a platform for different sellers to list their products, they will need some
kind of access to add new products and manage their sales. However, not every visitor will need that
level of access since most of them are visiting your site to buy products.

As such, having a broken access control opens up your site to web application vulnerabilities, which
attackers can exploit to access sensitive information or unauthorized functionality. They might even use
these attacks to make modifications to access rights and user data.

How to Prevent It
It’s crucial to maintain a security-first policy when developing and configuring software.

Except for public resources, deny access by default.

Make sure you apply protection horizontally (across all data) and vertically (across all levels of access
privileges). Vertical protection involves employing the least privilege concept wherein access is granted
only in accordance to their

Centralize all authorization decisions to minimize the occurrence of access-related web application
vulnerabilities.

Instead of letting users freely create, read, modify, or delete any record, use model access controls to
enforce record ownership. Remove their ability to read or modify data from other users.

Implement a one-time access control mechanism that you can reuse through the 1.

Set limitations to API and controller access to reduce the risk of attacks by automated tools.

Invalidate JWT tokens and user sessions on the server after logout.

Disable webserver directory listing and also prevent web roots from storing backup files and file
metadata.
3.9 Client Side Security
Definition
Client-side processing, in general, is an application design principle that moves app functionality into
the client, or user’s computer. In a client-server relationship of this type, the client conducts some level
of application processing on the user’s computer before sending information to the server for further
processing. Client-side processing has many benefits, including relieving processing stress on the server
and creating a customized user experience.

When security is placed client-side, a problem arises. The security controls are now in the hands of the
user. Most users are not malicious nor technically capable of exploiting this control, but a skilled
malicious user can easily bypass controls that are placed in their hands.

Specific Examples

Multiple vulnerabilities existed in this web app, but two serve as good examples of bypassed Client-side
security: CAPTCHA with a client-side invocation and file upload functionality with client-side file
restrictions.

Client-side web security


To address attacks such as XSS, Magecart and other card skimming exploits found in modern
eCommerce environments, the use of client-side web security methods is beginning to emerge as a
particularly useful practice.

Obviously, enterprise teams should integrate client-side protections with desired server-side
countermeasures to ensure a full risk management profile (e.g., the client-side is a poor selection point
to stop denial of service).

Several standards-based client-side security approaches have begun to mature that are worth examining
from the perspective of website security and protection of browser sessions from malicious exploits. The
best client-side security platforms automate implementation of these standards-based controls with
emphasis on simplicity of administration. A typical, representative platform is used to demonstrate
necessary client-side security controls.

Content security policy


To understand client-side security platforms, it helps to first explore the specifics of a standard approach
known as a content security policy (CSP). This is a standard that is designed to address several types of
web breaches such as cross-site scripting, click-jacking and form-jacking (all described earlier in this
article series). CSP is also designed to reduce the risk of client-side malware injected from an infected
advertising ecosystem.

CSPs are implemented as standard directives involving HTTP headers or page tags that specify which
domains, subdomains, and resources a browser can load from a website. CSP use is consistent with the
browsers any user would likely use including Chrome, Firefox, Safari, and Edge. The goal is that if
malicious code is resident on a site, then visitors to that site would be prevented by the CSP from being
directed to the hacker’s domain.
Figure 3.1. Content security policy

The example shown above in Figure 1 is taken directly from the original W3 recommendation. The CSP
code can be interpreted as follows: Each source expression represents the location where content of the
type specified is allowed to be pulled. To illustrate this whitelist security operation, consider that
the self keyword-source designation, in the example above, represents the set of URIs in the origin as the
protected website.

Companies like Google have rolled out CSP successfully and are using it to stop attacks against their
web applications daily. However, CSP is deployed only lightly in most web application environments.
The challenge with CSP implementation has been its complex administration. Tala Security researchers
have found, for example, that roughly two percent of website operators in the top Alexa 1000 websites
deploy the standard to prevent client-side attacks. Assisting with this administrative challenge is a
primary motivation for client-side platforms.

Client-side security protection results from using CSP can websites can be quite impressive. Here are
some observed statistics from the Tala Security research team based on their experiences with client-side
security support:

Images – The average website in the Alexa 1000 loads images from roughly sixteen different external
domains. The img-src directive in CSP blocks images from any unwanted or potentially malicious sites.

Stylesheets – The average website in the Alexa 1000 loads stylesheets from roughly two different
external domains. The style-src directive in CSP blocks stylesheet loads from any unwanted or
potentially malicious sites.

Fonts – The average website in the Alexa 1000 loads images from roughly one-and-a-half different
external domains. The font-src directive in CSP blocks font downloads from any unwanted or potentially
malicious sites.

Media – The average website in the Alexa 1000 loads images from different external domains.
The media-src directive in CSP blocks font downloads from any unwanted or potentially malicious sites.

Subresource integrity
An additional applicable cyber security standard from the World Wide Web Consortium (W3C) is known
as subresource integrity (SRI). This standard is designed to validate resources being served up by any
third party on a visited website. Such third parties include content distribution networks (CDNs), where
it has not been uncommon to find malicious code being offered up to unsuspecting websites.

SRI is implemented through cryptographic hash functions which finger-print JavaScript being offered
by third parties. Browsers can then fetch a resource, check the cryptographic hash value – which include
the location of the resource, and then make a policy decision about whether to accept the resource. This
capability is supported in all important browsers, and significantly reduces the risk of malware from third
party actors.

Client-side security platform


Client-side security platforms will make use of both CSP and SRI to provide effective client-side
protections. The goal of these platform is to provide policy-based mitigation of fine-grained behavior for
third-party sources where content is being served. Client-side platforms can then watch for any data
collection suggestive of the attacks used by Magecart (and similar groups).

The client browser mitigation should be implemented based on artificial intelligence-based classification
and learning. The software should install quickly and easily. Commercial platforms should support
implementation for many target environments including Apache Nginx, IIS, NodeJS, and others.
Performance and latency impacts should also be essentially non-existent and non-affecting of the user
experience. Specific capabilities included in a commercial platform should include:

Indicator evaluation – The selected platform should be designed to evaluate many different indicators of
a web page’s architecture to analyze code, content, connections, and data exchange.

Behavioral and risk modeling – The platform should include support for analysis to inform a behavioral
and risk modeling task designed to highlight normal behavior and expose vulnerabilities.

Operational improvement – Insights gained from the platform evaluation and modeling should be made
available to help prevent client-side attacks such as XSS, Magecart, and the like.

The operation of world-class client side security platforms should include an on-going interaction
between four different activities: Build, Monitor, Block, and Respond. The connection flow between
these different lifecycle phases is depicted below.

Figure 3.2. Commercial client-side security lifecycle

Information model
Client-side security platforms should implement some type of information model that can be used to
analyze the different behaviors on pages from the customer’s website to be protected. The security
objective for such extraction should be to explicitly identify any sources of code and content on these
web pages, as well as to find any data exchange support options that could involve sensitive data.
The resultant behavioral information model will thus provide a functional baseline on which to perform
the necessary client-side risk management. The goal obviously should be to determine in real-time
whether the site is vulnerable to attacks, third-party insertion, or other advanced breaches. As one would
expect, performance of such behavioral modeling and protection in real-time complements any existing
server-side security tools.

3.10 Cookies Security Policy


Cookie Policy
A cookie is a string of information that a website stores on a visitor’s computer, and that the visitor’s
browser provides to the website each time the visitor returns. Carrigtwohill Pharmacy uses cookies to
help it identify and track visitors, their usage of Carrigtwohill Pharmacy website, and their website access
preferences. Carrigtwohill Pharmacy visitors who do not wish to have cookies placed on their computers
should set their browsers to refuse cookies before using the Carrigtwohill Pharmacy website, with the
drawback that certain features of the Carrigtwohill Pharmacy website may not function properly without
the aid of cookies.

Carrigtwohill Pharmacy is committed to providing you with the best online experience while visiting our
website. As part of this process, we utilise standard third party cookies to obtain data about your
behaviour online while you are on our sites, and we also track information about the number of times our
site is visited and the number of people who return to our site.

We track all information as an aggregate and therefore we do not collect any personal
information about you as an individual, unless you apply for a job, upload your CV, fill in a form on our
site, or sign up for email alerts through our site.

What we track
We use Google Analytics on this website. This enables us to make sure we are offering the best service
possible to our customers. Google Analytics uses cookies to track the visits we have to the website and
the interactions the visitor has with the website. For more information on Google Analytics and how to
opt out of this and block cookies please visit Google’s Privacy Policy.

Our shopping cart system (WooCommerce) and our checkout mechanism (PayPal) also use cookies.
Some of these cookies are sessional and are required for the payment process to work and no longer have
an effect once you have logged out of the site. Others remain on your internet browser once you have
left the site. For information on how PayPal use cookies and on blocking, deleting or disabling cookies,
please see the PayPal Privacy Policy.

If you do not wish us to track your cookie information you can set your browser to reject cookies, please
visit the ‘Help’ menu of your Internet browser to find out how to do this. This may impact your user
experience on our site and restrict you from utilising certain site functionality.

How to manage cookies


Our cookies do not store financial information or information which is capable of directly identifying
you (such as your name or address). Cookies simply allow our website to retrieve this information in
order to track your experience.

3.11 Plugins
 In computing, a plug-in (or plugin, add-in, addin, add-on, or addon) is a software
component that adds a specific feature to an existing computer program. When a program
supports plug-ins, it enables customization.
 A theme or skin is a preset package containing additional or changed graphical appearance
details, achieved by the use of a graphical user interface (GUI) that can be applied to specific
software and websites to suit the purpose, topic, or tastes of different users to customize the
look and feel of a piece of computer software or an operating system front-end GUI
(and window managers).

 Plugins are external pieces of software that work in tandem with certain programs to offer
additional function.

 Eg, flash player is a plugin because flash is not a program installed in your browser; it is a bit
of software installed separately which then works with the browser to render flash content.

 Similarly many media players have plugins which work with the browser to support certain
file formats such that they can be played in the browser.

Example of plugin are:

 Adobe Acrobat

 Adobe Flash

 Java

 QuickTime

 RealPlayer

 Shockwave

 Silverlight

 VRML

 X3D

Applications may support plug-ins to:

 enable third-party developers to extend an application

 support easily adding new features

 reduce the size of an application by not loading unused features

 Separate source code from an application because of incompatible software licenses.

Types of applications and why they use plug-ins:

 Digital audio workstations and audio editing software use audio plug-ins to generate, process
or analyze sound. Ardour, Audacity, Cubase, FL Studio, Logic Pro X and Pro Tools are
examples of such systems.

 Email clients use plug-ins to decrypt and encrypt email. Pretty Good Privacy is an example of
such plug-ins.

 Video game console emulators often use plug-ins to modularize the separate subsystems of
the devices they seek to emulate.[2][3][4][5][6][7][8][9][10] For example, the PCSX2 emulator makes
use of video, audio, optical, etc. plug-ins for those respective components of the PlayStation 2.
 Graphics software use plug-ins to support file formats and process images. A Photoshop
plugin may do this.

 Media players use plug-ins to support file formats and apply


filters. foobar2000, GStreamer, Quintessential, VST, Winamp, XMMS are examples of such
media players.

 Packet sniffers use plug-ins to decode packet formats. OmniPeek is an example of such packet
sniffers.

 Remote sensing applications use plug-ins to process data from different sensor
types; e.g., Opticks.

 Text editors and Integrated development environments use plug-ins to support programming
languages or enhance the development process e.g., Visual Studio, RAD Studio, Eclipse, IntelliJ
IDEA, jEdit and MonoDevelop support plug-ins. Visual Studio itself can be plugged into other
applications via Visual Studio Tools for Office and Visual Studio Tools for Applications.

 Web browsers have historically used executables as plug-ins, though they are now
mostly deprecated. Examples include the Adobe Flash Player, a Java virtual machine (for Java
applets), QuickTime, Microsoft Silverlight and the Unity Web Player. (Browser extensions,
which are a separate type of installable module, are still widely in use.)

Mechanism of Plugin

The host application provides services which the plug-in can use, including a way for plug-ins to
register themselves with the host application and a protocol for the exchange of data with plug-ins.
Plug-ins depend on the services provided by the host application and do not usually work by
themselves. Conversely, the host application operates independently of the plug-ins, making it possible
for end-users to add and update plug-ins dynamically without needing to make changes to the host
application.

Programmers typically implement plug-ins as shared libraries, which get dynamically loaded at run
time. HyperCard supported a similar facility, but more commonly included the plug-in code in the
HyperCard documents (called stacks) themselves. Thus the HyperCard stack became a self-contained
application in its own right, distributable as a single entity that end-users could run without the need for
additional installation-steps. Programs may also implement plugins by loading a directory of
simple script files written in a scripting language like Python or Lua.

Figure 3.1. Plugin framework


3.12 Extensions
A browser extension is a small software module for customizing a web browser. Browsers typically
allow a variety of extensions, including user interface modifications, ad
blocking, cookie management, web form recovery, and browsing session exporting.

Browser plug-ins are a separate type of module. The main difference is that extensions are usually
just source code, but plug-ins are always executables (i.e. object code). As of 2021, plug-ins have
been deprecated by most browsers, while extensions are widely used. The most popular
browser, Google Chrome,[2] has over 100,000 extensions available but no longer supports plug-ins.

Extensions are small software’s that can provide you with difference options and can enhanced the
functionality. Like the extensions for Google Chrome can allow you to do different things by using the
Extensions. You can write your own chrome extensions by using simple web technologies which are
common like HTML, CSS or JavaScript. Examples have no user interface, they provide you with
simple buttons to enable or disable the function it gives. A common and most used extension is
Adblock which is being used by many users. Adblock allows you to block all of the ads available in the
webpage you are visiting.

Extensions, or “add-ons”, can often do these magical things. They can add onto the browser UI,
process pages that the browser loads.

They do all sorts of things. However, they are not the same thing as plugins; they affect the web
browser itself, not really the page. They may affect a page as well. In fact, you can even put a plugin
inside an extension( at least in Firefox).

However, if you write an extension for Firefox, you’ll probably have to write it again for Chrome,
Safari, and IE… one for each. Perhaps there is a framework out there for writing portable extensions,
though.

3.13 Web User tracking tools


 AWStats comes pre-installed by many web hosting companies. Additionally, if you’re setting
up your own servers, you can download it for your personal use. AWStats goes deeper into the
referring sites’ information than most analytics packages, and is a perfect tool for monitoring
whether someone is hotlinking files from your site. Besides being a great detective tool for
bandwidth thieves, it offers all of the usual useful tools that you might expect from a statistics
package.

 eLogic provides three levels of service based on your exact needs. If you need to track only
one or two pages, they offer a stat counter that just offers you the most basic of reports. Their
Webstats BASIC package is also free, but gives you more the usual tools you expect like
referring sites, a history, demographics, and more. Finally if you’re a business or a larger site,
you may sign up for their subscription program, Webstats PRO, that will give you a full
history and more extensive tools

 Google Analytics is arguably the most popular analytics package available for individual site
owners. Google Analytics (or plain old “GA”) allows you to dig down deep into your stats to
see breakdowns of individual regions, states/provinces, cities and numerous other items to
better identify your site visitors. The wealth of data available is admirably balanced by a well-
executed user interface, but it can still be overwhelming. The package integrates with
AdWords and has ecommerce-specific tools to track sales.

 ShinyStat was initially designed to monitor visits to Italian web sites. Now it is available to
sites all over the world, and offers software packages for the individual user, the professional
user who needs to track marketing, and a business owner who needs to monitor sales and ROI.
There is also a level of service for ISPs to install and include with their hosting accounts.
 SiteMeter has a free version for smaller bloggers with up to 100,000 monthly visitors that
offers all of the usual tools a webmaster can expect such as tracking referrals, visit durations
and so on. If you are launching a larger site and need more tools, there is a paid version based
on your volume of visitors.

 StatCounter might have a rather plain interface, but it deftly handles multi-author blogs,
allowing you to easily assign unique codes to each author. While it is free and does work, you
have to click on a link to see each analytic result on a separate page. Despite its unpolished
looks, the site does offer you clearly readable stats on things such as keywords, traffic sources,
and other useful information.

 W3Counter comes in a free and paid version. With a free W3Counter account, you can track
up to 5,000 page views a day across 10 websites and see all of the usual stats. In addition, you
get a bonus that you can share your stats with anyone you like via widgets for your blog or an
API that lets you build new tools. For sites with higher traffic, you can go for the Pro account
that allows you to track up to 1 million views a month.

 W3Perl differs from other analytics packages in that it doesn’t just measure web traffic, but
also can parse the log files of email and RSS to measure just about anything you choose. You
can set up the administration interface for web access and gain real-time stats from there.

 Webalizer is written in C, which means that it is extremely fast, and is a favorite choice of
people who host their own servers. Many web hosts have this analytics package pre- installed
for your use inside of their control panel. Webalizer doesn’t allow you to dive terribly in-
depth into your data like some other packages, but it provides an excellent overview.

 Woopra is currently in a closed beta test, but it offers you a wealth of data for those who can
get in. Real-time data are streamed from your site that appear on a map letting you graphically
see where readers are coming from, what keywords brought them in, and referring sites.
Woopra offers you a unique ability to open up a chat window with visitors of your choice as
they browse your site. An unusual feature of this service is that the data is presented to you in
a desktop application. WordPress users can install a plugin that lets them see this data in the
dashboard of their blog.

3.14 Web Application Firewall and Fuzzers


 A web application firewall (WAF) is an appliance, server plugin, or filter that applies a set of
rules to an HTTP conversation. Generally, these rules cover common attacks such as: cross-
site scripting (XSS) and SQL injection. By customizing the rules to your application,
many attacks can be identified and blocked.

 A Web application firewall (WAF) is a firewall that monitors, filters or blocks the HTTP traffic
to and from a Web application

 A WAF can be either network-based or host-based and is typically deployed through a proxy
and placed in front of one or more Web applications. In real time or near-real time, it monitors
traffic before it reaches the Web application, analyzing all requests using a rule base to
filter out potentially harmful traffic or traffic patterns. Web application firewalls are a
common security control used by enterprises to protect Web applications against zero-day
exploits, impersonation and known vulnerabilities and attackers.

Need of Web Application Firewalls

1. Web applications are unsecured.

2. Developers should, try to build better/more secure software.


3. But in the meantime, system administrators must try to secure deployment of web
applications.

4. WAFs are an important building block in every HTTP network.

Fuzzers

 A Security fuzzer is a tool used by security professionals (and professional hackers :) to test a
parameter of an application.

 Typical fuzzers test an application for buffer overflows, format string vulnerabilities, and error
handling.

 More advanced fuzzers incorporate functionality to test for directory traversal attacks,
command execution vulnerabilities, SQL Injection and Cross Site Scripting
vulnerabilities.

 Web Vulnerability scanners typically perform all of this functionality, and can be considered
an advanced fuzzer.

 Fuzzing is to execute a program on many abnormal inputs, look for badness.

 Goal: Prevent attackers from encountering exploitable errors

Automatically generate test cases

Many slightly anomalous test cases are input into a target interface

Popular free fuzzers include SPIKE Proxy, Peach Fuzzer Framework, and WebScarab.

Fuzz testing or fuzzing is a software testing technique used to discover coding errors and security loop-
holes in software, operating systems or networks by inputting massive amounts of random data, called
fuzz, to the system in an attempt to make it crash. If vulnerability is found, a tool called a fuzz tester (or
fuzzer), indicates potential causes. Fuzz testing was originally developed by Barton Miller at the
University of Wisconsin in 1989

Fuzzers work best for problems that can cause a program to crash, such as overflow, cross site
scripting, denial of service attacks, format, bugs and SQL injection. These schemes are often used by
malicious hackers intent on wreaking the greatest possible amount of havoc in the least possible time.
Fuzz testing is less effective for dealing with security threats that do not cause program crashes, such as
spyware, some viruses, worms, Trojans and keyloggers.

Fuzz testing is simple and offers a high benefit-to-cost ratio. Fuzz testing can often reveal defects that
are overlooked when software is written and debugged. Nevertheless, fuzz testing usually finds only
the most serious faults. Fuzz testing alone cannot provide a complete picture of the overall security,
quality or effectiveness of a program in a particular situation or application. Fuzzers are most effective
when used in conjunction with extensive black box testing, beta testing and other proven debugging
methods.

Mutation Based Fuzzing (Dumb Fuzzing)

 Little or no knowledge of the structure of the inputs is assumed

 Anomalies are added to existing valid inputs

 Anomalies may be completely random or follow some heuristics (e.g. remove NUL, shift
character forward)

Dumb Fuzzing In Short


 Strengths

 Super easy to setup and automate

 Little to no protocol knowledge required

Weaknesses

 Limited by initial corpus

 May fail for protocols with checksums, those which depend on challenge response,
etc.

Generation Based Fuzzing

 Test cases are generated from some description of the format.

 Anomalies are added to each possible spot in the inputs

 Knowledge of protocol should give better results than random fuzzing

 Strengths

 completeness

 Can deal with complex dependencies e.g. checksums

Weaknesses

 Have to have spec of protocol

 Often can find good tools for existing protocols e.g. http, SNMP

 Writing generator can be labor intensive for complex protocols

 The spec is not the code

Fuzzing Tools- Input Generation

 Existing generational fuzzers for common protocols (ftp, http, SNMP, etc.)

 Mu-4000, Codenomicon, PROTOS, FTPFuzz

Fuzzing Frameworks: You provide a spec, they provide a fuzz set

 SPIKE, Peach, Sulley

Dumb Fuzzing automated: you provide the files or packet traces, they provide the fuzz sets

 Filep, Taof, GPF, ProxyFuzz, PeachShark


Solved questions

Q1. When I try to view a secure page, the browser complains that the site certificate doesn't match the
server and asks me if I wish to continue. Should I??
Ans. The host name of the Web server is an unalterable part of the site certificate. If the name of the host
doesn't match the name on the certificate, the browser will notice this fact and alert you of the
problem. Sometimes this is merely an innocent server misconfiguration, but it can also be evidence
that a server certificate has been stolen and is being used to fool you. In most cases, it's best to abort
the transmission.

You may occasionally see a similar message that warns you that the server's certificate has expired.
This may mean that the Webmaster hasn't renewed the site's certificate in a timely fashion, or may
again indicate that the certificate has been stolen and is being misused. Again, the safest course is
to abort the transmission.

Q2. How secure is the encryption used by SSL?


Ans. SSL uses public-key encryption to exchange a session key between the client and server; this session
key is used to encrypt the http transaction (both request and response). Each transaction uses a
different session key so that if someone manages to decrypt a transaction, that does not mean that
they've found the server's secret key; if they want to decrypt another transaction, they'll need to
spend as much time and effort on the second transaction as they did on the first.
Netscape servers and browsers do encryption using either a 40-bit secret key or a 128-bit secret
key. Many people feel that using a 40-bit key is insecure because it's vulnerable to a "brute force"
attack (trying each of the 2^40 possible keys until you find the one that decrypts the message). This
was in fact demonstrated in 1995 when a French researcher used a network of workstations to crack
a 40-bit encrypted message in a little over a week. It is thought that with specialized hardware, 40-
bit messages can be cracked in minutes to hours. Using a 128-bit key eliminates this problem
because there are 2^128 instead of 2^40 possible keys. To crack a message encrypted with such a
key by brute force would take significantly longer than the age of the universe using conventional
technology. Unfortunately, many Netscape users have browsers that support only 40-bit secret
keys. This is because of legal restrictions on the encryption software that can be exported from the
United States.

Q3. How are digital certificates used?

Ans. Digital certificates are used in the following ways:


Credit and debit cards use chip-embedded digital certificates that connect with merchants and banks
to ensure that the transactions performed are secure and authentic.
Digital payment companies use digital certificates to authenticate their automated teller machines,
kiosks and point-of-sale equipment in the field with a central server in their data center.
Websites use digital certificates for domain validation to show they are trusted and authentic.
Digital certificates are used in secure email to identify one user to another and may also be used for
electronic document signing. The sender digitally signs the email, and the recipient verifies the
signature.
Computer hardware manufacturers embed digital certificates into cable modems to help prevent the
theft of broadband service through device cloning.

Q4. Who can issue a digital certificate?

Ans. An entity can create its own PKI and issue its own digital certificates, creating a self-signed
certificate. This approach might be reasonable when an organization maintains its own PKI to issue
certificates for its own internal use. But certificate authorities (CAs) -- considered trusted third
parties in the context of a PKI -- issue most digital certificates. Using a trusted third party to issue
digital certificates enables individuals to extend their trust in the CA to the digital certificates it
issues.

Objective Type Questions

Q1. Which of the following is used for session management?

a) Persisting the session in database


b) URL rewriting
c) Create new database connection
d) Kill session from multiple sessions

Q2. Which of the below is not a session tracking method?

a) URL rewriting
b) History
c) Cookies
d) SSL sessions

Q3. Which of the following is stored at client side?

a) URL rewriting
b) Hidden form fields
c) SSL sessions
d) Cookies

Q4. Which of the following leads to high network traffic?

a) URL rewriting
b) Hidden form fields
c) SSL sessions
d) Cookies

Q5. Which of the following is not true about session?

a) All users connect to the same session


b) All users have same session variable
c) Default timeout value for session variable is 20 minutes
d) New session cannot be created for a new user

Q6. Session IDs are stored in cookies.

a) True
b) False

Q7. What is the maximum size of cookie?


a) 4 KB
b) 4 MB
c) 4 bytes
d) 40 KB

Q8. How can we invalidate a session?

a) session.discontinue()
b) session.invalidate()
c) session.disconnect()
d) session.falsify()

Q9. Which method creates unique fields in the HTML which are not shown to the user?

a) User authentication
b) URL writing
c) HTML Hidden field
d) HTML invisible field

Q10. Which object is used by spring for authentication?

a) ContextHolder
b) SecurityHolder
c) AnonymousHolder
d) SecurityContextHolder

Q11. Which is the type of attack when Network is made unavailable for user

a) masquerade
b) replay
c) modification
d) denial of service

Q12. From the options below, which of them is not a threat to information security?

a) disaster
b) eavesdropping
c) information leakage
d) unchanged default password

Q13. Compromising confidential information comes under


a) bug
b) threat
c) vulnerability
d) attack

Q14. In which of the following, a person is constantly followed/chased by another person or group of
several peoples?

a) Phishing
b) Bulling
c) Stalking
d) Identity theft

Q15. Which one of the following can be considered as the class of computer threats?

a) Identity
b) Dos Attack
c) Soliciting
d) Both A and C

Q16. Which of the following is considered as the unsolicited commercial email?

a) Spam
b) Virus
c) Malware
d) All of the above
Q17. Which of the following usually observe each activity on the internet of the victim, gather all
information in the background, and send it to someone else?

a) Malware
b) Spyware
c) Adware
d) All of the above

Q18. _______ is a type of software designed to help the user's computer detect viruses and avoid them.

a) Malware
b) Adware
c) Antivirus
d) Both B and C

Q19. Which one of the following is a type of antivirus program?

a) Quick heal
b) Mcafee
c) Kaspersky
d) All of the above

Q20. It can be a software program or a hardware device that filters all data packets coming through the
internet, a network, etc. it is known as the_______:

a) Antivirus
b) Firewall
c) Cookies
d) Malware

Q21. Which of the following refers to stealing one's idea or invention of others and use it for their own
benefits?

a) Piracy
b) Plagiarism
c) Intellectual property rights
d) All of the above

Q22. Which of the following refers to exploring the appropriate, ethical behaviors related to the online
environment and digital media platform?

a) Cyber low
b) Cyberethics
c) Cybersecurity
d) Cybersafety

Q23. Which one of the following usually used in the process of Wi-Fi-hacking?

a) Aircrack-ng
b) Wireshark
c) Norton
d) All of the above

Q24. What is phishing?


a) A new kind of software.
b) An e-mail scam
c) A data transfer protocol

Q25. A firewall is security software. True or false?


a) True
b) False

Q26. How often should you update your antivirus software?


a) Every day
b) Every month.
c) Your program should update automatically when you connect to the Internet.

Q27. What is a cookie?


a) A file that makes it easier to access a Web site and browse.
b) A file that hackers use to steal your identity.
c) A computer virus.

Q28. What is the digital certificate of a secured Web site used for?
a) It calculates the number of visitors a day.
b) It saves the identities of site visitors.
c) It enables visitors to confirm the authenticity of the site they are on.

Q29. What is encryption used for?


a) Compiling statistics on a Web site.
b) Calculating how often you visit a site compared to others.
c) Encrypting your personal information when sending data on the Internet.

Answers: 1 (a), 2 (b), 3 (d), 4 (a), 5 (c), 6 (a), 7 (a), 8 (b), 9 (c), 10 (d), 11 (d), 12 (d),
13 (b), 14 (c), 15 (a), 16 (a), 17 (b), 18 (c), 19 (a), 20(c), 21(d), 22(b), 23(a), 24(b),
25(a), 26(c), 27(a), 28(c), 29(c)
Unit-4

4.1 Introduction to Web 1.0, 2.0 and Web 3.0


Web 1.0 refers to the first stage of the World Wide Web evolution. Earlier, there were only few content
creators in Web 1.0 with the huge majority of users who are consumers of content. Personal web pages
were common, consisting mainly of static pages hosted on ISP-run web servers, or on free web hosting
services.
In Web 1.0 advertisements on websites while surfing the internet is banned. Also, in Web 1.0 is an online
digital photography website, on which user could store, share, view and print digital pictures. Web 1.0
is a content delivery network (CDN) which enables to showcase the piece of information on the websites.
It can be used as personal websites. It costs to user as per pages viewed. It has directories which enable
user to retrieve a particular piece of information.

Four design essentials of a Web 1.0 site include:


1. Static pages.
2. Content is served from the server’s file-system.
3. Pages built using Server Side Includes or Common Gateway Interface (CGI).
4. Frames and Tables used to position and align the elements on a page.

Web2.0–
Web 2.0 refers to world wide website which highlight user-generated content, usability and
interoperability for end users. Web 2.0 is also called participative social web. It does not refer to a
modification to any technical specification, but to modify in the way Web pages are designed and used.
The transition is beneficial but it does not seem that when the changes are occurred. An interaction and
collaboration with each other is allowed by Web 2.0 in a social media dialogue as creator of user-
generated content in a virtual community. Web 1.0 is enhanced version of Web 2.0.
The web browser technologies are used in Web 2.0 development and it includes AJAX and JavaScript
frameworks. Recently, AJAX and JavaScript frameworks have become a very popular means of creating
web 2.0 sites.
Five major features of Web 2.0 –

1. Free sorting of information, permits users to retrieve and classify the information
collectively.
2. Dynamic content that is responsive to user input.
3. Information flows between site owner and site users by means of evaluation & online
commenting.
4. Developed APIs to allow self-usage, such as by a software application.
5. Web access leads to concern different, from the traditional Internet user base to a wider
variety of users.

Usage of Web 2.0 –

The social Web contains a number of online tools and platforms where people share their perspectives,
opinions, thoughts and experiences. Web 2.0 applications tend to interact much more with the end user.
As such, the end user is not only a user of the application but also a participant by these 8 tools mentioned
below:
1. Podcasting
2. Blogging
3. Tagging
4. Curating with RSS
5. Social bookmarking
6. Social networking
7. Social media
8. Web content voting

Web 3.0 –

It refers the evolution of web utilization and interaction which includes altering the Web into a database.
In enables the upgradation of back-end of the web, after a long time of focus on the front-end (Web 2.0
has mainly been about AJAX, tagging, and another front-end user-experience innovation). Web 3.0 is a
term which is used to describe many evolutions of web usage and interaction among several paths. In
this, data isn’t owned but instead shared, where services show different views for the same web / the
same data.
The Semantic Web (3.0) promises to establish “the world’s information” in more reasonable way than
Google can ever attain with their existing engine schema. This is particularly true from the perspective
of machine conception as opposed to human understanding. The Semantic Web necessitates the use of a
declarative ontological language like OWL to produce domain-specific ontologies that machines can use
to reason about information and make new conclusions, not simply match keywords.

Below are 5 main features that can help us define Web 3.0:
1. SemanticWeb
The succeeding evolution of the Web involves the Semantic Web. The semantic web
improves web technologies in demand to create, share and connect content through search
and analysis based on the capability to comprehend the meaning of words, rather than on
keywords or numbers.
2. ArtificialIntelligence
Combining this capability with natural language processing, in Web 3.0, computers can
distinguish information like humans in order to provide faster and more relevant results.
They become more intelligent to fulfil the requirements of users.
3. 3DGraphics
The three-dimensional design is being used widely in websites and services in Web 3.0.
Museum guides, computer games, ecommerce, geospatial contexts, etc. are all examples
that use 3D graphics.
4. Connectivity
With Web 3.0, information is more connected thanks to semantic metadata. As a result, the
user experience evolves to another level of connectivity that leverages all the available
information.
5. Ubiquity
Content is accessible by multiple applications, every device is connected to the web, the
services can be used everywhere.

Difference between Web 1.0, Web 2.0 and Web 3.0 –

Web 1.0 Web 2.0 Web 3.0

Mostly Read-Only Wildly Read-Write Portable and Personal

Company Focus Community Focus Individual Focus

Home Pages Blogs / Wikis Live-streams / Waves

Owning Content Sharing Content Consolidating Content


Web 1.0 Web 2.0 Web 3.0

Web Forms Web Applications Smart Applications

Directories Tagging User Behaviour

Page Views Cost Per Click User Engagement

Banner Advertising Interactive Advertising Behavioural Advertising

Britannica Online Wikipedia The Semantic Web

HTML/Portals XML / RSS RDF / RDFS / OWL

4.2 Web Development Trends


Gone are the days when the Web Development is all about HTML, CSS, and JavaScript – however these
are still the building blocks for any website but due to the rapid evolution of technologies, now you need
to keep up with the latest trends & technologies as well during web development to stay ahead of the
game. For instance, it is reported that by the year 2021, more than half of all the searches across the
internet will be voice-based. Similarly, more than 60%of users don’t come back to the website just
because of unresponsive design.
Probably that’d be enough to let you understand that missing out on these latest tech trends can make
you outdated or lost in the development world!!
Undoubtedly, it is quite known to everyone that user experience is one of the most considerable facets
of web development. And with the same concern, developers are required to follow the latest tech trends
of web development to enhance the user experience in every possible aspect such as security, speed,
UI, etc. If we look at the numbers, around 90% of online visitors are less likely to return to the website
after having a substandard user experience. Though to stay aware of all the latest web development trends
is quite a tough job and with the same concern, we’ve compiled a list of several most-recommended tech
trends to make it easier for you.
Now, without wasting much time, let’s take a look at the top 10 Web Development trends :-

1. Single Page Applications


Single Page Application (SPA) is one of the most preferred tech trends by web developers in recent
times. In general, Single Page Applications are concerned with the apps that work inside the browser,
and with SPAs, users are not required to reload the webpage as it loads all the other content using
JavaScript. There are various advantages of SPAs such as better speed & performance, high level of
responsiveness, streamlined & optimized development, etc. that ultimately leads to high traffic and better
conversion rate. Some of the major examples of Single Page Applications are Gmail, Twitter, Facebook,
and many more.

2. Progressive Web Applications


Although Progressive Web Applications are not a new name in the web development world, they’ve
gained momentum in the past few years. As the number of smartphone users is increasing exponentially,
there is a rising demand for PWAs in the market as it eliminates the need for installation of the
application to run it on the device. Hence, Progressive Web Applications replicates the experience of a
native app without downloading and installation processes. There are various features of PWAs such as
integrated & engaging, higher efficiency, cost-effectiveness, better conversion rate, and many more.
Moreover, Flipkart, OLX, Pinterest, etc. are among the few renowned examples of the Progressive Web
Applications.

3. WebAssembly
As a majority of the web applications are built on JavaScript, it makes the applications heavier and
comparatively slow. However, with WebAssembly, web development is getting more powerful as it
allows you to compile the code in any programming language into byte code that runs in a browser.
Meanwhile, the WebAssembly code is executed faster in comparison with JavaScript. Some of the
prominent features of using WebAssembly are non-browser embedding support, portability & efficiency,
etc. Also, the technology is strongly recommended to the web developers if they’re looking forward
to building web games, audio/video apps, mapping apps, or other related applications.

4. Motion User Interface


Motion User Interface is indeed the best way to enhance the user experience as it is concerned with
the UI that consists of any kind of animations, graphics, transitions, illustrations, videos, etc. on the
web page. As there are numerous websites available over the web for the same niche, Motion User
Interface helps you to differentiate yourself from other competitors with some unique designing
advancements to draw the user’s attention. And Motion UI is not only about better visuals but it also
helps you to represent the information in a more engaging & creating way that subsequently boosts the
website performance.

5. Accelerated Mobile Pages


Here comes another most preferred web trend of recent times – Accelerated Mobile Pages. AMP,
developed by Google, aims to speed up the web page performance by creating HTML copies of the
existing webpages of the website. The Accelerated Mobile Pages are exceedingly lightweight pages and
in general, the AMP page takes around less than 2 seconds to load, on the other hand, non-AMP pages
can consume up to 20-22 seconds as loading time. There are various renowned advantages of following
AMP trends such as reduced load time, low bounce rate, enhanced SEO, mobile-friendliness, no
requirement of the sitemap submission, and many more.

6. Voice Search Optimization


Either we talk about Siri from Apple, Alexa & Echo from Amazon, Google Assistant from Googleor any
other – voice search technology has witnessed a huge spike in its demand & popularity in the last few
years. And, with the same concern, web developers are also required to optimized their websites for
voice search aspects to stay ahead in the domain. In general, the technology allows you to speak your
query to the device for getting the required information or search results instead of typing the keywords
in the search box. As it offers features like ease of use, time-saving, etc., it is being more preferred by
the users.

7. Artificial Intelligence & Chatbots


The integration of Artificial Intelligence technologies, especially Chatbots, is advancing the web
development domain by making it more feasible and personalized for humans to interact with the
applications. As per the reports, more than 90% of web users prefer chatbots for support & assistance
and there will be around 1.5 Billion users by the year 2021 who will be using AI assistants. Moreover, it
offers various key benefits such as higher user satisfaction, saves time & money, 24-hour problem-
solving potential, and many more. Also, numerous tech giants such as Facebook, Skype, etc. are already
using Artificial Intelligence & Chatbots technology in their respective platforms.

8. Push Notifications
Push Notification is a feature of the websites that allows it to notify the user of certain events, offers,
news, reminders, etc. on the device. Meanwhile, there is no need for the user to be active on the particular
website to receive the push notifications. The primary goal of using push notifications is to enhance user
engagement and it has seen a good response in web development in recent times. Although before using
push notifications for any website, developers or other key persons are required to analyze its
requirements effectively as unnecessary or irrelevant push notifications may result in negative outcomes
also.

9. Blockchain Technology
Blockchain is one of the fastest-growing web development trends which is concerned with the occurrence
of transactions with the help of blocks. Here each transaction is verified by the decentralized distributed
network. The technology is majorly being used for trading or performing transactions along with several
other aspects such as decentralize file storage, cybersecurity, and others. The best part of Blockchain
integration with web development is the utmost safety it provides that subsequently enhances the user
experience. Several other benefits of Blockchain in web development aspects are higher web pages
interactivity, data security, smart prediction system, etc.

10. Serverless Applications and Architecture


Last but not least – the Serverless Application & Architecture is concerned with the running of
applications & services without building up the server. These applications work by renting the server
from external vendors rather than developing on their own. There are various renowned vendors such
as AWS, Azure, etc. that are offering this server facility for website development with better scalability
and security. The technology is being used in web development to avoid complications like system
overloading, high development costs, data loss, and many more. Moreover, the serverless app
architecture helps you to strengthen web applications with flexibility potential, a sustainable internet
environment, etc.
So, these are several most-recommended Web Development trends that you’re recommended to follow
in 2020. Additionally, there are several other trends also such as browser extensions, ghost buttons,
virtual & augmented reality, etc. that can also be taken into consideration. In the end, you need to stay
aware of these trends to please your users with a remarkable experience and to stay competitive in the
web development market. Now, what are waiting for? Learn these latest web development trends to make
the most out of these for your upcoming projects!!

4.3 Applications of web engineering technologies in distributed system


“A distributed system in which the computer power in the system is distributed geographically around a
number of computers which share the processing load of the system.” “A distributed object is an object
which is resident on one computer and for which methods can be invoked associated with code resident
on other computers.”

A simple e-commerce system

e-Commerce Auction Sites Affiliate Sites Banner Adverts

Shopping Malls / Portals Digital Publishing Community Sites (Chat Rooms)

What is a Web Service? Web Service:

“Web-based applications that dynamically interact with other Web applications using open standards
that include XML, UDDI and SOAP” Service-Oriented Architecture (SOA):“Development of
applications from distributed collections of smaller loosely coupled service providers” “A collection of
services or software agents that communicate freely with each other”

Web Service Advantages for E-Business

Allow companies to reduce the cost of doing e- business, to deploy solutions faster need a common
program-to-program communications model Allow heterogeneous applications to be integrated more
rapidly, easily and less expensively Facilitate deploying and providing access to business functions over
the Web

Web Services Terminology

SOAP (Simple Object Access Protocol)exchanging XML messages on a network Like RPC, it provides
a way to communicate between applications Unlike RPC, it communicates over HTTP because HTTP is
supported by all Internet browsers and servers, SOAP can run on different operating systems, with
different technologies and programming languages WSDL (Web Service Description Language
)describing interfaces of Web services UDDI (Universal Description, Discovery and
Integration)managing registries of Web services

Web Service Model

Web Service Model Roles in a Web Service Architecture Service provider


Owner of the service Platform that hosts access to the service Service requestor Business that requires
certain functions to be satisfied Application looking for and invoking an interaction with a service Service
registry Searchable registry of service descriptions where service providers publish their service
descriptions

Web Service Model Operations in a Web Service Architecture Publish


Service descriptions need to be published in order for service requestor to find them Find Service
requestor queries the service registry for the service required Bind Service requestor invokes or initiates
an interaction with the service at runtime

4.4 Web Security Issues


The Web has become the visible interface of the Internet. Many corporations now use the Web for
advertising, marketing and sales. Web servers might be easy to use but…Complicated to configure
correctly and difficult to build without security flaws. They can serve as a security hole by which an
adversary might access other data and computer systems Threats Consequences Counter measures
Integrity Modification of Data Trojan horses Loss of Information Compromise of Machine MACs
(mandatory access control) and Hashes Confidentiality Eavesdropping Theft of Information Privacy
Breach Encryption DoS Stopping Filling up Disks and Resources Stopped Transactions Authentication
Impersonation Data Forgery Misrepresentation of User Accept false Data Signatures, MACs

So Where to Secure the Web?

There are many strategies to securing the web. We may attempt to secure the IP Layer of the TCP/IP
Stack: this may be accomplished using IPSec, for example. We may leave IP alone and secure on top of
TCP: this may be accomplished using the Secure Sockets Layer (SSL) or Transport Layer Security (TLS)
We may seek to secure specific applications by using application-specific security solutions: for example,
we may use Secure Electronic Transaction (SET)The first two provide generic solutions, while the third
provides for more specialized services

4.5 Case Studies Using Different Tools


Case study analysis is a serious work that often demands a lot of time and effort. Students need to go
through a lot of information, to analyze it, to choose the suitable pieces, to make their own conclusions
and to organize a neat paper. In addition to that, they need to do it all fast because they always have many
other assignments to deal with, too, not mentioning any part-time jobs and extracurricular activities.

Luckily, there are some tools these days that can help with planning and write this academic paper. Some
tools can help on every step of the way starting from planning your work and fitting it into your schedule
and finishing with checking your paper for typos and organizing a bibliography. Here are some of the
best tools for it.

Paperity

This is an indispensable tool for a research part of working on a case study. Paperity offers you free
access to multiple numbers of journals of different subjects. No matter what your major and case study
subject are, you can most certainly find something useful here.

There are many similar resources online, but the majority of them are paid, and that makes Paperity more
desirable for students. If you wish, you can also contribute some of your papers to such sites so that other
students can benefit from this information.

Zotero

This tool can be indispensable at the research stage. If you look for the material for your case study
online, you can use Zotero to collect quotes with sources, save links to the interesting articles, download
PDF-files, web-pages, and other files as well as to create your personal topical bibliographies.

This tool (it is a browser extension, actually) can come very handy if you need to work with a significant
amount of information and want to automate the process of collecting the sources of this information.

Quetext – Plagiarism Checker

Checking your work for plagiarism is a major step for modern students. Even if you wrote your work
yourself based on the information you had found, it still might have some plagiarized sentences. What
the majority of the information students write in their papers is not new, and it is easy to sound like
someone else sounded before. Be careful of that, as many professors, today like to check students’ work
for plagiarism.

There are many good quality plagiarism checkers today, and Quetext is one of them. It is free, by the
way.

Producteev

This is a very effective task management program. Many students procrastinate all the time and have
problems with managing their time and assignments. This program can help with all that. The cool thing
about Producteev is that it integrates with such tools as e-mail, messengers, social media, etc. It is
compatible with Windows and can be used as an iOS or Android app on mobile devices. It synchronizes
with your calendar which is very convenient, too.
MindMapple

Using mind maps in the educational process is a popular trend for a reason. Many students feel it is a
convenient way to organize many things. Working on a case study analysis, you can also try this tool.
For instance, you can use a mind map to make a plan of your actions on every step of the way – research,
analysis, writing, etc.

Alternatively, you can use mind mapping when you have found a lot of information, and you want to
arrange it logically. Be creative.

Wordstorm

This tool can be helpful if you are stuck with your writing and don’t know what to do next. You can type
in a word and get a map of suggested words to go with it. It is an excellent option for brainstorming.

Self Control

This app is for procrastinators and those who often just go and Twitter for a minute and find themselves
leaving their case study for tomorrow again. This tool allows you to block all the distracting websites so
that you can focus on your case study only. Note that you won’t be able to visit those distracting sites
even if you reboot your computer. So, you will have no choice but to work on your paper.

Grammarly

This tool can help a lot at the stage of writing a text. Surely, your writing skills are alright since you are
in college, but all people make mistakes and may not notice them at first. If you haven’t heard of it,
Grammarly is a tool that corrects your writing mistakes.

It has free and paid versions that differ in the number of suggested options. The paid version makes a
deeper analysis of your work and points out not only spelling and grammar errors but also tells you what
can be altered to make your text more appealing stylistically. You can synchronize the program with
your browsers and Microsoft Word, and it will correct any of your writing there.

Encyclopedia.com

This is a great site for collecting the information. It consists of a huge amount of data and can be useful
for writing a case study analysis as well as any other college assignment. So, save it somewhere for your
future works.

Easybib

Creating a bibliography after writing a case study analysis is one of the things students don’t like the
most. There are so many rules and small details that almost everyone makes at least one mistake in their
citation list. Easybib is a program for that. It automates the whole process for you and creates citations
according to the required style.
Solved questions

Q1. What is the main purpose of semantic web?


Ans. The Semantic Web provides a common framework that allows data to be shared and reused across
application, enterprise, and community boundaries. It is a collaborative effort led by W3C with
participation from a large number of researchers and industrial partners.

Q2. What is web oriented architecture? Give examples.


Ans. Web-oriented architecture (WOA) is a type of software architecture that is designed to be used for
website and Web applications. It builds on service-oriented architecture (SOA) by adding support
for Web-based software application and services. The key difference between SOA and WOA is
the use of REST APIs by WOA instead of SOAP by SOA.
WOA is primarily a sub-style of SOA with Web capabilities. It integrates and connects systems
and users through the global set of hypermedia (Internet) technologies and works on user interfaces
and API. It is commonly used as service architecture in social media websites and cloud-based
services.
WOA has five fundamental interface constraints:
 Identification of the resource, such as uniform resource identifier
 Manipulation of resources through Web-based representations such as HTTP
 Self-descriptive messages like MIME
 Hypermedia for the engine of application state
 Application neutrality, meaning the application/service created on WOA can be deployed/used
on any platform

Q3. What is Semantic Web and how it works?


Ans. The Semantic Web proposes to help computers "read" and use the Web. ... This won't bestow
artificial intelligence or make computers self-aware, but it will give machines tools to find,
exchange and, to a limited extent, interpret information. It's an extension of, not a replacement for,
the World Wide Web.

Q4. What is the example of Semantic Web?


Ans. Examples include Best Buy, BBC World Cup site, Google, Facebook and Flipboard. Google,
Microsoft, Yahoo and Yandex agree on Schema.org, a vocabulary for associating meaning to data
on the web. The vocabulary is defined by a community process.

Unsolved questions

Q1. List some of the security threats?


Q2. A computer virus also goes through different phases. Name them?
Q3. What is digital Signature?
Q4. Distinguish between secret key and public key systems?
Q5. What are the security issues in JavaScript and VBScript?
Q6. What are the difference among Web 1.0,Web 2.0, and Web 3.0? What is extended Web 3.0?
Q7. What is the main purpose of semantic web?
Q8. What is web oriented architecture? Give example?
Q9. What are blogs?
Objective Type Questions

Q1. Semantic web technologies include

a) RDF and OWL


b) ASP.NET
c) JSP
d) None of the above

Q2. Identify the Risk factors which are associated with Electronic payment system?
a) Fraudulent use of Credit Cards
b) Sending Credit Card details over internet
c) Remote storage of Credit Card details
d) All of the above

Q3. What component of .NET includes services used to support web services?
a) Platform
b) Framework
c) Visual Studio
d) System

Q4. Netscape framed


a) The web as a software
b) The web as a paradigm
c) The web as a platform
d) None of the above

Q5. On the server side web 2.0 uses


a) PHP
b) Ruby
c) Perl
d) All of the above

Q6. Which of the following is a web 2.0 tool?


a) Wikis
b) Mikis
c) Bikis
d) None of the above

Q7. The term semantic web was coined by


a) Jacobson
b) Booch
c) Tim Berners Lee
d) None of the above

Q8. Web 3.0 introduces


a) AI
b) BI
c) C
d) None of the above

Q9. The best products to sell in B2C e-commerce are


a) Small products
b) Digital products
c) Specialty products
d) Fresh products

Q10. A rare type of blog hosted on the Gopher Protocol is


a) Phlog
b) Reverse blog
c) Simple blog
d) None of the above

Answers: 1 (a), 2 (d), 3 (b), 4 (c), 5 (d), 6 (a), 7 (c), 8 (a), 9 (b), 10 (a).

References

1. https://en.wikipedia.org/wiki/HTTPS

2. https://searchsecurity.techtarget.com/definition/digital-certificate

You might also like