0% found this document useful (0 votes)
18 views214 pages

WT All Unit Notes zccurate

Notes

Uploaded by

techfinder287
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views214 pages

WT All Unit Notes zccurate

Notes

Uploaded by

techfinder287
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 214

1.

HTML – OVERVIEW HTML

HTML stands for Hypertext Markup Language, and it is the most widely used language to
write Web Pages.

• Hypertext refers to the way in which Web pages (HTML documents) are linked
together. Thus, the link available on a webpage is called Hypertext.

• As its name suggests, HTML is a Markup Language which means you use HTML to
simply "mark-up" a text document with tags that tell a Web browser how to structure
it to display.

Originally, HTML was developed with the intent of defining the structure of documents like
headings, paragraphs, lists, and so forth to facilitate the sharing of scientific information
between researchers.

Now, HTML is being widely used to format web pages with the help of different tags available
in HTML language.

Basic HTML Document


In its simplest form, following is an example of an HTML document:

<!DOCTYPE html>
<html>
<head>
<title>This is document title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Document content goes here .... </p>
</body>
</html>

Either you can use Try it option available at the top right corner of the code box to check the
result of this HTML code, or let's save it in an HTML file test.htm using your favorite text
editor. Finally open it using a web browser like Internet Explorer or Google Chrome, or Firefox
etc. It must show the following output:

16
HTML

HTMLTags
As told earlier, HTML is a markup language and makes use of various tags to format the
content. These tags are enclosed within angle braces <Tag Name>. Except few tags, most
of the tags have their corresponding closing tags. For example, <html> has its closing
tag</html> and <body> tag has its closing tag </body> tag etc.

Above example of HTML document uses the following tags:

Tag Description

<!DOCTYPE...> This tag defines the document type and HTML version.

This tag encloses the complete HTML document and mainly comprises
<html> of document header which is represented by <head>...</head> and
document body which is represented by <body>...</body> tags.

This tag represents the document's header which can keep other HTML
<head>
tags like <title>, <link> etc.

The <title> tag is used inside the <head> tag to mention the
<title>
document title.

This tag represents the document's body which keeps other HTML tags
<body>
like <h1>, <div>, <p> etc.

<h1> This tag represents the heading.

17
HTML

<p> This tag represents a paragraph.

To learn HTML, you will need to study various tags and understand how they behave, while
formatting a textual document. Learning HTML is simple as users have to learn the usage of
different tags in order to format the text or images to make a beautiful webpage.

World Wide Web Consortium (W3C) recommends to use lowercase tags starting from HTML
4.

HTML Document Structure


A typical HTML document will have the following structure:

Document declaration tag


<html>
<head>
Document header related tags
</head>

<body>
Document body related tags
</body>
</html>

We will study all the header and body tags in subsequent chapters, but for now let's see what
is document declaration tag.

The <!DOCTYPE> Declaration


The <!DOCTYPE> declaration tag is used by the web browser to understand the version of
the HTML used in the document. Current version of HTML is 5 and it makes use of the following
declaration:

<!DOCTYPE html>

There are many other declaration types which can be used in HTML document depending on
what version of HTML is being used. We will see more details on this while discussing
<!DOCTYPE...> tag along with other HTML tags.

18
2. HTML – BASIC TAGS HTML

Heading Tags
Any document starts with a heading. You can use different sizes for your headings. HTML also
has six levels of headings, which use the elements <h1>, <h2>, <h3>, <h4>, <h5>, and
<h6>. While displaying any heading, browser adds one line before and one line after that
heading.

Example
<!DOCTYPE html>
<html>
<head>
<title>Heading Example</title>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body>
</html>

This will produce the following result:

19
HTML

Paragraph Tag
The <p> tag offers a way to structure your text into different paragraphs. Each paragraph of
text should go in between an opening <p> and a closing </p> tag as shown below in the
example:

Example
<!DOCTYPE html>
<html>
<head>
<title>Paragraph Example</title>
</head>
<body>
<p>Here is a first paragraph of text.</p>
<p>Here is a second paragraph of text.</p>
<p>Here is a third paragraph of text.</p>
</body>
</html>

This will produce the following result:

Here is a first paragraph of text.


Here is a second paragraph of text.
Here is a third paragraph of text.

20
HTML

Line Break Tag


Whenever you use the <br /> element, anything following it starts from the next line. This
tag is an example of an empty element, where you do not need opening and closing tags, as
there is nothing to go in between them.

The <br /> tag has a space between the characters br and the forward slash. If you omit this
space, older browsers will have trouble rendering the line break, while if you miss the forward
slash character and just use <br> it is not valid in XHTML.

Example
<!DOCTYPE html>
<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<p>Hello<br />
You delivered your assignment on time.<br />
Thanks<br />
Mahnaz</p>
</body>
</html>

This will produce the following result:

Hello
You delivered your assignment on time.
Thanks
Mahnaz

Centering Content
You can use <center> tag to put any content in the center of the page or any table cell.

Example
<!DOCTYPE html>
<html>
<head>

21
HTML

<title>Centring Content Example</title>


</head>
<body>
<p>This text is not in the center.</p>
<center>
<p>This text is in the center.</p>
</center>
</body>
</html>

This will produce the following result:

This text is not in the center.

This text is in the center.

Horizontal Lines
Horizontal lines are used to visually break-up sections of a document. The <hr> tag creates
a line from the current position in the document to the right margin and breaks the line
accordingly.

For example, you may want to give a line between two paragraphs as in the given example
below:

Example
<!DOCTYPE html>
<html>
<head>
<title>Horizontal Line Example</title>
</head>
<body>
<p>This is paragraph one and should be on top</p>
<hr />
<p>This is paragraph two and should be at bottom</p>
</body>
</html>

22
HTML

This will produce the following result:

This is paragraph one and should be on top

This is paragraph two and should be at bottom

Again <hr /> tag is an example of the empty element, where you do not need opening and
closing tags, as there is nothing to go in between them.

The <hr /> element has a space between the characters hr and the forward slash. If you
omit this space, older browsers will have trouble rendering the horizontal line, while if you
miss the forward slash character and just use <hr> it is not valid in XHTML

Preserve Formatting
Sometimes, you want your text to follow the exact format of how it is written in the HTML
document. In these cases, you can use the preformatted tag <pre>.

Any text between the opening <pre> tag and the closing </pre> tag will preserve the
formatting of the source document.

Example
<!DOCTYPE html>
<html>
<head>
<title>Preserve Formatting Example</title>
</head>
<body>
<pre>
function testFunction( strText ){
alert (strText)
}
</pre>
</body>
</html>

This will produce the following result:

function testFunction( strText ){

23
HTML

alert (strText)

Try using the same code without keeping it inside <pre>...</pre> tags

Nonbreaking Spaces
Suppose you want to use the phrase "12 Angry Men." Here, you would not want a browser to
split the "12, Angry" and "Men" across two lines:

An example of this technique appears in the movie "12 Angry Men."

In cases, where you do not want the client browser to break text, you should use a
nonbreaking space entity &nbsp; instead of a normal space. For example, when coding the
"12 Angry Men" in a paragraph, you should use something similar to the following code:

Example
<!DOCTYPE html>
<html>
<head>
<title>Nonbreaking Spaces Example</title>
</head>
<body>
<p>An example of this technique appears in the movie "12&nbsp;Angry&nbsp;Men."</p>
</body>
</html>

24
3. HTML – ELEMENTS HTML

An HTML element is defined by a starting tag. If the element contains other content, it ends
with a closing tag, where the element name is preceded by a forward slash as shown below
with few tags:

Start Tag Content End Tag

<p> This is paragraph content. </p>

<h1> This is heading content. </h1>

<div> This is division content. </div>

<br />

So here <p>....</p> is an HTML element, <h1>...</h1> is another HTML element. There


are some HTML elements which don't need to be closed, such as <img.../>, <hr /> and
<br /> elements. These are known as void elements.

HTML documents consists of a tree of these elements and they specify how HTML documents
should be built, and what kind of content should be placed in what part of an HTML document.

HTML Tag vs. Element


An HTML element is defined by a starting tag. If the element contains other content, it ends
with a closing tag.

For example, <p> is starting tag of a paragraph and </p> is closing tag of the same
paragraph but <p>This is paragraph</p> is a paragraph element.

Nested HTML Elements


It is very much allowed to keep one HTML element inside another HTML element:

Example

25
HTML

<head>

<title>Nested Elements Example</title>


</head>
<body>
<h1>This is <i>italic</i> heading</h1>
<p>This is <u>underlined</u> paragraph</p>
</body>
</html>

This will display the following result:

This is italic heading

This is underlined paragraph

26
4. HTML – ATTRIBUTES HTML

We have seen few HTML tags and their usage like heading tags <h1>, <h2>, paragraph tag
<p> and other tags. We used them so far in their simplest form, but most of the HTML tags
can also have attributes, which are extra bits of information.

An attribute is used to define the characteristics of an HTML element and is placed inside the
element's opening tag. All attributes are made up of two parts: a name and a value:

• The name is the property you want to set. For example, the paragraph <p> element
in the example carries an attribute whose name is align, which you can use to indicate
the alignment of paragraph on the page.

• The value is what you want the value of the property to be set and always put within
quotations. The below example shows three possible values of align attribute: left,
center and right.

Attribute names and attribute values are case-insensitive. However, the World Wide Web
Consortium (W3C) recommends lowercase attributes/attribute values in their HTML 4
recommendation.

Example
<!DOCTYPE html>
<html>
<head>
<title>Align Attribute Example</title>
</head>
<body>
<p align="left">This is left aligned</p>
<p align="center">This is center aligned</p>
<p align="right">This is right aligned</p>
</body>
</html>

This will display the following result:

This is left aligned


This is center aligned

27
HTML

This is right aligned

Core Attributes
The four core attributes that can be used on the majority of HTML elements (although not all)
are:

• Id
• Title
• Class
• Style

The Id Attribute
The id attribute of an HTML tag can be used to uniquely identify any element within an HTML
page. There are two primary reasons that you might want to use an id attribute on an
element:

• If an element carries an id attribute as a unique identifier, it is possible to identify just


that element and its content.

• If you have two elements of the same name within a Web page (or style sheet), you
can use the id attribute to distinguish between elements that have the same name.

We will discuss style sheet in separate tutorial. For now, let's use the id attribute to distinguish
between two paragraph elements as shown below.

Example
<p id="html">This para explains what is HTML</p>
<p id="css">This para explains what is Cascading Style Sheet</p>

The titleAttribute
The title attribute gives a suggested title for the element. They syntax for the title attribute
is similar as explained for id attribute:

The behavior of this attribute will depend upon the element that carries it, although it is often
displayed as a tooltip when cursor comes over the element or while the element is loading.

Example
<!DOCTYPE html>
<html>
<head>

28
HTML

<title>The title Attribute Example</title>


</head>
<body>
<h3 title="Hello HTML!">Titled Heading Tag Example</h3>
</body>
</html>

This will produce the following result:

Titled Heading Tag Example


Now try to bring your cursor over "Titled Heading Tag Example" and you will see that whatever
title you used in your code is coming out as a tooltip of the cursor.

The class Attribute


The class attribute is used to associate an element with a style sheet, and specifies the class
of element. You will learn more about the use of the class attribute when you will learn
Cascading Style Sheet (CSS). So for now you can avoid it.

The value of the attribute may also be a space-separated list of class names. For example:

class="className1 className2 className3"

The style Attribute


The style attribute allows you to specify Cascading Style Sheet (CSS) rules within the element.

<!DOCTYPE html>
<html>
<head>
<title>The style Attribute</title>
</head>
<body>
<p style="font-family:arial; color:#FF0000;">Some text...</p>
</body>
</html>

This will produce the following result:

29
HTML

Some text...

At this point of time, we are not learning CSS, so just let's proceed without bothering much
about CSS. Here, you need to understand what are HTML attributes and how they can be
used while formatting content.

Internationalization Attributes
There are three internationalization attributes, which are available for most (although not all)
XHTML elements.

• dir
• lang
• xml:lang

The dir Attribute


The dir attribute allows you to indicate to the browser about the direction in which the text
should flow. The dir attribute can take one of two values, as you can see in the table that
follows:

Value Meaning

ltr Left to right (the default value)

rtl Right to left (for languages such as Hebrew or Arabic that are read right to left)

Example
<!DOCTYPE html>
<html dir="rtl">
<head>
<title>Display Directions</title>
</head>
<body>
This is how IE 5 renders right-to-left directed text.
</body>
</html>

This will produce the following result:

30
HTML

This is how IE 5 renders right-to-left directed text.

When dir attribute is used within the <html> tag, it determines how text will be presented
within the entire document. When used within another tag, it controls the text's direction for
just the content of that tag.

The lang Attribute


The lang attribute allows you to indicate the main language used in a document, but this
attribute was kept in HTML only for backwards compatibility with earlier versions of HTML.
This attribute has been replaced by the xml:lang attribute in new XHTML documents.

The values of the lang attribute are ISO-639 standard two-character language codes. Check
HTML Language Codes: ISO 639 for a complete list of language codes.

Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>English Language Page</title>
</head>
<body>
This page is using English Language
</body>
</html>

The xml:lang Attribute


The xml:lang attribute is the XHTML replacement for the lang attribute. The value of
thexml:lang attribute should be an ISO-639 country code as mentioned in previous section.

Generic Attributes
Here's a table of some other attributes that are readily usable with many of the HTML tags.

Attribute Options Function

align right, left, center Horizontally aligns tags

31
HTML

valign top, middle, bottom Vertically aligns tags within an HTML


element.

bgcolor numeric, hexidecimal, RGB Places a background color behind an


values element

background URL Places a background image behind an


element

id User Defined Names an element for use with Cascading


Style Sheets.

class User Defined Classifies an element for use with Cascading


Style Sheets.

width Numeric Value Specifies the width of tables, images, or


table cells.

height Numeric Value Specifies the height of tables, images, or


table cells.

title User Defined "Pop-up" title of the elements.

We will see related examples as we will proceed to study other HTML tags. For a complete list
of HTML Tags and related attributes please check reference to HTML Tags List.

32
5. HTML – FORMATTING HTML

If you use a word processor, you must be familiar with the ability to make text bold, italicized,
or underlined; these are just three of the ten options available to indicate how text can appear
in HTML and XHTML.

Bold Text
Anything that appears within <b>...</b> element, is displayed in bold as shown below:

Example
<!DOCTYPE html>
<html>
<head>
<title>Bold Text Example</title>
</head>
<body>
<p>The following word uses a <b>bold</b> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses a bold typeface.

Italic Text
Anything that appears within <i>...</i> element is displayed in italicized as shown below:

Example
<!DOCTYPE html>
<html>
<head>
<title>Italic Text Example</title>
</head>
33
HTML

<body>
<p>The following word uses a <i>italicized</i> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses an italicized typeface.

Underlined Text
Anything that appears within <u>...</u> element, is displayed with underline as shown
below:

Example
<!DOCTYPE html>
<html>
<head>
<title>Underlined Text Example</title>
</head>
<body>
<p>The following word uses a <u>underlined</u> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses an underlined typeface.

Strike Text
Anything that appears within <strike>...</strike> element is displayed with strikethrough,
which is a thin line through the text as shown below:

Example
<!DOCTYPE html>
<html>
<head>

34
HTML

<title>Strike Text Example</title>


</head>
<body>
<p>The following word uses a <strike>strikethrough</strike> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses a strikethrough typeface.

Monospaced Font
The content of a <tt>...</tt> element is written in monospaced font. Most of the fonts are
known as variable-width fonts because different letters are of different widths (for example,
the letter 'm' is wider than the letter 'i'). In a monospaced font, however, each letter has the
same width.

Example
<!DOCTYPE html>
<html>
<head>
<title>Monospaced Font Example</title>
</head>
<body>
<p>The following word uses a <tt>monospaced</tt> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses a monospaced typeface.

Superscript Text
The content of a <sup>...</sup> element is written in superscript; the font size used is the
same size as the characters surrounding it but is displayed half a character's height above
the other characters.

35
HTML

Example
<!DOCTYPE html>
<html>
<head>
<title>Superscript Text Example</title>
</head>
<body>
<p>The following word uses a <sup>superscript</sup> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses a superscript typeface.

Subscript Text
The content of a <sub>...</sub> element is written in subscript; the font size used is the
same as the characters surrounding it, but is displayed half a character's height beneath the
other characters.

Example
<!DOCTYPE html>
<html>
<head>
<title>Subscript Text Example</title>
</head>
<body>
<p>The following word uses a <sub>subscript</sub> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses a subscript typeface.

36
HTML

Inserted Text
Anything that appears within <ins>...</ins> element is displayed as inserted text.

Example
<!DOCTYPE html>
<html>
<head>
<title>Inserted Text Example</title>
</head>
<body>
<p>I want to drink <del>cola</del> <ins>wine</ins></p>
</body>
</html>

This will produce the following result:

Deleted Text
Anything that appears within <del>...</del> element, is displayed as deleted text.

Example
<!DOCTYPE html>
<html>
<head>
<title>Deleted Text Example</title>
</head>
<body>
<p>I want to drink <del>cola</del> <ins>wine</ins></p>
</body>
</html>

This will produce the following result:

37
HTML

Larger Text
The content of the <big>...</big> element is displayed one font size larger than the rest of
the text surrounding it as shown below:

Example
<!DOCTYPE html>
<html>
<head>
<title>Larger Text Example</title>
</head>
<body>
<p>The following word uses a <big>big</big> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses a big typeface.

Smaller Text
The content of the <small>...</small> element is displayed one font size smaller than the
rest of the text surrounding it as shown below:

Example
<!DOCTYPE html>
<html>
<head>
<title>Smaller Text Example</title>
</head>
<body>
<p>The following word uses a <small>small</small> typeface.</p>
</body>

38
HTML

</html>

This will produce the following result:

The following word uses a small typeface.

Grouping Content
The <div> and <span> elements allow you to group together several elements to create
sections or subsections of a page.

For example, you might want to put all of the footnotes on a page within a <div> element to
indicate that all of the elements within that <div> element relate to the footnotes. You might
then attach a style to this <div> element so that they appear using a special set of style
rules.

Example
<!DOCTYPE html>
<html>
<head>
<title>Div Tag Example</title>
</head>
<body>
<div id="menu" align="middle" >
<a href="/index.htm">HOME</a> |
<a href="/about/contact_us.htm">CONTACT</a> |
<a href="/about/index.htm">ABOUT</a>
</div>

<div id="content" align="left" bgcolor="white">


<h5>Content Articles</h5>
<p>Actual content goes here .... </p>
</div>
</body>
</html>

This will produce the following result:

39
HTML

HOME | CONTACT | ABOUT

CONTENT ARTICLES

Actual content goes here.....

The <span> element, on the other hand, can be used to group inline elements only. So, if
you have a part of a sentence or paragraph which you want to group together, you could use
the <span> element as follows

Example
<!DOCTYPE html>
<html>
<head>
<title>Span Tag Example</title>
</head>
<body>
<p>This is the example of <span style="color:green">span tag</span> and the <span
style="color:red">div tag</span> alongwith CSS</p>
</body>
</html>

This will produce the following result:

This is the example of span tag and the div tag along with CSS

These tags are commonly used with CSS to allow you to attach a style to a section of a page.

40
6. HTML – PHRASE TAGS HTML

The phrase tags have been desicolgned for specific purposes, though they are displayed in a
similar way as other basic tags like <b>, <i>, <pre>, and <tt>, you have seen in previous
chapter. This chapter will take you through all the important phrase tags, so let's start seeing
them one by one.

Emphasized Text
Anything that appears within <em>...</em> element is displayed as emphasized text.

Example
<!DOCTYPE html>
<html>
<head>
<title>Emphasized Text Example</title>
</head>
<body>
<p>The following word uses a <em>emphasized</em> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses an emphasized typeface.

Marked Text
Anything that appears with-in <mark>...</mark> element, is displayed as marked with
yellow ink.

Example
<!DOCTYPE html>
<html>
<head>
<title>Marked Text Example</title>

41
HTML

</head>
<body>
<p>The following word has been <mark>marked</mark> with yellow</p>
</body>
</html>

This will produce the following result:

The following word has been marked with yellow.

Strong Text
Anything that appears within <strong>...</strong> element is displayed as important text.

Example
<!DOCTYPE html>
<html>
<head>
<title>Strong Text Example</title>
</head>
<body>
<p>The following word uses a <strong>strong</strong> typeface.</p>
</body>
</html>

This will produce the following result:

The following word uses a strong typeface.

TextAbbreviation
You can abbreviate a text by putting it inside opening <abbr> and closing </abbr> tags. If
present, the title attribute must contain this full description and nothing else.

Example
<!DOCTYPE html>
<html>
<head>

42
HTML

<title>Text Abbreviation</title>
</head>
<body>
<p>My best friend's name is <abbr title="Abhishek">Abhy</abbr>.</p>
</body>
</html>

This will produce the following result:

My best friend's name is Abhy.

Acronym Element
The <acronym> element allows you to indicate that the text between <acronym> and
</acronym> tags is an acronym.

At present, the major browsers do not change the appearance of the content of the
<acronym> element.

Example
<!DOCTYPE html>
<html>
<head>
<title>Acronym Example</title>
</head>
<body>
<p>This chapter covers marking up text in <acronym>XHTML</acronym>.</p>
</body>
</html>

This will produce the following result:

This chapter covers marking up text in XHTML.

Text Direction
The <bdo>...</bdo> element stands for Bi-Directional Override and it is used to override
the current text direction.

43
HTML

Example
<!DOCTYPE html>
<html>
<head>
<title>Text Direction Example</title>
</head>
<body>
<p>This text will go left to right.</p>
<p><bdo dir="rtl">This text will go right to left.</bdo></p>
</body>
</html>

This will produce the following result:

This text will go left to right.

This text will go right to left.

Special Terms
The <dfn>...</dfn> element (or HTML Definition Element) allows you to specify that you
are introducing a special term. It's usage is similar to italic words in the midst of a paragraph.

Typically, you would use the <dfn> element the first time you introduce a key term. Most
recent browsers render the content of a <dfn> element in an italic font.

Example
<!DOCTYPE html>
<html>
<head>
<title>Special Terms Example</title>
</head>
<body>
<p>The following word is a <dfn>special</dfn> term.</p>
</body>
</html>

This will produce the following result:

44
HTML

The following word is a special term.

Quoting Text
When you want to quote a passage from another source, you should put it in
between<blockquote>...</blockquote> tags.

Text inside a <blockquote> element is usually indented from the left and right edges of the
surrounding text, and sometimes uses an italicized font.

Example
<!DOCTYPE html>
<html>
<head>
<title>Blockquote Example</title>
</head>
<body>
<p>The following description of XHTML is taken from the W3C Web site:</p>

<blockquote>XHTML 1.0 is the W3C's first Recommendation for XHTML, following on


from earlier work on HTML 4.01, HTML 4.0, HTML 3.2 and HTML 2.0.</blockquote>
</body>
</html>

This will produce the following result:

The following description of XHTML is taken from the W3C Web site:

XHTML 1.0 is the W3C's first Recommendation for XHTML, following on from earlier
work on HTML 4.01, HTML 4.0, HTML 3.2 and HTML 2.0.

Short Quotations
The <q>...</q> element is used when you want to add a double quote within a sentence.

Example
<!DOCTYPE html>
<html>
<head>

45
HTML

<title>Double Quote Example</title>


</head>
<body>
<p>Amit is in Spain, <q>I think I am wrong</q>.</p>
</body>
</html>

This will produce the following result:

Amit is in Spain, I think I am wrong.

Text Citations
If you are quoting a text, you can indicate the source placing it between an opening <cite>tag
and closing </cite> tag

As you would expect in a print publication, the content of the <cite> element is rendered in
italicized text by default.

Example
<!DOCTYPE html>
<html>
<head>
<title>Citations Example</title>
</head>
<body>
<p>This HTML tutorial is derived from <cite>W3 Standard for HTML</cite>.</p>
</body>
</html>

This will produce the following result:

This HTML tutorial is derived from W3 Standard for HTML.

Computer Code
Any programming code to appear on a Web page should be placed
inside <code>...</code>tags. Usually the content of the <code> element is presented in a
monospaced font, just like the code in most programming books.

46
HTML

Example
<!DOCTYPE html>
<html>
<head>
<title>Computer Code Example</title>
</head>
<body>
<p>Regular text. <code>This is code.</code> Regular text.</p>
</body>
</html>

This will produce the following result:

Regular text. This is code. Regular text.

Keyboard Text
When you are talking about computers, if you want to tell a reader to enter some text, you
can use the <kbd>...</kbd> element to indicate what should be typed in, as in this
example.

Example
<!DOCTYPE html>
<html>
<head>
<title>Keyboard Text Example</title>
</head>
<body>
<p>Regular text. <kbd>This is inside kbd element</kbd> Regular text.</p>
</body>
</html>

This will produce the following result:

Regular text. This is inside kbd element Regular text.

47
HTML

Programming Variables
This element is usually used in conjunction with the <pre> and <code> elements to indicate
that the content of that element is a variable.

Example
<!DOCTYPE html>
<html>
<head>
<title>Variable Text Example</title>
</head>
<body>
<p><code>document.write("<var>user-name</var>")</code></p>
</body>
</html>

This will produce the following result:


document.write("user-name")

Program Output
The <samp>...</samp> element indicates sample output from a program, and script etc.
Again, it is mainly used when documenting programming or coding concepts.

Example
<!DOCTYPE html>
<html>
<head>
<title>Program Output Example</title>
</head>
<body>
<p>Result produced by the program is <samp>Hello World!</samp></p>
</body>
</html>

This will produce the following result:

Result produced by the program is Hello World!


48
HTML

Address Text
The <address>...</address> element is used to contain any address.

Example
<!DOCTYPE html>
<html>
<head>
<title>Address Example</title>
</head>
<body>
<address>388A, Road No 22, Jubilee Hills - Hyderabad</address>
</body>
</html>

This will produce the following result:

388A, Road No 22, Jubilee Hills - Hyderabad

49
7. HTML – META TAGS HTML

HTML lets you specify metadata - additional important information about a document in a
variety of ways. The META elements can be used to include name/value pairs describing
properties of the HTML document, such as author, expiry date, a list of keywords, document
author etc.

The <meta> tag is used to provide such additional information. This tag is an empty element
and so does not have a closing tag but it carries information within its attributes.

You can include one or more meta tags in your document based on what information you
want to keep in your document but in general, meta tags do not impact physical appearance
of the document so from appearance point of view, it does not matter if you include them or
not.

Adding Meta Tags to Your Documents


You can add metadata to your web pages by placing <meta> tags inside the header of the
document which is represented by <head> and </head> tags. A meta tag can have
following attributes in addition to core attributes:

Attribute Description

Name Name for the property. Can be anything. Examples include, keywords,
description, author, revised, generator etc.

content Specifies the property's value.

scheme Specifies a scheme to interpret the property's value (as declared in the
content attribute).

http- Used for http response message headers. For example, http-equiv can be
equiv used to refresh the page or to set a cookie. Values include content-type,
expires, refresh and set-cookie.

Specifying Keywords
You can use <meta> tag to specify important keywords related to the document and later
these keywords are used by the search engines while indexing your webpage for searching
purpose.

50
HTML

Example
Following is an example, where we are adding HTML, Meta Tags, Metadata as important
keywords about the document.

<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Example</title>
<meta name="keywords" content="HTML, Meta Tags, Metadata" />
</head>
<body>
<p>Hello HTML5!</p>
</body>
</html>

This will produce the following result:

Hello HTML5!

Document Description
You can use <meta> tag to give a short description about the document. This again can be
used by various search engines while indexing your webpage for searching purpose.

Example
<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Example</title>
<meta name="keywords" content="HTML, Meta Tags, Metadata" />
<meta name="description" content="Learning about Meta Tags." />
</head>
<body>
<p>Hello HTML5!</p>
</body>
</html>

51
HTML

Document Revision Date


You can use <meta> tag to give information about when last time the document was updated.
This information can be used by various web browsers while refreshing your webpage.

Example
<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Example</title>
<meta name="keywords" content="HTML, Meta Tags, Metadata" />
<meta name="description" content="Learning about Meta Tags." />
<meta name="revised" content="Tutorialspoint, 3/7/2014" />
</head>
<body>
<p>Hello HTML5!</p>
</body>
</html>

Document Refreshing
A <meta> tag can be used to specify a duration after which your web page will keep refreshing
automatically.

Example
If you want your page keep refreshing after every 5 seconds then use the following syntax.

<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Example</title>
<meta name="keywords" content="HTML, Meta Tags, Metadata" />
<meta name="description" content="Learning about Meta Tags." />
<meta name="revised" content="Tutorialspoint, 3/7/2014" />
<meta http-equiv="refresh" content="5" />

52
HTML

</head>
<body>
<p>Hello HTML5!</p>
</body>
</html>

Page Redirection
You can use <meta> tag to redirect your page to any other webpage. You can also specify a
duration if you want to redirect the page after a certain number of seconds.

Example
Following is an example of redirecting current page to another page after 5 seconds. If you
want to redirect page immediately then do not specify content attribute.

<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Example</title>
<meta name="keywords" content="HTML, Meta Tags, Metadata" />
<meta name="description" content="Learning about Meta Tags." />
<meta name="revised" content="Tutorialspoint, 3/7/2014" />
<meta http-equiv="refresh" content="5; url=http://www.tutorialspoint.com" />
</head>
<body>
<p>Hello HTML5!</p>
</body>
</html>

Setting Cookies
Cookies are data, stored in small text files on your computer and it is exchanged between
web browser and web server to keep track of various information based on your web
application need.

You can use <meta> tag to store cookies on client side and later this information can be used
by the Web Server to track a site visitor.

53
HTML

Example
Following is an example of redirecting current page to another page after 5 seconds. If you
want to redirect page immediately then do not specify content attribute.

<!DOCTYPE html>
<html>
<head>
<title>Meta Tags Example</title>
<meta name="keywords" content="HTML, Meta Tags, Metadata" />
<meta name="description" content="Learning about Meta Tags." />
<meta name="revised" content="Tutorialspoint, 3/7/2014" />

54
1. CSS ─ OVERVIEW

What is CSS?
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable.

CSS handles the look and feel part of a web page. Using CSS, you can control the color of the
text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out,
what background images or colors are used, as well as a variety of other effects.

CSS is easy to learn and understand but it provides a powerful control over the presentation
of an HTML document. Most commonly, CSS is combined with the markup languages HTML
or XHTML.

Advantages of CSS
• CSS saves time - You can write CSS once and then reuse the same sheet in multiple
HTML pages. You can define a style for each HTML element and apply it to as many
web pages as you want.

• Pages load faster - If you are using CSS, you do not need to write HTML tag
attributes every time. Just write one CSS rule of a tag and apply it to all the
occurrences of that tag. So, less code means faster download times.

• Easy maintenance - To make a global change, simply change the style, and all the
elements in all the web pages will be updated automatically.

• Superior styles to HTML - CSS has a much wider array of attributes than HTML, so
you can give a far better look to your HTML page in comparison to HTML attributes.

• Multiple Device Compatibility - Style sheets allow content to be optimized for more
than one type of device. By using the same HTML document, different versions of a
website can be presented for handheld devices such as PDAs and cellphones or for
printing.

• Global web standards – Now HTML attributes are being deprecated and it is being
recommended to use CSS. So it’s a good idea to start using CSS in all the HTML pages
to make them compatible with future browsers.

10
Who Creates and Maintains CSS?
CSS is created and maintained through a group of people within the W3C called the CSS
Working Group. The CSS Working Group creates documents called specifications. When a
specification has been discussed and officially ratified by the W3C members, it becomes a
recommendation.

These ratified specifications are called recommendations because the W3C has no control over
the actual implementation of the language. Independent companies and organizations create
that software.

NOTE: The World Wide Web Consortium or W3C is a group that makes recommendations
about how the Internet works and how it should evolve.

CSS Versions
Cascading Style Sheets level 1 (CSS1) came out of W3C as a recommendation in December
1996. This version describes the CSS language as well as a simple visual formatting model
for all the HTML tags.

CSS2 became a W3C recommendation in May 1998 and builds on CSS1. This version adds
support for media-specific style sheets e.g. printers and aural devices, downloadable fonts,
element positioning and tables.

11
2. CSS ─ SYNTAX

A CSS comprises of style rules that are interpreted by the browser and then applied to the
corresponding elements in your document. A style rule is made of three parts:

• Selector: A selector is an HTML tag at which a style will be applied. This could be any
tag like <h1> or <table> etc.

• Property: A property is a type of attribute of HTML tag. Put simply, all the HTML
attributes are converted into CSS properties. They could be color, border, etc.

• Value: Values are assigned to properties. For example, color property can have the
value either red or #F1F1F1 etc.

You can put CSS Style Rule Syntax as follows:

selector { property: value }

Example: You can define a table border as follows:

table{ border :1px solid #C00; }

Here table is a selector and border is a property and the given value 1px solid #C00 is the
value of that property.

You can define selectors in various simple ways based on your comfort. Let me put these
selectors one by one.

The Type Selectors


This is the same selector we have seen above. Again, one more example to give a color to all
level 1 headings:

h1 {
color: #36CFFF;
}

The Universal Selectors


Rather than selecting elements of a specific type, the universal selector quite simply matches
the name of any element type:

12
* {
color: #000000;
}

This rule renders the content of every element in our document in black.

The Descendant Selectors


Suppose you want to apply a style rule to a particular element only when it lies inside a
particular element. As given in the following example, the style rule will apply to <em>
element only when it lies inside the <ul> tag.

ul em {
color: #000000;
}

The Class Selectors


You can define style rules based on the class attribute of the elements. All the elements having
that class will be formatted according to the defined rule.

.black {
color: #000000;
}

This rule renders the content in black for every element with class attribute set to black in our
document. You can make it a bit more particular. For example:

h1.black {
color: #000000;
}

This rule renders the content in black for only <h1> elements with class attribute set to black.

You can apply more than one class selectors to a given element. Consider the following
example:

<p class="center bold">


This para will be styled by the classes center and bold.

13
</p>

The ID Selectors
You can define style rules based on the id attribute of the elements. All the elements having
that id will be formatted according to the defined rule.

#black {
color: #000000;
}

This rule renders the content in black for every element with id attribute set to black in our
document. You can make it a bit more particular. For example:

h1#black {

color: #000000;
}

This rule renders the content in black for only <h1> elements with id attribute set to black.

The true power of id selectors is when they are used as the foundation for descendant
selectors. For example:

#black h2 {
color: #000000;
}

In this example, all level 2 headings will be displayed in black color when those headings will
lie within tags having id attribute set to black.

The Child Selectors


You have seen the descendant selectors. There is one more type of selector, which is very
similar to descendants but have different functionality. Consider the following example:

body > p {
color: #000000;
}

14
This rule will render all the paragraphs in black if they are a direct child of the <body>
element. Other paragraphs put inside other elements like <div> or <td> would not have any
effect of this rule.

TheAttribute Selectors
You can also apply styles to HTML elements with particular attributes. The style rule below
will match all the input elements having a type attribute with a value of text:

input[type="text"]{
color: #000000;
}

The advantage to this method is that the <input type="submit" /> element is unaffected, and
the color applied only to the desired text fields.

There are following rules applied to attribute selector.

• p[lang] - Selects all paragraph elements with a lang attribute.

• p[lang="fr"] - Selects all paragraph elements whose lang attribute has a value of
exactly "fr".

• p[lang~="fr"] - Selects all paragraph elements whose lang attribute contains the
word "fr".

• p[lang|="en"] - Selects all paragraph elements whose lang attribute contains values
that are exactly "en", or begin with "en-".

Multiple Style Rules


You may need to define multiple style rules for a single element. You can define these rules
to combine multiple properties and corresponding values into a single block as defined in the
following example:

h1 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

15
Here all the property and value pairs are separated by a semicolon (;). You can keep them
in a single line or multiple lines. For better readability, we keep them in separate lines.

For a while, don't bother about the properties mentioned in the above block. These properties
will be explained in the coming chapters and you can find the complete detail about properties
in CSS References.

Grouping Selectors
You can apply a style to many selectors if you like. Just separate the selectors with a comma,
as given in the following example:

h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

This define style rule will be applicable to h1, h2 and h3 element as well. The order of the list
is irrelevant. All the elements in the selector will have the corresponding declarations applied
to them.

You can combine the various class selectors together as shown below:

#content, #footer, #supplement {


position: absolute;
left: 510px;
width: 200px;
}

16
3. CSS ─ INCLUSION

There are four ways to associate styles with your HTML document. Most commonly used
methods are inline CSS and External CSS.

Embedded CSS - The <style> Element


You can put your CSS rules into an HTML document using the <style> element. This tag is
placed inside the <head>...</head> tags. Rules defined using this syntax will be applied to
all the elements available in the document. Here is the generic syntax:

<head>
<style type="text/css" media="...">
Style Rules
............
</style>
</head>

Attributes
Attributes associated with <style> elements are:

Attribute Value Description

type text/css Specifies the style sheet language as a content-type


(MIME type). This is a required attribute.

media screen Specifies the device, the document will be displayed


tty on. Default value is all. This is an optional attribute.
tv
projection
handheld
print
braille

17
aural
all

Example
Following is an example of embed CSS based on the above syntax:

<head>
<style type="text/css" media="all">
h1{
color: #36C;
}
</style>
</head>

Inline CSS - The style Attribute


You can use style attribute of any HTML element to define style rules. These rules will be
applied to that element only. Here is the generic syntax:

<element style="...style rules ... ">

Attributes
Attribute Value Description

style style The value of style attribute is a combination of style declarations


rules separated by semicolon (;).

Example
Following is the example of inline CSS based on the above syntax:

18
<h1 style ="color:#36C;"> This is inline CSS </h1>

It will produce the following result:

This is inline CSS

External CSS - The <link> Element


The <link> element can be used to include an external stylesheet file in your HTML document.

An external style sheet is a separate text file with .css extension. You define all the Style
rules within this text file and then you can include this file in any HTML document using <link>
element.

Here is the generic syntax of including external CSS file:

<head>
<link type="text/css" href="..." media="..." />
</head>

Attributes
Attributes associated with <style> elements are:

Attribute Value Description

type text/css Specifies the style sheet language as a content-type (MIME


type). This attribute is required.

href URL Specifies the style sheet file having Style rules. This attribute
is a required.

media screen Specifies the device the document will be displayed on. Default
tty value is all. This is an optional attribute.
tv
projection
handheld
print
braille

19
aural
all

Example
Consider a simple style sheet file with a name mystyle.css having the following rules:

h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

Now you can include this file mystyle.css in any HTML document as follows:

<head>
<link type="text/css" href="mystyle.css" media="all" />
</head>

Imported CSS - @import Rule


@import is used to import an external stylesheet in a manner similar to the <link> element.
Here is the generic syntax of @import rule.

<head>
<@import "URL";
</head>

Here URL is the URL of the style sheet file having style rules. You can use another syntax as
well:

<head>
20
<@import url("URL");
</head>

Example
Following is the example showing you how to import a style sheet file into an HTML document:

<head>
@import "mystyle.css";
</head>

CSS Rules Overriding


We have discussed four ways to include style sheet rules in an HTML document. Here is the
rule to override any Style Sheet Rule.

• Any inline style sheet takes the highest priority. So, it will override any rule defined in
<style>...</style> tags or the rules defined in any external style sheet file.

• Any rule defined in <style>...</style> tags will override the rules defined in any
external style sheet file.

• Any rule defined in the external style sheet file takes the lowest priority, and the rules
defined in this file will be applied only when the above two rules are not applicable.

Handling Old Browsers


There are still many old browsers who do not support CSS. So, we should take care while
writing our Embedded CSS in an HTML document. The following snippet shows how to use
comment tags to hide CSS from older browsers:

<style type="text/css">
<!--
body, td {
color: blue;
}
-->
</style>

21
CSS Comments
Many times, you may need to put additional comments in your style sheet blocks. So, it is
very easy to comment any part in the style sheet. You can simply put your comments inside
/*.....this is a comment in style sheet .... */.

You can use /* ....*/ to comment multi-line blocks in similar way you do in C and C++
programming languages.

Example

/* This is an external style sheet file */


h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
/* end of style rules. */

22
4. CSS ─ MEASUREMENT UNITS

Before we start the actual exercise, we would like to give a brief idea about the CSS
Measurement Units. CSS supports a number of measurements including absolute units such
as inches, centimeters, points, and so on, as well as relative measures such as percentages
and em units. You need these values while specifying various measurements in your Style
rules e.g. border="1px solid red".

We have listed out all the CSS Measurement Units along with proper Examples:

Unit Description Example

Defines a measurement as a percentage


p {font-size: 16pt; line-height:
% relative to another value, typically an
125%;}
enclosing element.

cm Defines a measurement in centimeters. div {margin-bottom: 2cm;}

A relative measurement for the height of


a font in em spaces. Because an em unit
em is equivalent to the size of a given font, if p {letter-spacing: 7em;}
you assign a font to 12pt, each "em" unit
would be 12pt; thus, 2em would be 24pt.

This value defines a measurement


relative to a font's x-height. The x-height p {font-size: 24pt; line-height:
ex
is determined by the height of the font's 3ex;}
lowercase letter x.

in Defines a measurement in inches. p {word-spacing: .15in;}

mm Defines a measurement in millimeters. p {word-spacing: 15mm;}

Defines a measurement in picas. A pica is


pc equivalent to 12 points; thus, there are 6 p {font-size: 20pc;}
picas per inch.

23
Defines a measurement in points. A point
pt body {font-size: 18pt;}
is defined as 1/72nd of an inch.

px Defines a measurement in screen pixels. p {padding: 25px;}

24
5. CSS ─ COLORS

CSS uses color values to specify a color. Typically, these are used to set a color either for the
foreground of an element (i.e., its text) or for the background of the element. They can also
be used to affect the color of borders and other decorative effects.

You can specify your color values in various formats. Following table lists all the possible
formats:

Format Syntax Example

Hex Code #RRGGBB p{color:#FF0000;}

Short Hex Code #RGB p{color:#6A7;}

RGB % rgb(rrr%,ggg%,bbb%) p{color:rgb(50%,50%,50%);}

RGB Absolute rgb(rrr,ggg,bbb) p{color:rgb(0,0,255);}

keyword aqua, black, etc. p{color:teal;}

These formats are explained in more detail in the following sections:

CSS Colors - Hex Codes


A hexadecimal is a 6 digit representation of a color. The first two digits (RR) represent a red
value, the next two are a green value (GG), and the last are the blue value (BB).

A hexadecimal value can be taken from any graphics software like Adobe Photoshop, Jasc
Paintshop Pro, or even using Advanced Paint Brush.

Each hexadecimal code will be preceded by a pound or hash sign ‘#’. Following are the
examples to use Hexadecimal notation.

Color Color HEX

25
#000000

#FF0000

#00FF00

#0000FF

#FFFF00

#00FFFF

#FF00FF

#C0C0C0

#FFFFFF

CSS Colors - Short Hex Codes


This is a shorter form of the six-digit notation. In this format, each digit is replicated to arrive
at an equivalent six-digit value. For example: #6A7 becomes #66AA77.

A hexadecimal value can be taken from any graphics software like Adobe Photoshop, Jasc
Paintshop Pro or even using Advanced Paint Brush.

Each hexadecimal code will be preceded by a pound or hash sign #. Following are the
examples to use the Hexadecimal notation.

26
1.JAVASCRIPT – OVERVIEW

What is JavaScript?
Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side
script to interact with the user and make dynamic pages. It is an interpreted
programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript
made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The
general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.

The ECMA-262 Specification defined a standard version of the core JavaScript


language.

• JavaScript is a lightweight, interpreted programming language.

• Designed for creating network-centric applications.

• Complementary to and integrated with Java.

• Complementary to and integrated with HTML.

• Open and cross-platform.

Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should
be included in or referenced by an HTML document for the code to be interpreted by
the browser.

It means that a web page need not be a static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.

11
The JavaScript code is executed when the user submits the form, and only if all the
entries are valid, they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.

Advantages of JavaScript
The merits of using JavaScript are:

• Less server interaction: You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your
server.

• Immediate feedback to the visitors: They don't have to wait for a page
reload to see if they have forgotten to enter something.

• Increased interactivity: You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.

• Richer interfaces: You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.

Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features:

• Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.

• JavaScript cannot be used for networking applications because there is no such


support available.

• JavaScript doesn't have any multithreading or multiprocessor capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that


allows you to build interactivity into otherwise static HTML pages.

JavaScript Development Tools


One of major strengths of JavaScript is that it does not require expensive
development tools. You can start with a simple text editor such as Notepad. Since it

12
is an interpreted language inside the context of a web browser, you don't even need
to buy a compiler.

To make our life simpler, various vendors have come up with very nice JavaScript
editing tools. Some of them are listed here:

• Microsoft FrontPage: Microsoft has developed a popular HTML editor called


FrontPage. FrontPage also provides web developers with a number of
JavaScript tools to assist in the creation of interactive websites.

• Macromedia Dreamweaver MX: Macromedia Dreamweaver MX is a very


popular HTML and JavaScript editor in the professional web development
crowd. It provides several handy prebuilt JavaScript components, integrates
well with databases, and conforms to new standards such as XHTML and XML.

• Macromedia HomeSite 5: HomeSite 5 is a well-liked HTML and JavaScript


editor from Macromedia that can be used to manage personal websites
effectively.

Where is JavaScript Today?


The ECMAScript Edition 5 standard will be the first update to be released in over four
years. JavaScript 2.0 conforms to Edition 5 of the ECMAScript standard, and the
difference between the two is extremely minor.

The specification for JavaScript 2.0 can be found on the following site:
http://www.ecmascript.org/

Today, Netscape's JavaScript and Microsoft's JScript conform to the ECMAScript


standard, although both the languages still support the features that are not a part
of the standard.

13
2.JAVASCRIPT – SYNTAX

JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.

You can place the <script> tags, containing your JavaScript, anywhere within you
web page, but it is normally recommended that you should keep it within the <head>
tags.

The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.

<script ...>
JavaScript code
</script>

The script tag takes two important attributes:

• Language: This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.

• Type: This attribute is what is now recommended to indicate the scripting


language in use and its value should be set to "text/javascript".

So your JavaScript syntax will look as follows.

<script language="javascript" type="text/javascript">


JavaScript code
</script>

Your First JavaScript Code


Let us take a sample example to print out "Hello World". We added an optional HTML
comment that surrounds our JavaScript code. This is to save our code from a browser
that does not support JavaScript. The comment ends with a "//-->". Here "//"
signifies a comment in JavaScript, so we add that to prevent a browser from reading

14
the end of the HTML comment as a piece of JavaScript code. Next, we call a
function document.write which writes a string into our HTML document.

This function can be used to write text, HTML, or both. Take a look at the following
code.

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Hello World!")
//-->
</script>
</body>
</html>

This code will produce the following result:

Hello World!

Whitespace and Line Breaks


JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
You can use spaces, tabs, and newlines freely in your program and you are free to
format and indent your programs in a neat and consistent way that makes the code
easy to read and understand.

Semicolons are Optional


Simple statements in JavaScript are generally followed by a semicolon character, just
as they are in C, C++, and Java. JavaScript, however, allows you to omit this
semicolon if each of your statements are placed on a separate line. For example, the
following code could be written without semicolons.

<script language="javascript" type="text/javascript">

15
<!--
var1 = 10
var2 = 20
//-->
</script>

But when formatted in a single line as follows, you must use semicolons:

<script language="javascript" type="text/javascript">


<!--
var1 = 10; var2 = 20;
//-->
</script>

Note: It is a good programming practice to use semicolons.

Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.

So the identifiers Time and TIME will convey different meanings in JavaScript.

NOTE: Care should be taken while writing variable and function names in JavaScript.

Comments in JavaScript
JavaScript supports both C-style and C++-style comments. Thus:

• Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.

• Any text between the characters /* and */ is treated as a comment. This may
span multiple lines.

16
• JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.

• The HTML comment closing sequence --> is not recognized by JavaScript so it


should be written as //-->.

Example
The following example shows how to use comments in JavaScript.

<script language="javascript" type="text/javascript">


<!--

// This is a comment. It is similar to comments in C++

/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>

17
3.JAVASCRIPT – ENABLING

All the modern browsers come with built-in support for JavaScript. Frequently, you
may need to enable or disable this support manually. This chapter explains the
procedure of enabling and disabling JavaScript support in your browsers: Internet
Explorer, Firefox, chrome, and Opera.

JavaScript in Internet Explorer


Here are the steps to turn on or turn off JavaScript in Internet Explorer:

• Follow Tools -> Internet Options from the menu.

• Select Security tab from the dialog box.

• Click the Custom Level button.

• Scroll down till you find the Scripting option.

• Select Enable radio button under Active scripting.

• Finally click OK and come out.

To disable JavaScript support in your Internet Explorer, you need to select Disable
radio button under Active scripting.

JavaScript in Firefox
Here are the steps to turn on or turn off JavaScript in Firefox:

• Open a new tab -> type about: config in the address bar.

• Then you will find the warning dialog. Select I’ll be careful, I promise!

• Then you will find the list of configure options in the browser.

• In the search bar, type javascript.enabled.

• There you will find the option to enable or disable javascript by right-clicking
on the value of that option -> select toggle.

If javascript.enabled is true; it converts to false upon clicking toogle. If javascript is


disabled; it gets enabled upon clicking toggle.
18
JavaScript in Chrome
Here are the steps to turn on or turn off JavaScript in Chrome:

• Click the Chrome menu at the top right hand corner of your browser.

• Select Settings.

• Click Show advanced settings at the end of the page.

• Under the Privacy section, click the Content settings button.

• In the "Javascript" section, select "Do not allow any site to run JavaScript"
or "Allow all sites to run JavaScript (recommended)".

JavaScript in Opera
Here are the steps to turn on or turn off JavaScript in Opera:

• Follow Tools-> Preferences from the menu.

• Select Advanced option from the dialog box.

• Select Content from the listed items.

• Select Enable JavaScript checkbox.

• Finally click OK and come out.

To disable JavaScript support in Opera, you should not select the Enable
JavaScript checkbox.

Warning for Non-JavaScript Browsers


If you have to do something important using JavaScript, then you can display a
warning message to the user using <noscript> tags.

You can add a noscript block immediately after the script block as follows:

<html>
<body>

<script language="javascript" type="text/javascript">


<!--
19
document.write ("Hello World!")
//-->
</script>

<noscript>
Sorry...JavaScript is needed to go ahead.
</noscript>
</body>
</html>

Now, if the user's browser does not support JavaScript or JavaScript is not enabled,
then the message from </noscript> will be displayed on the screen.

20
4.JAVASCRIPT – PLACEMENT

There is a flexibility given to include JavaScript code anywhere in an HTML document.


However the most preferred ways to include JavaScript in an HTML file are as follows:

• Script in <head>...</head> section.

• Script in <body>...</body> section.

• Script in <body>...</body> and <head>...</head> sections.

• Script in an external file and then include in <head>...</head> section.

In the following section, we will see how we can place JavaScript in an HTML file in
different ways.

JavaScript in <head>...</head> Section


If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows.

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
<input type="button" onclick="sayHello()" value="Say Hello" />

21
</body>
</html>

This code will produce the following results:

Click here for the result

Say Hello

JavaScript in <body>...</body> Section


If you need a script to run as the page loads so that the script generates content in
the page, then the script goes in the <body> portion of the document. In this case,
you would not have any function defined using JavaScript. Take a look at the following
code.

<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>

This code will produce the following results:

Hello World

22
This is web page body

JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as
follows.

<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

This code will produce the following result.

HelloWorld
Say Hello

23
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find that
there are cases where you are reusing identical JavaScript code on multiple pages of
a site.

You are not restricted to be maintaining identical code in multiple HTML files.
The script tag provides a mechanism to allow you to store JavaScript in an external
file and then include it into your HTML files.

Here is an example to show how you can include an external JavaScript file in your
HTML code using script tag and its src attribute.

<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>

To use JavaScript from an external file source, you need to write all your JavaScript
source code in a simple text file with the extension ".js" and then include that file as
shown above.

For example, you can keep the following content in filename.js file and then you
can use sayHello function in your HTML file after including the filename.js file.

function sayHello() {
alert("Hello World")
}

24
5.JAVASCRIPT – VARIABLES

JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set
of data types it supports. These are the type of values that can be represented and
manipulated in a programming language.

JavaScript allows you to work with three primitive data types:

• Numbers, e.g., 123, 120.50 etc.

• Strings of text, e.g. "This text string" etc.

• Boolean, e.g. true or false.

JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value. In addition to these primitive data types, JavaScript
supports a composite data type known as object. We will cover objects in detail in a
separate chapter.

Note: Java does not make a distinction between integer values and floating-point
values. All numbers in JavaScript are represented as floating-point values. JavaScript
represents numbers using the 64-bit floating-point format defined by the IEEE 754
standard.

JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.

<script type="text/javascript">
<!--
var money;
var name;
25
//-->
</script>

You can also declare multiple variables with the same var keyword as follows:

<script type="text/javascript">
<!--
var money, name;
//-->
</script>

Storing a value in a variable is called variable initialization. You can do variable


initialization at the time of variable creation or at a later point in time when you need
that variable.

For instance, you might create a variable named money and assign the value
2000.50 to it later. For another variable, you can assign a value at the time of
initialization as follows.

<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>

Note: Use the var keyword only for declaration or initialization, once for the life of
any variable name in a document. You should not re-declare same variable twice.

JavaScript is untyped language. This means that a JavaScript variable can hold a
value of any data type. Unlike many other languages, you don't have to tell JavaScript
during variable declaration what type of value the variable will hold. The value type
of a variable can change during the execution of a program and JavaScript takes care
of it automatically.

26
JavaScript Variable Scope
The scope of a variable is the region of your program in which it is defined. JavaScript
variables have only two scopes.

• Global Variables: A global variable has global scope which means it can be
defined anywhere in your JavaScript code.

• Local Variables: A local variable will be visible only within a function where it
is defined. Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable
with the same name. If you declare a local variable or function parameter with the
same name as a global variable, you effectively hide the global variable. Take a look
into the following example.

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

It will produce the following result:

Local

JavaScript Variable Names


While naming your variables in JavaScript, keep the following rules in mind.

27
• You should not use any of the JavaScript reserved keywords as a variable
name. These keywords are mentioned in the next section. For example, break
or boolean variable names are not valid.

• JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or an underscore character. For example, 123test is an
invalid variable name but _123test is a valid one.

• JavaScript variable names are case-sensitive. For example, Name and name
are two different variables.

JavaScript Reserved Words


A list of all the reserved words in JavaScript are given in the following table. They
cannot be used as JavaScript variables, functions, methods, loop labels, or any object
names.

abstract else Instanceof switch

boolean enum int synchronized

break export interface this

byte extends long throw

case false native throws

catch final new transient

char finally null true

class float package try

const for private typeof

continue function protected var

debugger goto public void

default if return volatile

delete implements short while

do import static with

double in super

28
6.JAVASCRIPT – OPERATORS

What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and ‘+’ is called the operator. JavaScript supports the following types of
operators.

• Arithmetic Operators

• Comparison Operators

• Logical (or Relational) Operators

• Assignment Operators

• Conditional (or ternary) Operators

Let’s have a look at all the operators one by one.

Arithmetic Operators
JavaScript supports the following arithmetic operators:

Assume variable A holds 10 and variable B holds 20, then:

S. No. Operator and Description

+ (Addition)

1 Adds two operands

Ex: A + B will give 30

- (Subtraction)

2 Subtracts the second operand from the first

Ex: A - B will give -10

29
* (Multiplication)

3 Multiply both operands

Ex: A * B will give 200

/ (Division)

4 Divide the numerator by the denominator

Ex: B / A will give 2

% (Modulus)

5 Outputs the remainder of an integer division

Ex: B % A will give 0

++ (Increment)

6 Increases an integer value by one

Ex: A++ will give 11

-- (Decrement)

7 Decreases an integer value by one

Ex: A-- will give 9

Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will
give "a10".
Example
The following code shows how to use arithmetic operators in JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = 33;

30
var b = 10;
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

31
a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);

b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and then try...</p>


</body>
</html>

Output

a + b = 43
a - b = 23
a / b = 3.3
a % b = 3
a + b + c = 43Test
a++ = 33
b-- = 10

Set the variables to different values and then try...

32
Comparison Operators
JavaScript supports the following comparison operators:

Assume variable A holds 10 and variable B holds 20, then:

S.No Operator and Description

== (Equal)

Checks if the value of two operands are equal or not, if yes, then
1
the condition becomes true.

Ex: (A == B) is not true.

!= (Not Equal)

Checks if the value of two operands are equal or not, if the values
2
are not equal, then the condition becomes true.

Ex: (A != B) is true.

> (Greater than)

Checks if the value of the left operand is greater than the value of
3
the right operand, if yes, then the condition becomes true.

Ex: (A > B) is not true.

< (Less than)

Checks if the value of the left operand is less than the value of the
4
right operand, if yes, then the condition becomes true.

Ex: (A < B) is true.

>= (Greater than or Equal to)

Checks if the value of the left operand is greater than or equal to


5 the value of the right operand, if yes, then the condition becomes
true.

Ex: (A >= B) is not true.

33
<= (Less than or Equal to)

Checks if the value of the left operand is less than or equal to the
6
value of the right operand, if yes, then the condition becomes true.

Ex: (A <= B) is true.

Example
The following code shows how to use comparison operators in JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write("(a == b) => ");


result = (a == b);
document.write(result);
document.write(linebreak);

document.write("(a < b) => ");


result = (a < b);
document.write(result);
document.write(linebreak);

document.write("(a > b) => ");


result = (a > b);
document.write(result);
document.write(linebreak);
34
document.write("(a != b) => ");
result = (a != b);
document.write(result);
document.write(linebreak);

document.write("(a >= b) => ");


result = (a >= b);
document.write(result);
document.write(linebreak);

document.write("(a <= b) => ");


result = (a <= b);
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false

35
(a <= b) => true

Set the variables to different values and different operators and then
try...

Logical Operators
JavaScript supports the following logical operators:

Assume variable A holds 10 and variable B holds 20, then:

S.No Operator and Description

&& (Logical AND)

1 If both the operands are non-zero, then the condition becomes true.

Ex: (A && B) is true.

|| (Logical OR)

2 If any of the two operands are non-zero, then the condition becomes true.

Ex: (A || B) is true.

! (Logical NOT)

Reverses the logical state of its operand. If a condition is true, then the
3
Logical NOT operator will make it false.

Ex: ! (A && B) is false.

Example

36
Try the following code to learn how to implement Logical Operators in JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";

document.write("(a && b) => ");


result = (a && b);
document.write(result);
document.write(linebreak);

document.write("(a || b) => ");


result = (a || b);
document.write(result);
document.write(linebreak);

document.write("!(a && b) => ");


result = (!(a && b));
document.write(result);
document.write(linebreak);

//-->
</script>

37
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

(a && b) => false


(a || b) => true
!(a && b) => true

Set the variables to different values and different operators and then
try...

Bitwise Operators
JavaScript supports the following bitwise operators:
Assume variable A holds 2 and variable B holds 3, then:

S.No Operator and Description

& (Bitwise AND)

1 It performs a Boolean AND operation on each bit of its integer arguments.

Ex: (A & B) is 2.

| (BitWise OR)

2 It performs a Boolean OR operation on each bit of its integer arguments.

Ex: (A | B) is 3.

3 ^ (Bitwise XOR)

38
It performs a Boolean exclusive OR operation on each bit of its integer
arguments. Exclusive OR means that either operand one is true or operand
two is true, but not both.

Ex: (A ^ B) is 1.

~ (Bitwise Not)

4 It is a unary operator and operates by reversing all the bits in the operand.

Ex: (~B) is -4.

<< (Left Shift)

It moves all the bits in its first operand to the left by the number of places
specified in the second operand. New bits are filled with zeros. Shifting a
5
value left by one position is equivalent to multiplying it by 2, shifting two
positions is equivalent to multiplying by 4, and so on.

Ex: (A << 1) is 4.

>> (Right Shift)

Binary Right Shift Operator. The left operand’s value is moved right by the
6
number of bits specified by the right operand.

Ex: (A >> 1) is 1.

>>> (Right shift with Zero)

This operator is just like the >> operator, except that the bits shifted in
7
on the left are always zero.

Ex: (A >>> 1) is 1.

Example
Try the following code to implement Bitwise operator in JavaScript.

<html>
<body>

<script type="text/javascript">

39
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";

document.write("(a & b) => ");


result = (a & b);
document.write(result);
document.write(linebreak);

document.write("(a | b) => ");


result = (a | b);
document.write(result);
document.write(linebreak);

document.write("(a ^ b) => ");


result = (a ^ b);
document.write(result);
document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << b);
document.write(result);
document.write(linebreak);

40
document.write("(a >> b) => ");
result = (a >> b);
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0

Set the variables to different values and different operators and then
try...

Assignment Operators
JavaScript supports the following assignment operators:

S.No Operator and Description

= (Simple Assignment )
1
Assigns values from the right side operand to the left side operand

41
Ex: C = A + B will assign the value of A + B into C

+= (Add and Assignment)

It adds the right operand to the left operand and assigns the result to the
2
left operand.

Ex: C += A is equivalent to C = C + A

-= (Subtract and Assignment)

It subtracts the right operand from the left operand and assigns the result
3
to the left operand.

Ex: C -= A is equivalent to C = C - A

*= (Multiply and Assignment)

It multiplies the right operand with the left operand and assigns the result
4
to the left operand.

Ex: C *= A is equivalent to C = C * A

/= (Divide and Assignment)

It divides the left operand with the right operand and assigns the result to
5
the left operand.

Ex: C /= A is equivalent to C = C / A

%= (Modules and Assignment)

It takes modulus using two operands and assigns the result to the left
6
operand.

Ex: C %= A is equivalent to C = C % A

Note: Same logic applies to Bitwise operators, so they will become <<=, >>=, >>=,
&=, |= and ^=.

Example
Try the following code to implement assignment operator in JavaScript.

42
<html>
<body>

<script type="text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";

document.write("Value of a => (a = b) => ");


result = (a = b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a += b) => ");


result = (a += b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a -= b) => ");


result = (a -= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a *= b) => ");


result = (a *= b);
document.write(result);
document.write(linebreak);

43
document.write("Value of a => (a /= b) => ");
result = (a /= b);
document.write(result);
document.write(linebreak);

document.write("Value of a => (a %= b) => ");


result = (a %= b);
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

Value of a => (a = b) => 10


Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0

Set the variables to different values and different operators and then
try...

44
Miscellaneous Operators
We will discuss two operators here that are quite useful in JavaScript: the
conditional operator (? :) and the typeof operator.

Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result of the
evaluation.

S.No Operator and Description

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

Example
Try the following code to understand how the Conditional Operator works in
JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


45
result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);

//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

((a > b) ? 100 : 200) => 200


((a < b) ? 100 : 200) => 100

Set the variables to different values and different operators and then
try...

typeof Operator
The typeof operator is a unary operator that is placed before its single operand,
which can be of any type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to "number", "string", or "boolean" if its operand is a


number, string, or boolean value and returns true or false based on the evaluation.

Here is a list of the return values for the typeof Operator.

Type String Returned by typeof

Number "number"

String "string"

46
Boolean "boolean"

Object "object"

Function "function"

Undefined "undefined"

Null "object"

Example
The following code shows how to implement typeof operator.

<html>
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = "String";
var linebreak = "<br />";

result = (typeof b == "string" ? "B is String" : "B is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

result = (typeof a == "string" ? "A is String" : "A is Numeric");


document.write("Result => ");
document.write(result);
document.write(linebreak);

47
//-->
</script>

<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>

Output

Result => B is String


Result => A is Numeric

Set the variables to different values and different operators and then
try...

48
J AV A - N E T W O R KI N G

The term network programming refers to writing programs that execute across multiple devices
computers, in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide
the low-level communication details, allowing you to write programs that focus on solving the
problem at hand.

The java.net package provides support for the two common network protocols:

TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to
as TCP/IP.

UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for
packets of data to be transmitted between applications.

This tutorial gives good understanding on the following two subjects:

Socket Programming: This is most widely used concept in Networking and it has been
explained in very detail.

URL Processing: This would be covered separately. Click here to learn about URL
Processing in Java language.

Socket Programming:
Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket to
a server.

When the connection is made, the server creates a socket object on its end of the communication.
The client and server can now communicate by writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a
mechanism for the server program to listen for clients and establish connections with them.

The following steps occur when establishing a TCP connection between two computers using
sockets:

The server instantiates a ServerSocket object, denoting which port number communication is
to occur on.

The server invokes the accept method of the ServerSocket class. This method waits until a
client connects to the server on the given port.

After the server is waiting, a client instantiates a Socket object, specifying the server name
and port number to connect to.

The constructor of the Socket class attempts to connect the client to the specified server and
port number. If communication is established, the client now has a Socket object capable of
communicating with the server.

On the server side, the accept method returns a reference to a new socket on the server that
is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket
has both an OutputStream and an InputStream. The client's OutputStream is connected to the
server's InputStream, and the client's InputStream is connected to the server's OutputStream.

TCP is a twoway communication protocol, so data can be sent across both streams at the same
time. There are following usefull classes providing complete set of methods to implement sockets.
ServerSocket Class Methods:
The java.net.ServerSocket class is used by server applications to obtain a port and listen for
client requests

The ServerSocket class has four constructors:

SN Methods with Description

1 public ServerSocketintport throws IOException

Attempts to create a server socket bound to the specified port. An exception occurs if the
port is already bound by another application.

2 public ServerSocketintport, intbacklog throws IOException

Similar to the previous constructor, the backlog parameter specifies how many incoming
clients to store in a wait queue.

3 public ServerSocketintport, intbacklog, InetAddressaddress throws IOException

Similar to the previous constructor, the InetAddress parameter specifies the local IP
address to bind to. The InetAddress is used for servers that may have multiple IP
addresses, allowing the server to specify which of its IP addresses to accept client requests
on

4 public ServerSocket throws IOException

Creates an unbound server socket. When using this constructor, use the bind method when
you are ready to bind the server socket

If the ServerSocket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.

Here are some of the common methods of the ServerSocket class:

SN Methods with Description

1 public int getLocalPort

Returns the port that the server socket is listening on. This method is useful if you passed
in 0 as the port number in a constructor and let the server find a port for you.

2 public Socket accept throws IOException

Waits for an incoming client. This method blocks until either a client connects to the server
on the specified port or the socket times out, assuming that the time-out value has been
set using the setSoTimeout method. Otherwise, this method blocks indefinitely

3 public void setSoTimeoutinttimeout

Sets the time-out value for how long the server socket waits for a client during the accept.

4 public void bindSocketAddresshost, intbacklog

Binds the socket to the specified server and port in the SocketAddress object. Use this
method if you instantiated the ServerSocket using the no-argument constructor.
When the ServerSocket invokes accept, the method does not return until a client connects. After a
client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a
reference to this new Socket. A TCP connection now exists between the client and server, and
communication can begin.

Socket Class Methods:


The java.net.Socket class represents the socket that both the client and server use to
communicate with each other. The client obtains a Socket object by instantiating one, whereas the
server obtains a Socket object from the return value of the accept method.

The Socket class has five constructors that a client uses to connect to a server:

SN Methods with Description

1 public SocketStringhost, intport throws UnknownHostException, IOException.

This method attempts to connect to the specified server at the specified port. If this
constructor does not throw an exception, the connection is successful and the client is
connected to the server.

2 public SocketInetAddresshost, intport throws IOException

This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object.

3 public SocketStringhost, intport, InetAddresslocalAddress, intlocalPort throws IOException.

Connects to the specified host and port, creating a socket on the local host at the specified
address and port.

4 public SocketInetAddresshost, intport, InetAddresslocalAddress, intlocalPort throws IOException.

This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object instead of a String

5 public Socket

Creates an unconnected socket. Use the connect method to connect this socket to a
server.

When the Socket constructor returns, it does not simply instantiate a Socket object but it actually
attempts to connect to the specified server and port.

Some methods of interest in the Socket class are listed here. Notice that both the client and server
have a Socket object, so these methods can be invoked by both the client and server.

SN Methods with Description

1 public void connectSocketAddresshost, inttimeout throws IOException

This method connects the socket to the specified host. This method is needed only when
you instantiated the Socket using the no-argument constructor.

2 public InetAddress getInetAddress


This method returns the address of the other computer that this socket is connected to.

3 public int getPort

Returns the port the socket is bound to on the remote machine.

4 public int getLocalPort

Returns the port the socket is bound to on the local machine.

5 public SocketAddress getRemoteSocketAddress

Returns the address of the remote socket.

6 public InputStream getInputStream throws IOException

Returns the input stream of the socket. The input stream is connected to the output stream
of the remote socket.

7 public OutputStream getOutputStream throws IOException

Returns the output stream of the socket. The output stream is connected to the input
stream of the remote socket

8 public void close throws IOException

Closes the socket, which makes this Socket object no longer capable of connecting again
to any server

InetAddress Class Methods:


This class represents an Internet Protocol IP address. Here are following usefull methods which you
would need while doing socket programming:

SN Methods with Description

1 static InetAddress getByAddressbyte[]addr

Returns an InetAddress object given the raw IP address .

2 static InetAddress getByAddressStringhost, byte[]addr

Create an InetAddress based on the provided host name and IP address.

3 static InetAddress getByNameStringhost

Determines the IP address of a host, given the host's name.

4 String getHostAddress

Returns the IP address string in textual presentation.

5 String getHostName

Gets the host name for this IP address.


6 static InetAddress InetAddress getLocalHost

Returns the local host.

7 String toString

Converts this IP address to a String.

Socket Client Example:


The following GreetingClient is a client program that connects to a server by using a socket and
sends a greeting, and then waits for a response.

// File Name GreetingClient.java

import java.net.*;
import java.io.*;

public class GreetingClient


{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName +
" on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFrom Server = client.getInputStream();
DataInputStream in =
new DataInputStream(inFrom Server);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

Socket Server Example:


The following GreetingServer program is an example of a server application that uses the Socket
class to listen for clients on a port number specified by a command-line argument:

// File Name GreetingServer.java

import java.net.*;
import java.io.*;

public class GreetingServer extends Thread


{
private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException


{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}

public void run()


{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

Compile client and server and then start server as follows:

$ java GreetingServer 6066


Waiting for client on port 6066...
EJB
1. EJB – OVERVIEW

EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform. J2EE
platform has component based architecture to provide multi-tiered, distributed and highly
transactional features to enterprise level applications.

EJB provides an architecture to develop and deploy component based enterprise applications
considering robustness, high scalability, and high performance. An EJB application can be
deployed on any of the application server compliant with the J2EE 1.3 standard specification.

We'll be discussing EJB 3.0 in detail in this tutorial.

Types
EJB is primarily divided into three categories; following table lists their names with brief
descriptions:

Type Description

Session bean stores data of a particular user for a single


session. It can be stateful or stateless. It is less resource
Session Bean
intensive as compared to entity bean. Session bean gets
destroyed as soon as user session terminates.

Entity beans represent persistent data storage. User data


Entity Bean can be saved to database via entity beans and later on can
be retrieved from the database in the entity bean.

Message driven beans are used in context of JMS (Java


Message Driven
Messaging Service). Message Driven Beans can consumes
Bean
JMS messages from external entities and act accordingly.

Benefits
Following are the important benefits of EJB:

• Simplified development of large-scale enterprise level application.

• Application Server/EJB container provides most of the system level services like
transaction handling, logging, load balancing, persistence mechanism, exception
handling, and so on. Developer has to focus only on business logic of the application.

7
EJB

• EJB container manages life cycle of EJB instances, thus developer needs not to worry
about when to create/delete EJB objects.

8
EJB
2. EJB – ENVIRONMENT SETUP

EJB is a framework for Java, so the very first requirement is to have a Java Development Kit
(JDK) installed in your machine.

System Requirement
JDK 1.5 or above.
Memory no minimum requirement.
Disk Space no minimum requirement.
Operating System no minimum requirement.

Step 1 - VerifyJavaInstallation inYour System


Now open console and execute the following java command.

OS Task Command
Open Command
Windows c:\> java -version
Console
Open Command
Linux $ java -version
Terminal
Mac Open Terminal machine:~ joseph$ java -version

Let's verify the output for all the operating systems:

OS Output
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b11)
Windows
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed
mode)
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b11)
Linux
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed
mode)
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b11)
Mac
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed
mode)

If you do not have Java installed, install the Java Software Development Kit (SDK) from
http://www.oracle.com/technetwork/java/javase/downloads/index.html.
9
EJB

We are assuming that Java 1.6.0_21 as installed version for this tutorial.

Step 2 – Set JAVAEnvironment


Set the JAVA_HOME environment variable to point the base directory location where Java is
installed on your system. For example,

OS Output
Set the environment variable JAVA_HOME to C:\Program
Windows
Files\Java\jdk1.6.0_21
Linux export JAVA_HOME=/usr/local/java-current
Mac export JAVA_HOME=/Library/Java/Home

Append Java compiler location to System Path.

OS Output
Append the string ;C:\Program Files\Java\jdk1.6.0_21\bin to the
Windows
end of the system variable, Path.
Linux export PATH=$PATH:$JAVA_HOME/bin/
Mac not required

Verify Java Installation using java -version command explained above.

Step 3 – Download and Install NetBeans IDE


Download the latest version of NetBeans IDE from
https://netbeans.org/downloads/index.html. At the time of writing this tutorial, I downloaded
Netbeans 7.3, which comes bundled with JDK 1.7 using the following link
http://www.oracle.com/technetwork/java/javase/downloads/index.html

OS Installer name
Windows Netbeans 7.3
Linux Netbeans 7.3
Mac Netbeans 7.3

Step 4 – Set up JBossApplication Server


You can download the latest version of JBoss Server from
http://www.jboss.org/jbossas/downloads/. Download the archive as per the platform. Extract
the Jboss to any location on your machine.

10
EJB

OS File name
Windows jboss-5.1.0.GA-jdk6.zip
Linux jboss-5.1.0.GA-src.tar.gz
Mac jboss-5.1.0.GA-src.tar.gz

Step5– Configure JEE Pluginsto Netbeans


Open Plugin window using Tools > Plugins. Open "Available Plugin" tab and select "Java EE
Base" and "EJB and EAR" under "Java Web and EE" category. Click install button. Netbeans
will download and install the respective plugins. Verify plugins installation using "Installed"
tab (as shown in the image given below).

Step6– Configure JBossServerinNetbeans


Go to Services tab and right click on servers to add a new server.

11
EJB

Add Server Instance wizard will open. Select JBoss and in next step enter the relevant details
to configure server in netbeans.

Once everything is configured, you will see the following screen.

12
EJB

Step 7 – Install Database Server (PostGreSql)


Download latest version of PostGreSql database server from
http://www.postgresql.org/download/. At the time of writing this tutorial, I downloaded
PostGreSql 9.2

OS Installer name
Windows PostGreSql 9.2
Linux PostGreSql 9.2
Mac PostGreSql 9.2

13
EJB
3. EJB – CREATE APPLICATION

To create a simple EJB module, we will use NetBeans, "New project" wizard. In the example
given below, We will create an EJB module project named Component.

Create Project
In NetBeans IDE, select File > New Project >. You will see the following screen.

Select project type under category Java EE, Project type as EJB Module. Click Next >
button. You will see the following screen.

14
EJB

Enter project name and location. Click Next > button. You will see the following screen.

15
EJB

Select Server as JBoss Application Server. Click Finish button. You will see the following
project created by NetBeans.

Create a Sample EJB


To create a simple EJB, we will use NetBeans "New" wizard. In the example given below, We
will create a stateless EJB class named librarySessionBean under EjbComponent project.

Select project EjbComponent in project explorer window and right click on it. Select, New >
Session Bean. You will see the New Session Bean wizard.

16
EJB

Enter session bean name and package name. Click Finish button. You will see the following
EJB classes created by NetBeans.

• LibrarySessionBean - stateless session bean

• LibrarySessionBeanLocal - local interface for session bean

I am changing local interface to remote interface as we are going to access our EJB in a
console based application. Remote/Local interface is used to expose business methods that
an EJB has to implement.

LibrarySessionBeanLocal is renamed to LibrarySessionBeanRemote and LibrarySessionBean


implements LibrarySessionBeanRemote interface.

LibrarySessionBeanRemote

package com.tutorialspoint.stateless;

import java.util.List;
import javax.ejb.Remote;

@Remote

17
EJB

public interface LibrarySessionBeanRemote {

void addBook(String bookName);

List getBooks();

LibrarySessionBean

package com.tutorialspoint.stateless;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;

@Stateless
public class LibrarySessionBean implements LibrarySessionBeanRemote {

List<String> bookShelf;

public LibrarySessionBean(){
bookShelf = new ArrayList<String>();
}

public void addBook(String bookName) {


bookShelf.add(bookName);
}

public List<String> getBooks() {


return bookShelf;
}
}

18
EJB

Build the Project


• Select EjbComponent project in Project Explorer window

• Right click on it to open context menu.

• Select clean and build.

You will see the following output in NetBeans console output.

ant -f C:\\EJB\\EjbComponent clean dist


init:
undeploy-clean:
deps-clean:
Deleting directory C:\EJB\EjbComponent\build
Deleting directory C:\EJB\EjbComponent\dist
clean:
init:
deps-jar:
Created dir: C:\EJB\EjbComponent\build\classes
Copying 3 files to C:\EJB\EjbComponent\build\classes\META-INF
Created dir: C:\EJB\EjbComponent\build\empty
Created dir: C:\EJB\EjbComponent\build\generated-sources\ap-source-output
Compiling 2 source files to C:\EJB\EjbComponent\build\classes
warning: [options] bootstrap class path not set in conjunction with -source 1.6
Note: C:\EJB\EjbComponent\src\java\com\tutorialspoint\stateless
\LibraryPersistentBean.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 warning
compile:
library-inclusion-in-archive:
Created dir: C:\EJB\EjbComponent\dist
Building jar: C:\EJB\EjbComponent\dist\EjbComponent.jar
dist:
BUILD SUCCESSFUL (total time: 3 seconds)

19
EJB

Start the Application Server


• Select JBoss application server under Servers in Services window.

• Right click on it to open context menu.

• Select start.

You will see the following output in NetBeans, output under JBoss Application Server.

Calling C:\jboss-5.1.0.GA\bin\run.conf.bat
=========================================================================

JBoss Bootstrap Environment

JBOSS_HOME: C:\jboss-5.1.0.GA

JAVA: C:\Program Files (x86)\Java\jdk1.6.0_21\bin\java

JAVA_OPTS: -Dprogram.name=run.bat -Xms128m -Xmx512m -server

CLASSPATH: C:\jboss-5.1.0.GA\bin\run.jar

=========================================================================

16:25:50,062 INFO [ServerImpl] Starting JBoss (Microcontainer)...


16:25:50,062 INFO [ServerImpl] Release ID: JBoss [The Oracle] 5.1.0.GA (build:
SVNTag=JBoss_5_1_0_GA date=200905221634)
...

16:26:40,420 INFO [TomcatDeployment] deploy, ctxPath=/admin-console


16:26:40,485 INFO [config] Initializing Mojarra (1.2_12-b01-FCS) for context
'/admin-console'

16:26:42,362 INFO [TomcatDeployment] deploy, ctxPath=/


16:26:42,406 INFO [TomcatDeployment] deploy, ctxPath=/jmx-console
16:26:42,471 INFO [Http11Protocol] Starting Coyote HTTP/1.1 on http-127.0.0.1-
8080
16:26:42,487 INFO [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009

20
EJB

16:26:42,493 INFO [ServerImpl] JBoss (Microcontainer) [5.1.0.GA (build:


SVNTag=JBoss_5_1_0_GA date=200905221634)] Started in 52s:427ms

Deploy the Project


• Select EjbComponent project in Project Explorer window.

• Right click on it to open context menu.

• Select Deploy.

You will see the following output in NetBeans console output.

ant -f C:\\EJB\\EjbComponent -DforceRedeploy=true -


Ddirectory.deployment.supported=false -Dnb.wait.for.caches=true run
init:
deps-jar:
compile:
library-inclusion-in-archive:
Building jar: C:\EJB\EjbComponent\dist\EjbComponent.jar
dist-directory-deploy:
pre-run-deploy:
Checking data source definitions for missing JDBC drivers...
Distributing C:\EJB\EjbComponent\dist\EjbComponent.jar to
[org.jboss.deployment.spi.LocalhostTarget@1e4f84ee]
Deploying C:\EJB\EjbComponent\dist\EjbComponent.jar
Application Deployed
Operation start started
Operation start completed
post-run-deploy:
run-deploy:
run:
BUILD SUCCESSFUL (total time: 2 seconds)

JBoss Application Server Log Output

16:30:00,963 INFO [DeployHandler] Begin start, [EjbComponent.jar]


...

21
EJB

16:30:01,233 INFO [Ejb3DependenciesDeployer] Encountered deployment


AbstractVFSDeploymentContext@12038795{vfszip:/C:/jboss-
5.1.0.GA/server/default/deploy/EjbComponent.jar/}
...
16:30:01,281 INFO [JBossASKernel] jndi:LibrarySessionBean/remote-
com.tutorialspoint.stateless.LibrarySessionBeanRemote
16:30:01,281 INFO [JBossASKernel]
Class:com.tutorialspoint.stateless.LibrarySessionBeanRemote
16:30:01,281 INFO [JBossASKernel] jndi:LibrarySessionBean/remote
16:30:01,281 INFO [JBossASKernel] Added
bean(jboss.j2ee:jar=EjbComponent.jar,name=
LibrarySessionBean,service=EJB3) to KernelDeployment of: EjbComponent.jar
16:30:01,282 INFO [JBossASKernel] installing bean:
jboss.j2ee:jar=EjbComponent.jar,name=BookMessageHandler,service=EJB3
16:30:01,282 INFO [JBossASKernel] with dependencies:
16:30:01,282 INFO [JBossASKernel] and demands:
16:30:01,282 INFO [JBossASKernel] jboss.ejb:service=EJBTimerService
...
16:30:01,283 INFO [EJB3EndpointDeployer] Deploy
AbstractBeanMetaData@5497cb{name=jboss.j2ee:jar=EjbComponent.jar,
name=LibrarySessionBean, service=EJB3_endpoint
bean=org.jboss.ejb3.endpoint.deployers.impl.EndpointImpl properties=[container]
constructor=null autowireCandidate=true}
...
16:30:01,394 INFO [SessionSpecContainer] Starting
jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:01,395 INFO [EJBContainer] STARTED EJB:
com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean
16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in
Global JNDI:
LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote
- EJB3.x Remote Business Interface
16:30:02,723 INFO [SessionSpecContainer] Starting
jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:02,723 INFO [EJBContainer] STARTED EJB:
com.tutorialspoint.stateless.LibrarySessionBean ejbName: LibrarySessionBean
16:30:02,731 INFO [JndiSessionRegistrarBase] Binding the following Entries in
Global JNDI:
22
EJB

LibrarySessionBean/remote - EJB3.x Default Remote Business Interface


LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote
- EJB3.x Remote Business Interface

Create Client toAccess EJB


• In NetBeans IDE, select File > New Project >.

• Select project type under category Java, Project type as Java Application. Click Next
> button.

• Enter project name and location. Click Finish > button. We have chosen name as
EjbTester.

• Right click on project name in Project explorer window. Select properties.

• Add EJB component project created earlier under libraries using Add Project button
in compile tab.

• Add jboss libraries using Add jar/folder button in compile tab. Jboss libraries can
be located at <jboss installation folder>> client folder.

23
1. INTRODUCTION Node.js

What is Node.js?
Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine).
Node.js was developed by Ryan Dahl in 2009 and its latest version is v0.10.36. The definition
of Node.js as supplied by its official documentation is as follows:

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast and
scalable network applications. Node.js uses an event-driven, non-blocking I/O model
that makes it lightweight and efficient, perfect for data-intensive real-time applications
that run across distributed devices.

Node.js is an open source, cross-platform runtime environment for developing server-side


and networking applications. Node.js applications are written in JavaScript, and can be run
within the Node.js runtime on OS X, Microsoft Windows, and Linux.

Node.js also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.

Node.js = Runtime Environment + JavaScript Library

Features of Node.js
Following are some of the important features that make Node.js the first choice of software
architects.

• Asynchronous and Event Driven − All APIs of Node.js library are asynchronous,
that is, non-blocking. It essentially means a Node.js based server never waits for an
API to return data. The server moves to the next API after calling it and a notification
mechanism of Events of Node.js helps the server to get a response from the previous
API call.

• Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is
very fast in code execution.

• Single Threaded but Highly Scalable − Node.js uses a single threaded model with
event looping. Event mechanism helps the server to respond in a non-blocking way
and makes the server highly scalable as opposed to traditional servers which create
limited threads to handle requests. Node.js uses a single threaded program and the
same program can provide service to a much larger number of requests than
traditional servers like Apache HTTP Server.

5
Node.js

• No Buffering − Node.js applications never buffer any data. These applications simply
output the data in chunks.

• License − Node.js is released under the MIT license.

Who Uses Node.js?


Following is the link on github wiki containing an exhaustive list of projects, application and
companies which are using Node.js. This list includes eBay, General Electric, GoDaddy,
Microsoft, PayPal, Uber, Wikipins, Yahoo!, and Yammer to name a few.

• Projects, Applications, and Companies Using Node

Concepts
The following diagram depicts some important parts of Node.js which we will discuss in detail
in the subsequent chapters.

Where to Use Node.js?


Following are the areas where Node.js is proving itself as a perfect technology partner.

6
Node.js

● I/O bound Applications


● Data Streaming Applications
● Data Intensive Real-time Applications (DIRT)
● JSON APIs based Applications
● Single Page Applications

Where Not to Use Node.js?


It is not advisable to use Node.js for CPU intensive applications.

7
2. ENVIRONMENT SETUP Node.js

Try it Option Online


You really do not need to set up your own environment to start learning Node.js. Reason is
very simple, we already have set up Node.js environment online, so that you can execute all
the available examples online and learn through practice. Feel free to modify any example
and check the results with different options.

Try the following example using the Try it option available at the top right corner of the below
sample code box (on our website):

/* Hello World! program in Node.js */


console.log("Hello World!");

For most of the examples given in this tutorial, you will find a Try it option, so just make use
of it and enjoy your learning.

Local Environment Setup


If you want to set up your environment for Node.js, you need to have the following two
software on your computer, (a) a Text Editor and (b) the Node.js binary installables.

Text Editor
You need to have a text editor to type your program. Examples of text editors include Windows
Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.

The name and version of text editors can vary from one operating system to another. For
example, Notepad will be used on Windows, and vim or vi can be used on Windows as well as
Linux or UNIX.

The files you create with your editor are called source files and they contain the program
source code. The source files for Node.js programs are typically named with the extension
".js".

Before you start programming, make sure you have one text editor in place and you have
enough experience in how to write a computer program, save it in a file, and finally execute
it.

8
Node.js

The Node.js Runtime


The source code that you would write in a source file is simply javascript. The Node.js
interpreter interprets and executes your javascript code.

Node.js distribution comes as a binary installable for SunOS, Linux, Mac OS X, and Windows
operating systems with the 32-bit (386) and 64-bit (amd64) x86 processor architectures.

The following section explains how to install Node.js binary distribution on various OS.

Download Node.jsArchive
Download the latest version of Node.js installable archive file from Node.js Downloads. At the
time of writing this tutorial, following are the versions available on different OS.

OS Archive name

Windows node-v6.3.1-x64.msi

Linux node-v6.3.1-linux-x86.tar.gz

Mac node-v6.3.1-darwin-x86.tar.gz

SunOS node-v6.3.1-sunos-x86.tar.gz

Installation on UNIX/Linux/Mac OS X and SunOS


Based on your OS architecture, download and extract the archive node-v0.12.0-
osname.tar.gz into /tmp, and then move the extracted files into /usr/local/nodejs directory.
For example:

$ cd /tmp
$ wget http://nodejs.org/dist/v6.3.1/node-v6.3.1-linux-x64.tar.gz
$ tar xvfz node-v6.3.1-linux-x64.tar.gz
$ mkdir -p /usr/local/nodejs
$ mv node-v6.3.1-linux-x64/* /usr/local/nodejs

Add /usr/local/nodejs/bin to the PATH environment variable.

OS Output

Linux export PATH=$PATH:/usr/local/nodejs/bin

9
Node.js

Mac export PATH=$PATH:/usr/local/nodejs/bin

FreeBSD export PATH=$PATH:/usr/local/nodejs/bin

Installation on Windows
Use the MSI file and follow the prompts to install Node.js. By default, the installer uses the
Node.js distribution in C:\Program Files\nodejs. The installer should set the C:\Program
Files\nodejs\bin directory in Window's PATH environment variable. Restart any open
command prompts for the change to take effect.

Verify Installation: Executing a File


Create a js file named main.js on your machine (Windows or Linux) having the following code.

/* Hello, World! program in node.js */


console.log("Hello, World!")

Now execute main.js using Node.js interpreter to see the result:

$ node main.js

If everything is fine with your installation, it should produce the following result:

Hello, World!

10
3. FIRST APPLICATION Node.js

Before creating an actual "Hello, World!" application using Node.js, let us see the components
of a Node.js application. A Node.js application consists of the following three important
components:

1. Import required modules: We use the require directive to load Node.js modules.

2. Create server: A server which will listen to client's requests similar to Apache HTTP
Server.

3. Read request and return response: The server created in an earlier step will read
the HTTP request made by the client which can be a browser or a console and return
the response.

Creating Node.js Application

Step1 - ImportRequiredModule
We use the require directive to load the http module and store the returned HTTP instance
into an http variable as follows:

var http = require("http");

Step 2-Create Server


We use the created http instance and call http.createServer() method to create a server
instance and then we bind it at port 8081 using the listen method associated with the server
instance. Pass it a function with parameters request and response. Write the sample
implementation to always return "Hello World".

http.createServer(function (request, response) {

// Send the HTTP header


// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"

11
Node.js

response.end('Hello World\n');
}).listen(8081);

// Console will print the message


console.log('Server running at http://127.0.0.1:8081/');

The above code is enough to create an HTTP server which listens, i.e., waits for a request
over 8081 port on the local machine.

Step 3-Testing Request & Response


Let's put step 1 and 2 together in a file called main.js and start our HTTP server as shown
below:

var http = require("http");


http.createServer(function (request, response) {

// Send the HTTP header


// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});

// Send the response body as "Hello World"


response.end('Hello World\n');
}).listen(8081);

// Console will print the message


console.log('Server running at http://127.0.0.1:8081/');

Now execute the main.js to start the server as follows:

$ node main.js

Verify the Output. Server has started.

Server running at http://127.0.0.1:8081/

12
Node.js

Make a Requestto the Node.js Server


Open http://127.0.0.1:8081/ in any browser and observe the following result.

Congratulations, you have your first HTTP server up and running which is responding to all
the HTTP requests at port 8081.

13
4. REPL TERMINAL Node.js

REPL stands for Read Eval Print Loop and it represents a computer environment like a
Windows console or Unix/Linux shell where a command is entered and the system responds
with an output in an interactive mode. Node.js or Node comes bundled with a REPL
environment. It performs the following tasks:

● Read - Reads user's input, parses the input into JavaScript data-structure, and stores
in memory.

● Eval - Takes and evaluates the data structure.

● Print - Prints the result.

● Loop - Loops the above command until the user presses ctrl-c twice.

The REPL feature of Node is very useful in experimenting with Node.js codes and to debug
JavaScript codes.

Online REPL Terminal


To simplify your learning, we have set up an easy-to-use Node.js REPL environment online,
where you can practice Node.js syntax: Launch Node.js REPL Terminal

StartingREPL
REPL can be started by simply running node on shell/console without any arguments as
follows.

$ node

You will see the REPL Command prompt > where you can type any Node.js command:

$ node
>

Simple Expression
Let's try a simple mathematics at the Node.js REPL command prompt:

$ node
> 1 + 3

14
Node.js

4
> 1 + ( 2 * 3 ) - 4
3
>

UseVariables
You can make use variables to store values and print later like any conventional script. If var
keyword is not used, then the value is stored in the variable and printed. Whereas if var
keyword is used, then the value is stored but not printed. You can print variables using
console.log().

$ node
> x = 10
10
> var y = 10
undefined
> x + y
20
> console.log("Hello World")
Hello Workd
undefined

MultilineExpression
Node REPL supports multiline expression similar to JavaScript. Let's check the following do-
while loop in action:

$ node
> var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... } while ( x < 5 );
x: 1
x: 2
15
Node.js

x: 3
x: 4
x: 5
undefined
>

... comes automatically when you press Enter after the opening bracket. Node automatically
checks the continuity of expressions.

Underscore Variable
You can use underscore (_) to get the last result:

$ node
> var x = 10
undefined
> var y = 20
undefined
> x + y
30
> var sum = _
undefined
> console.log(sum)
30
undefined
>

REPL Commands
• ctrl + c - terminate the current command.
• ctrl + c twice - terminate the Node REPL.
• ctrl + d - terminate the Node REPL.
• Up/Down Keys - see command history and modify previous commands.
• tab Keys - list of current commands.
• .help - list of all commands.
• .break - exit from multiline expression.

16
Node.js

• .clear - exit from multiline expression.


• .save filename - save the current Node REPL session to a file.
• .load filename - load file content in current Node REPL session.

Stopping REPL
As mentioned above, you will need to use ctrl-c twice to come out of Node.js REPL.

$ node
>
(^C again to quit)
>

17
5. NPM Node.js

Node Package Manager (NPM) provides two main functionalities:

• Online repositories for node.js packages/modules which are searchable on


search.nodejs.org

• Command line utility to install Node.js packages, do version management and


dependency management of Node.js packages.

NPM comes bundled with Node.js installables after v0.6.3 version. To verify the same, open
console and type the following command and see the result:

$ npm --version
2.7.1

If you are running an old version of NPM, then it is quite easy to update it to the latest version.
Just use the following command from root:

$ sudo npm install npm -g


/usr/bin/npm -> /usr/lib/node_modules/npm/bin/npm-cli.js
[email protected] /usr/lib/node_modules/npm

Installing Modules using NPM


There is a simple syntax to install any Node.js module:

$ npm install <Module Name>

For example, following is the command to install a famous Node.js web framework module
called express:

$ npm install express

Now you can use this module in your js file as following:

var express = require('express');

18
Node.js

Global vs Local Installation


By default, NPM installs any dependency in the local mode. Here local mode refers to the
package installation in node_modules directory lying in the folder where Node application is
present. Locally deployed packages are accessible via require() method. For example, when
we installed express module, it created node_modules directory in the current directory where
it installed the express module.

$ ls -l
total 0
drwxr-xr-x 3 root root 20 Mar 17 02:23 node_modules

Alternatively, you can use npm ls command to list down all the locally installed modules.

Globally installed packages/dependencies are stored in system directory. Such dependencies


can be used in CLI (Command Line Interface) function of any node.js but cannot be imported
using require() in Node application directly. Now let's try installing the express module using
global installation.

$ npm install express -g

This will produce a similar result but the module will be installed globally. Here, the first line
shows the module version and the location where it is getting installed.

[email protected] /usr/lib/node_modules/express
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]

19
Node.js

├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
└── [email protected] ([email protected], [email protected])

You can use the following command to check all the modules installed globally:

$ npm ls -g

Using package.json
package.json is present in the root directory of any Node application/module and is used to
define the properties of a package. Let's open package.json of express package present in
node_modules/express/

{
"name": "express",
"description": "Fast, unopinionated, minimalist web framework",
"version": "4.11.2",
"author": {
"name": "TJ Holowaychuk",
"email": "[email protected]"
},
"contributors": [
{
"name": "Aaron Heckmann",
"email": "[email protected]"
},
{
"name": "Ciaran Jessup",
"email": "[email protected]"
20
Node.js

},
{
"name": "Douglas Christopher Wilson",
"email": "[email protected]"
},
{
"name": "Guillermo Rauch",
"email": "[email protected]"
},
{
"name": "Jonathan Ong",
"email": "[email protected]"
},
{
"name": "Roman Shtylman",
"email": "[email protected]"
},
{
"name": "Young Jae Sim",
"email": "[email protected]"
}
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/strongloop/express"
},
"homepage": "http://expressjs.com/",
"keywords": [
"express",
"framework",
"sinatra",
"web",
21
Node.js

"rest",
"restful",
"router",
"app",
"api"
],
"dependencies": {
"accepts": "~1.2.3",
"content-disposition": "0.5.0",
"cookie-signature": "1.0.5",
"debug": "~2.1.1",
"depd": "~1.0.0",
"escape-html": "1.0.1",
"etag": "~1.5.1",
"finalhandler": "0.3.3",
"fresh": "0.2.4",
"media-typer": "0.3.0",
"methods": "~1.1.1",
"on-finished": "~2.2.0",
"parseurl": "~1.3.0",
"path-to-regexp": "0.1.3",
"proxy-addr": "~1.0.6",
"qs": "2.3.3",
"range-parser": "~1.0.2",
"send": "0.11.1",
"serve-static": "~1.8.1",
"type-is": "~1.5.6",
"vary": "~1.0.0",
"cookie": "0.1.2",
"merge-descriptors": "0.0.2",
"utils-merge": "1.0.0"
},
"devDependencies": {
22
Node.js

"after": "0.8.1",
"ejs": "2.1.4",
"istanbul": "0.3.5",
"marked": "0.3.3",
"mocha": "~2.1.0",
"should": "~4.6.2",
"supertest": "~0.15.0",
"hjs": "~0.0.6",
"body-parser": "~1.11.0",
"connect-redis": "~2.2.0",
"cookie-parser": "~1.3.3",
"express-session": "~1.10.2",
"jade": "~1.9.1",
"method-override": "~2.3.1",
"morgan": "~1.5.1",
"multiparty": "~4.1.1",
"vhost": "~3.0.0"
},
"engines": {
"node": ">= 0.10.0"
},
"files": [
"LICENSE",
"History.md",
"Readme.md",
"index.js",
"lib/"
],
"scripts": {
"test": "mocha --require test/support/env --reporter spec --bail –
check-leaks test/ test/acceptance/",

"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --


23
Node.js

require test/support/env --reporter dot --check-leaks test/


test/acceptance/",

"test-tap": "mocha --require test/support/env --reporter tap –


check-leaks test/ test/acceptance/",

"test-travis": "istanbul cover node_modules/mocha/bin/_mocha –


report lcovonly -- --require test/support/env --reporter spec –
check-leaks test/ test/acceptance/"
},
"gitHead": "63ab25579bda70b4927a179b580a9c580b6c7ada",
"bugs": {
"url": "https://github.com/strongloop/express/issues"
},
"_id": "[email protected]",
"_shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"_from": "express@*",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "[email protected]"
},
"maintainers": [
{
"name": "tjholowaychuk",
"email": "[email protected]"
},
{
"name": "jongleberry",
"email": "[email protected]"
},
{
"name": "shtylman",
24
Node.js

"email": "[email protected]"
},
{
"name": "dougwilson",
"email": "[email protected]"
},
{
"name": "aredridel",
"email": "[email protected]"
},
{
"name": "strongloop",
"email": "[email protected]"
},
{
"name": "rfeng",
"email": "[email protected]"
}
],
"dist": {
"shasum": "8df3d5a9ac848585f00a0777601823faecd3b148",
"tarball": "http://registry.npmjs.org/express/-/express-4.11.2.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/express/-/express-4.11.2.tgz",
"readme": "ERROR: No README data found!"
}

Attributes of Package.json
• name - name of the package

• version - version of the package

• description - description of the package


25
Node.js

• homepage - homepage of the package

• author - author of the package

• contributors - name of the contributors to the package

• dependencies - list of dependencies. NPM automatically installs all the dependencies


mentioned here in the node_module folder of the package.

• repository - repository type and URL of the package

• main - entry point of the package

• keywords - keywords

Uninstalling a Module
Use the following command to uninstall a Node.js module.

$ npm uninstall express

Once NPM uninstalls the package, you can verify it by looking at the content of
/node_modules/ directory or type the following command:

$ npm ls

Updating a Module
Update package.json and change the version of the dependency to be updated and run the
following command.

$ npm update express

Search a Module
Search a package name using NPM.

$ npm search express

Create a Module
Creating a module requires package.json to be generated. Let's generate package.json using
NPM, which will generate the basic skeleton of the package.json.

26
Node.js

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See 'npm help json' for definitive documentation on these fields


and exactly what they do.

Use 'npm install <pkg> --save' afterwards to install a package and


save it as a dependency in the package.json file.

Press ^C at any time to quit.


name: (webmaster)

You will need to provide all the required information about your module. You can take help
from the above-mentioned package.json file to understand the meanings of various
information demanded. Once package.json is generated, use the following command to
register yourself with NPM repository site using a valid email address.

$ npm adduser
Username: mcmohd
Password:
Email: (this IS public) [email protected]

It is time now to publish your module:

$ npm publish

If everything is fine with your module, then it will be published in the repository and will be
accessible to install using NPM like any other Node.js module.

27
6. CALLBACK CONCEPT Node.js

What is Callback?
Callback is an asynchronous equivalent for a function. A callback function is called at the
completion of a given task. Node makes heavy use of callbacks. All the APIs of Node are
written in such a way that they support callbacks.

For example, a function to read a file may start reading a file and return the control to the
execution environment immediately so that the next instruction can be executed. Once file
I/O is complete, it will call the callback function while passing the callback function, the
content of the file as a parameter. So there is no blocking or wait for File I/O. This makes
Node.js highly scalable, as it can process a high number of requests without waiting for any
function to return results.

Blocking Code Example


Create a text file named input.txt with the following content:

Tutorials Point is giving self learning content


to teach the world in simple and easy way!!!!!

Create a js file named main.js with the following code:

var fs = require("fs");

var data = fs.readFileSync('input.txt');

console.log(data.toString());
console.log("Program Ended");

Now run the main.js to see the result:

$ node main.js

Verify the Output.

Tutorials Point is giving self learning content

28
Node.js

to teach the world in simple and easy way!!!!!


Program Ended

Non-Blocking Code Example


Create a text file named input.txt with the following content.

Tutorials Point is giving self learning content


to teach the world in simple and easy way!!!!!

Update main.js to have the following code:

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {


if (err) return console.error(err);
console.log(data.toString());
});

console.log("Program Ended");

Now run the main.js to see the result:

$ node main.js

Verify the Output.

Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

These two examples explain the concept of blocking and non-blocking calls.

• The first example shows that the program blocks until it reads the file and then only it
proceeds to end the program.

• The second example shows that the program does not wait for file reading and
proceeds to print "Program Ended" and at the same time, the program without blocking
continues reading the file.

29
Node.js

Thus, a blocking program executes very much in sequence. From the programming point of
view, it is easier to implement the logic but non-blocking programs do not execute in
sequence. In case a program needs to use any data to be processed, it should be kept within
the same block to make it sequential execution.

30
7. EVENT LOOP Node.js

Node.js is a single-threaded application, but it can support concurrency via the concept of
event and callbacks. Every API of Node.js is asynchronous and being single-threaded, they
use async function calls to maintain concurrency. Node uses observer pattern. Node thread
keeps an event loop and whenever a task gets completed, it fires the corresponding event
which signals the event-listener function to execute.

Event-Driven Programming
Node.js uses events heavily and it is also one of the reasons why Node.js is pretty fast
compared to other similar technologies. As soon as Node starts its server, it simply initiates
its variables, declares functions, and then simply waits for the event to occur.

In an event-driven application, there is generally a main loop that listens for events, and then
triggers a callback function when one of those events is detected.

Although events look quite similar to callbacks, the difference lies in the fact that callback
functions are called when an asynchronous function returns its result, whereas event handling
works on the observer pattern. The functions that listen to events act as Observers.
Whenever an event gets fired, its listener function starts executing. Node.js has multiple in-
built events available through events module and EventEmitter class which are used to bind
events and event-listeners as follows:

// Import events module


var events = require('events');
// Create an eventEmitter object

31
Node.js

var eventEmitter = new events.EventEmitter();

Following is the syntax to bind an event handler with an event:

// Bind event and even handler as follows


eventEmitter.on('eventName', eventHandler);

We can fire an event programmatically as follows:

// Fire an event
eventEmitter.emit('eventName');

Example
Create a js file named main.js with the following code:

// Import events module


var events = require('events');

// Create an eventEmitter object


var eventEmitter = new events.EventEmitter();

// Create an event handler as follows


var connectHandler = function connected() {
console.log('connection successful.');

// Fire the data_received event


eventEmitter.emit('data_received');
}

// Bind the connection event with the handler


eventEmitter.on('connection', connectHandler);

32
Node.js

// Bind the data_received event with the anonymous function


eventEmitter.on('data_received', function(){
console.log('data received successfully.');
});

// Fire the connection event


eventEmitter.emit('connection');

console.log("Program Ended.");

Now let's try to run the above program and check its output:

$ mnode main.js

It should produce the following result:

connection successful.
data received successfully.
Program Ended.

How Node Applications Work?


In Node Application, any async function accepts a callback as the last parameter and a
callback function accepts an error as the first parameter. Let's revisit the previous example
again. Create a text file named input.txt with the following content.

Tutorials Point is giving self learning content


to teach the world in simple and easy way!!!!!

Create a js file named main.js having the following code:

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {


if (err){
console.log(err.stack);
return;

33
Node.js

}
console.log(data.toString());
});
console.log("Program Ended");

Here fs.readFile() is a async function whose purpose is to read a file. If an error occurs during
the read operation, then the err object will contain the corresponding error, else data will
contain the contents of the file. readFile passes err and data to the callback function after
the read operation is complete, which finally prints the content.

Program Ended
Tutorials Point is giving self learning content
to teach the world in simple and easy way!!!!!

34
8. EVENT EMITTER Node.js

Many objects in a Node emit events, for example, a net.Server emits an event each time a
peer connects to it, an fs.readStream emits an event when the file is opened. All objects which
emit events are the instances of events.EventEmitter.

EventEmitter Class
As we have seen in the previous section, EventEmitter class lies in the events module. It is
accessible via the following code:

// Import events module


var events = require('events');
// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

When an EventEmitter instance faces any error, it emits an 'error' event. When a new listener
is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event
is fired.

EventEmitter provides multiple properties like on and emit. on property is used to bind a
function with the event and emit is used to fire an event.

Methods
S.No. Method & Description

addListener(event, listener)
Adds a listener at the end of the listeners array for the specified event. No
1 checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added multiple times. Returns emitter, so calls can be chained.

on(event, listener)
Adds a listener at the end of the listeners array for the specified event. No
2 checks are made to see if the listener has already been added. Multiple calls
passing the same combination of event and listener will result in the listener
being added multiple times. Returns emitter, so calls can be chained.

3 once(event, listener)

35
Node.js

Adds a one-time listener to the event. This listener is invoked only the next time
the event is fired, after which it is removed. Returns emitter, so calls can be
chained.

removeListener(event, listener)

Removes a listener from the listener array for the specified event. Caution: It
4 changes the array indices in the listener array behind the listener. removeListener
will remove, at most, one instance of a listener from the listener array. If any single
listener has been added multiple times to the listener array for the specified event,
then removeListener must be called multiple times to remove each instance.
Returns emitter, so calls can be chained.
removeAllListeners([event])
Removes all listeners, or those of the specified event. It's not a good idea to
5 remove listeners that were added elsewhere in the code, especially when it's on
an emitter that you didn't create (e.g. sockets or file streams). Returns emitter,
so calls can be chained.

setMaxListeners(n)
By default, EventEmitters will print a warning if more than 10 listeners are added
6 for a particular event. This is a useful default which helps finding memory leaks.
Obviously not all Emitters should be limited to 10. This function allows that to be
increased. Set to zero for unlimited.

listeners(event)
7
Returns an array of listeners for the specified event.

emit(event, [arg1], [arg2], [...])


8 Execute each of the listeners in order with the supplied arguments. Returns true
if the event had listeners, false otherwise.

Class Methods
S.No. Method & Description

1 listenerCount(emitter, event)
Returns the number of listeners for a given event.

36
Node.js

Events
S. No. Events & Description

newListener

• event – String; the event name


1
• listener – Function; the event handler function

This event is emitted any time a listener is added. When this event is triggered,
the listener may not yet have been added to the array of listeners for the event.

removeListener

• event - String The event name

• listener - Function The event handler function


2

This event is emitted any time someone removes a listener. When this event is
triggered, the listener may not yet have been removed from the array of listeners
for the event.

Example
Create a js file named main.js with the following Node.js code:

var events = require('events');


var eventEmitter = new events.EventEmitter();

// listener #1
var listner1 = function listner1() {
console.log('listner1 executed.');
}
37
Node.js

// listener #2
var listner2 = function listner2() {
console.log('listner2 executed.');
}
// Bind the connection event with the listner1 function
eventEmitter.addListener('connection', listner1);
// Bind the connection event with the listner2 function
eventEmitter.on('connection', listner2);

var eventListeners =
require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");

// Fire the connection event


eventEmitter.emit('connection');

// Remove the binding of listner1 function


eventEmitter.removeListener('connection', listner1);
console.log("Listner1 will not listen now.");

// Fire the connection event


eventEmitter.emit('connection');

eventListeners =
require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");

console.log("Program Ended.");

Now run the main.js to see the result:

$ node main.js

Verify the Output.

38
Node.js

2 Listner(s) listening to connection event


listner1 executed.
listner2 executed.
Listner1 will not listen now.
listner2 executed.
1 Listner(s) listening to connection event
Program Ended.

39
MongoDB
1. MongoDB ─ Overview

MongoDB is a cross-platform, document oriented database that provides, high performance,


high availability, and easy scalability. MongoDB works on concept of collection and document.

Database
Database is a physical container for collections. Each database gets its own set of files on the
file system. A single MongoDB server typically has multiple databases.

Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents
within a collection can have different fields. Typically, all documents in a collection are of
similar or related purpose.

Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema
means that documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different types of data.

The following table shows the relationship of RDBMS terminology with MongoDB.

RDBMS MongoDB

Database Database

Table Collection

Tuple/Row Document

column Field

Table Join Embedded Documents

Primary Key (Default key _id provided by


Primary Key
mongodb itself)

Database Server and Client

Mysqld/Oracle mongod

5
MongoDB

mysql/sqlplus mongo

Sample Document
Following example shows the document structure of a blog site, which is simply a comma
separated key value pair.

{
_id: ObjectId(7df78ad8902c)
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2011,1,20,2,15),
like: 0
},
{
user:'user2',
message: 'My second comments',
dateCreated: new Date(2011,1,25,7,45),
like: 5
}
]
}

_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You
can provide _id while inserting the document. If you don’t provide then MongoDB provides a
unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3
bytes for machine id, next 2 bytes for process id of MongoDB server and remaining 3 bytes
are simple incremental VALUE.

6
MongoDB
2. MongoDB ─ Advantages

Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB, there is no concept of relationship.

Advantages of MongoDB over RDBMS


• Schema less: MongoDB is a document database in which one collection holds different
documents. Number of fields, content and size of the document can differ from one
document to another.

• Structure of a single object is clear.

• No complex joins.

• Deep query-ability. MongoDB supports dynamic queries on documents using a


document-based query language that's nearly as powerful as SQL.

• Tuning.

• Ease of scale-out: MongoDB is easy to scale.

• Conversion/mapping of application objects to database objects not needed.

• Uses internal memory for storing the (windowed) working set, enabling faster access
of data.

Why Use MongoDB?


• Document Oriented Storage: Data is stored in the form of JSON style documents.
• Index on any attribute
• Replication and high availability
• Auto-sharding
• Rich queries
• Fast in-place updates
• Professional support by MongoDB

Where to Use MongoDB?


• Big Data
• Content Management and Delivery
• Mobile and Social Infrastructure

7
MongoDB

• User Data Management


• Data Hub

8
MongoDB
3. MongoDB ─ Environment

Let us now see how to install MongoDB on Windows.

Install MongoDB on Windows


To install MongoDB on Windows, first download the latest release of MongoDB
from http://www.mongodb.org/downloads. Make sure you get correct version of MongoDB
depending upon your Windows version. To get your Windows version, open command prompt
and execute the following command.

C:\>wmic os get osarchitecture


OSArchitecture
64-bit
C:\>

32-bit versions of MongoDB only support databases smaller than 2GB and suitable only for
testing and evaluation purposes.

Now extract your downloaded file to c:\ drive or any other location. Make sure the name of
the extracted folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version].
Here [version] is the version of MongoDB download.

Next, open the command prompt and run the following command.

C:\>move mongodb-win64-* mongodb


1 dir(s) moved.
C:\>

In case you have extracted the MongoDB at different location, then go to that path by using
command cd FOOLDER/DIR and now run the above given process.

MongoDB requires a data folder to store its files. The default location for the MongoDB data
directory is c:\data\db. So you need to create this folder using the Command Prompt. Execute
the following command sequence.

C:\>md data
C:\md data\db

If you have to install the MongoDB at a different location, then you need to specify an alternate
path for \data\db by setting the path dbpath in mongod.exe. For the same, issue the
following commands.

9
MongoDB

In the command prompt, navigate to the bin directory present in the MongoDB installation
folder. Suppose my installation folder is D:\set up\mongodb

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"

This will show waiting for connections message on the console output, which indicates that
the mongod.exe process is running successfully.

Now to run the MongoDB, you need to open another command prompt and issue the following
command.

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>

This will show that MongoDB is installed and run successfully. Next time when you run
MongoDB, you need to issue only commands.

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data"


D:\set up\mongodb\bin>mongo.exe

Install MongoDB on Ubuntu


Run the following command to import the MongoDB public GPG key −

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

Create a /etc/apt/sources.list.d/mongodb.list file using the following command.

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen'


| sudo tee /etc/apt/sources.list.d/mongodb.list

Now issue the following command to update the repository −

sudo apt-get update

10
MongoDB

Next install the MongoDB by using the following command −

apt-get install mongodb-10gen=2.2.3

In the above installation, 2.2.3 is currently released MongoDB version. Make sure to install
the latest version always. Now MongoDB is installed successfully.

Start MongoDB
sudo service mongodb start

Stop MongoDB
sudo service mongodb stop

Restart MongoDB
sudo service mongodb restart

To use MongoDB run the following command.

mongo

This will connect you to running MongoDB instance.

MongoDB Help
To get a list of commands, type db.help() in MongoDB client. This will give you a list of
commands as shown in the following screenshot.

11
MongoDB

12
MongoDB

MongoDB Statistics
To get stats about MongoDB server, type the command db.stats() in MongoDB client. This
will show the database name, number of collection and documents in the database. Output
of the command is shown in the following screenshot.

13
MongoDB
4. MongoDB ─ Data Modelling

Data in MongoDB has a flexible schema.documents in the same collection. They do not need
to have the same set of fields or structure, and common fields in a collection’s documents
may hold different types of data.

Some considerations while designing Schema in MongoDB


• Design your schema according to user requirements.
• Combine objects into one document if you will use them together. Otherwise separate
them (but make sure there should not be need of joins).

• Duplicate the data (but limited) because disk space is cheap as compare to compute
time.

• Do joins while write, not on read.


• Optimize your schema for most frequent use cases.
• Do complex aggregation in the schema.

Example
Suppose a client needs a database design for his blog/website and see the differences
between RDBMS and MongoDB schema design. Website has the following requirements.

• Every post has the unique title, description and url.

• Every post can have one or more tags.

• Every post has the name of its publisher and total number of likes.

• Every post has comments given by users along with their name, message, data-time
and likes.

• On each post, there can be zero or more comments.

In RDBMS schema, design for above requirements will have minimum three tables.

14
MongoDB

While in MongoDB schema, design will have one collection post and the following structure:

{
_id: POST_ID
title: TITLE_OF_POST,
description: POST_DESCRIPTION,
by: POST_BY,
url: URL_OF_POST,
tags: [TAG1, TAG2, TAG3],
likes: TOTAL_LIKES,
comments: [
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
},
{
user:'COMMENT_BY',
message: TEXT,
dateCreated: DATE_TIME,
like: LIKES
}
]
}

15
MongoDB

So while showing the data, in RDBMS you need to join three tables and in MongoDB, data will
be shown from one collection only.

16
MongoDB
5. MongoDB ─ Create Database

In this chapter, we will see how to create a database in MongoDB.

The use Command


MongoDB use DATABASE_NAME is used to create database. The command will create a
new database if it doesn't exist, otherwise it will return the existing database.

Syntax
Basic syntax of use DATABASE statement is as follows:

use DATABASE_NAME

Example
If you want to create a database with name <mydb>, then use DATABASE statement would
be as follows:

>use mydb
switched to db mydb

To check your currently selected database, use the command db

>db
mydb

If you want to check your databases list, use the command show dbs.

>show dbs
local 0.78125GB
test 0.23012GB

Your created database (mydb) is not present in list. To display database, you need to insert
at least one document into it.

>db.movie.insert({"name":"tutorials point"})
>show dbs
local 0.78125GB
mydb 0.23012GB

17
MongoDB

test 0.23012GB

In MongoDB default database is test. If you didn't create any database, then collections will
be stored in test database.

18
MongoDB
6. MongoDB ─ Drop Database

In this chapter, we will see how to drop a database using MongoDB command.

The dropDatabase() Method


MongoDB db.dropDatabase() command is used to drop a existing database.

Syntax
Basic syntax of dropDatabase() command is as follows:

db.dropDatabase()

This will delete the selected database. If you have not selected any database, then it will
delete default 'test' database.

Example
First, check the list of available databases by using the command, show dbs.

>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>

If you want to delete new database <mydb>, then dropDatabase() command would be as
follows:

>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>

Now check list of databases.

>show dbs
local 0.78125GB
test 0.23012GB>

19
MongoDB
7. MongoDB ─ Create Collection

In this chapter, we will see how to create a collection using MongoDB.

The createCollection() Method


MongoDB db.createCollection(name, options) is used to create collection.

Syntax
Basic syntax of createCollection() command is as follows:

db.createCollection(name, options)

In the command, name is name of collection to be created. Options is a document and is


used to specify configuration of collection.

Parameter Type Description

Name String Name of the collection to be created

(Optional) Specify options about memory


Options Document
size and indexing

Options parameter is optional, so you need to specify only the name of the collection.
Following is the list of options you can use:

Field Type Description

(Optional) If true, enables a capped collection. Capped


collection is a fixed size collection that automatically
capped Boolean overwrites its oldest entries when it reaches its maximum
size. If you specify true, you need to specify size
parameter also.

(Optional) If true, automatically create index on _id field.


autoIndexID Boolean
Default value is false.

(Optional) Specifies a maximum size in bytes for a capped


size number collection. If capped is true, then you need to specify
this field also.

20
MongoDB

(Optional) Specifies the maximum number of documents


max number
allowed in the capped collection.

While inserting the document, MongoDB first checks size field of capped collection, then it
checks max field.

Examples
Basic syntax of createCollection() method without options is as follows:

>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>

You can check the created collection by using the command show collections.

>show collections
mycollection
system.indexes

The following example shows the syntax of createCollection() method with few important
options:

>db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800,


max : 10000 } )
{ "ok" : 1 }
>

In MongoDB, you don't need to create collection. MongoDB creates collection automatically,
when you insert some document.

>db.tutorialspoint.insert({"name" : "tutorialspoint"})
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

21
Java Servlets
Servlets – Overview

What are Servlets?


Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a requests coming from a Web browser or other HTTP client and
databases or applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in comparison
with the CGI.

• Performance is significantly better.

• Servlets execute within the address space of a Web server. It is not necessary to
create a separate process to handle each client request.

• Servlets are platform-independent because they are written in Java.

• Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.

• The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.

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

1
Java Servlets

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.

Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports
the Java Servlet specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages,


which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of writing
this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After you
install the servlet packages and add them to your computer's Classpath, you can compile
servlets with the JDK's Java compiler or any other current compiler.

What is Next?
I would take you step by step to set up your environment to start with Servlets. So
fasten your belt for a nice drive with Servlets. I'm sure you are going to enjoy this
tutorial very much.

2
Java Servlets
Servlets – Environment Setup

A development environment is where you would develop your Servlet, test them and
finally run them.

Like any other Java program, you need to compile a servlet by using the Java compiler
javac and after compilation the servlet application, it would be deployed in a configured
environment to test and run.

This development environment setup involves the following steps:

Setting up Java Development Kit


This step involves downloading an implementation of the Java Software Development Kit
(SDK) and setting up PATH environment variable appropriately.

You can download SDK from Oracle's Java site: Java SE Downloads.

Once you download your Java implementation, follow the given instructions to install and
configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to
the directory that contains java and javac, typically java_install_dir/bin and
java_install_dir respectively.

If you are running Windows and installed the SDK in C:\jdk1.8.0_65, you would put the
following line in your C:\autoexec.bat file.

set PATH=C:\jdk1.8.0_65\bin;%PATH%
set JAVA_HOME=C:\jdk1.8.0_65

Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select


Properties, then Advanced, then Environment Variables. Then, you would update the
PATH value and press the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.8.0_65 and you
use the C shell, you would put the following into your .cshrc file.

setenv PATH /usr/local/jdk1.8.0_65/bin:$PATH


setenv JAVA_HOME /usr/local/jdk1.8.0_65

Alternatively, if you use an Integrated Development Environment (IDE) like Borland


JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to
confirm that the IDE knows where you installed Java.

Setting up Web Server: Tomcat


A number of Web Servers that support servlets are available in the market. Some web
servers are freely downloadable and Tomcat is one of them.

3
Java Servlets

Apache Tomcat is an open source software implementation of the Java Servlet and Java
Server Pages technologies and can act as a standalone server for testing servlets and
can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on
your machine:

• Download latest version of Tomcat from http://tomcat.apache.org/.

• Once you downloaded the installation, unpack the binary distribution into a
convenient location. For example in C:\apache-tomcat-8.0.28 on windows, or
/usr/local/apache-tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME
environment variable pointing to these locations.

Tomcat can be started by executing the following commands on windows machine:

%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-8.0.28\bin\startup.bat

Tomcat can be started by executing the following commands on Unix (Solaris, Linux,
etc.) machine:

$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-8.0.28/bin/startup.sh

After startup, the default web applications included with Tomcat will be available by
visiting http://localhost:8080/. If everything is fine then it should display following
result:

4
Java Servlets

Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site:
http://tomcat.apache.org

Tomcat can be stopped by executing the following commands on windows machine:

C:\apache-tomcat-8.0.28\bin\shutdown

Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux,
etc.) machine:

/usr/local/apache-tomcat-8.0.28/bin/shutdown.sh

Setting Up the CLASSPATH


Since servlets are not part of the Java Platform, Standard Edition, you must identify the
servlet classes to the compiler.

If you are running Windows, you need to put the following lines in your C:\autoexec.bat
file.

set CATALINA=C:\apache-tomcat-8.0.28
set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%

Alternatively, on Windows NT/2000/XP, you could go to My Computer -> Properties ->


Advanced -> Environment Variables. Then, you would update the CLASSPATH value and
press the OK button.

On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following
lines into your .cshrc file.

setenv CATALINA=/usr/local/apache-tomcat-8.0.28

5
Java Servlets

setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH

NOTE: Assuming that your development directory is C:\ServletDevel (Windows) or


/usr/ServletDevel (Unix) then you would need to add these directories as well in
CLASSPATH in similar way as you have added above.

6
Java Servlets
Servlets – Life Cycle

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.

Now let us discuss the life cycle methods in detail.

The init() Method


The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as
with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.

When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {


// Initialization code...
}

The service() Method


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.

7
Java Servlets

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.

The doGet() and doPost() are most frequently used methods with in each service
request. Here is the signature of these two methods.

The doGet() Method


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.

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() Method


The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities.

8
Java Servlets

After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this:

public void destroy() {


// Finalization code...
}

Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.

• First the HTTP requests coming to the server are delegated to the servlet
container.

• The servlet container loads the servlet before invoking the service() method.

• Then the servlet container handles multiple requests by spawning multiple


threads, each thread executing the service() method of a single instance of the
servlet.

9
JSP ─ OVERVIEW JSP

What is JavaServer Pages?


JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special JSP
tags, most of which start with <% and end with %>.

A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of
a user interface for a Java web application. Web developers write JSPs as text files that
combine HTML or XHTML code, XML elements, and embedded JSP actions and commands.

Using JSP, you can collect input from users through Webpage forms, present records from a
database or another source, and create Webpages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a database
or registering user preferences, accessing JavaBeans components, passing control between
pages, and sharing information between requests, pages etc.

Why Use JSP?


JavaServer Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But JSP offers several advantages in comparison with
the CGI.

• Performance is significantly better because JSP allows embedding Dynamic Elements


in HTML Pages itself instead of having separate CGI files.

• JSP are always compiled before they are 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.

Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications.
This means that JSP can play a part in the simplest applications to the most complex and
demanding.

11
JSP

Advantages of JSP
Following is the list of other advantages of using JSP over other technologies:

vs. Active Server Pages (ASP)


The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic
or other MS specific language, so it is more powerful and easier to use. Second, it is portable
to other operating systems and non-Microsoft Web servers.

vs. Pure Servlets


It is more convenient to write (and to modify!) regular HTML than to have plenty of println
statements that generate the HTML.

vs. Server-Side Includes (SSI)


SSI is really only intended for simple inclusions, not for "real" programs that use form data,
make database connections, and the like.

vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly interact with the web
server to perform complex tasks like database access and image processing etc.

vs. Static HTML


Regular HTML, of course, cannot contain dynamic information.

What is Next?
I would take you step by step to set up your environment to start with JSP. I'm assuming you
have good hands-on with Java Programming to proceed with learning JSP.

If you are not aware of Java Programming Language, then we would recommend you go
through our Java Tutorial to understand Java Programming.

12
JSP ─ ENVIRONMENT SETUP JSP

A development environment is where you would develop your JSP programs, test them and
finally run them.

This tutorial will guide you to setup your JSP development environment which involves the
following steps:

Setting up Java Development Kit


This step involves downloading an implementation of the Java Software Development Kit
(SDK) and setting up the PATH environment variable appropriately.

You can download SDK from Oracle's Java site: Java SE Downloads.

Once you download your Java implementation, follow the given instructions to install and
configure the setup. Finally set the PATH and JAVA_HOME environment variables to refer
to the directory that contains java and javac, typically java_install_dir/bin and
java_install_dir respectively.

If you are running Windows and install the SDK in C:\jdk1.5.0_20, you need to add the
following line in your C:\autoexec.bat file.

set PATH=C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME=C:\jdk1.5.0_20

Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select


Properties, then Advanced, followed by Environment Variables. Then, you would update
the PATH value and press the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use
the C shell, you will put the following into your .cshrc file.

setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH


setenv JAVA_HOME /usr/local/jdk1.5.0_20

Alternatively, if you use an Integrated Development Environment (IDE) like Borland


JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program
to confirm that the IDE knows where you installed Java.

13
JSP

Setting up Web Server: Tomcat


A number of Web Servers that support JavaServer Pages and Servlets development are
available in the market. Some web servers can be downloaded for free and Tomcat is one of
them.

Apache Tomcat is an open source software implementation of the JavaServer Pages and
Servlet technologies and can act as a standalone server for testing JSP and Servlets, and can
be integrated with the Apache Web Server. Here are the steps to set up Tomcat on your
machine:

• Download the latest version of Tomcat from http://tomcat.apache.org/.

• Once you downloaded the installation, unpack the binary distribution into a convenient
location. For example, in C:\apache-tomcat-5.5.29 on windows, or
/usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME
environment variable pointing to these locations.

Tomcat can be started by executing the following commands on the Windows machine:

%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-5.5.29\bin\startup.bat

Tomcat can be started by executing the following commands on the Unix (Solaris, Linux, etc.)
machine:

$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-5.5.29/bin/startup.sh

After a successful startup, the default web-applications included with Tomcat will be available
by visiting http://localhost:8080/.

14
JSP

Upon execution, you will receive the following output:

Further information about configuring and running Tomcat can be found in the documentation
included here, as well as on the Tomcat web site: http://tomcat.apache.org

Tomcat can be stopped by executing the following commands on the Windows machine:

%CATALINA_HOME%\bin\shutdown
or

C:\apache-tomcat-5.5.29\bin\shutdown

Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine:

$CATALINA_HOME/bin/shutdown.sh

or

15
JSP

/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh

Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the
servlet classes to the compiler.

If you are running Windows, you need to put the following lines in your C:\autoexec.bat
file.

set CATALINA=C:\apache-tomcat-5.5.29
set CLASSPATH=%CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%

Alternatively, on Windows NT/2000/XP, you can also right-click on My Computer, select


Properties, then Advanced, then Environment Variables. Then, you would update the
CLASSPATH value and press the OK button.

On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines
into your .cshrc file.

setenv CATALINA=/usr/local/apache-tomcat-5.5.29
setenv CLASSPATH $CATALINA/common/lib/jsp-api.jar:$CLASSPATH

NOTE: Assuming that your development directory is C:\JSPDev (Windows) or


/usr/JSPDev (Unix), then you would need to add these directories as well in CLASSPATH.

16
JSP ─ ARCHITECTURE JSP

The web server needs a JSP engine, i.e., a container to process JSP pages. The JSP container
is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which
has built-in JSP container to support JSP pages development.

A JSP container works with the Web server to provide the runtime environment and other
services a JSP needs. It knows how to understand the special elements that are part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web application.

JSP Processing
The following steps explain how the web server creates the Webpage using JSP:

• As with a normal page, your browser sends an HTTP request to the web server.

• The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.

• The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code. This code implements
the corresponding dynamic behavior of the page.

• The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.

17
JSP

• A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format. This output is
further passed on to the web server by the servlet engine inside an HTTP response.

• The web server forwards the HTTP response to your browser in terms of static HTML
content.

• Finally, the web browser handles the dynamically-generated HTML page inside the
HTTP response exactly as if it were a static page.

All the above mentioned steps can be seen in the following diagram:

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and
whether the modification date on the JSP is older than the servlet. If the JSP is older than its
generated servlet, the JSP container assumes that the JSP hasn't changed and that the
generated servlet still matches the JSP's contents. This makes the process more efficient than
with the other scripting languages (such as PHP) and therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having to be a
Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a
regular servlet

18
JSP ─ LIFECYCLE JSP

In this chapter, we will discuss the lifecycle of JSP. The key to understanding the low-level
functionality of JSP is to understand the simple life cycle they follow.

A JSP life cycle is defined as the process from its creation till the destruction. This is similar
to a servlet life cycle with an additional step which is required to compile a JSP into servlet.

Paths Followed By JSP


The following are the paths followed by a JSP

• Compilation

• Initialization

• Execution

• Cleanup

The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle. The four
phases have been described below:

19
JSP

JSP 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:

• Parsing the JSP.

• Turning the JSP into a servlet.

• Compiling the servlet.

JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any requests.
If you need to perform JSP-specific initialization, override the jspInit() method:

public void jspInit(){


// Initialization code...
}

Typically, initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the jspInit
method.

JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.

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 takes an HttpServletRequest and an HttpServletResponse as


its parameters as follows:

void _jspService(HttpServletRequest request,


HttpServletResponse response)
{
// Service handling code...
}

20
JSP

The _jspService() method of a JSP is invoked on request basis. This 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, i.e., GET, POST, DELETE, etc.

JSP 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. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections
or closing open files.

The jspDestroy() method has the following form:

public void jspDestroy()


{
// Your cleanup code goes here.
}

21
JSP ─ SYNTAX JSP

In this chapter, we will discuss Syntax in JSP. We will understand the basic use of simple
syntax (i.e., elements) involved with JSP development.

Elements of JSP
The elements of JSP have been described below:

The Scriptlet
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 %>

You can write the XML equivalent of the above syntax as follows:

<jsp:scriptlet>
code fragment
</jsp:scriptlet>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the
simple and first example for JSP:

<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

22
JSP

NOTE: Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your


environment is setup as per environment setup tutorial.

Let us keep the above code in JSP file hello.jsp and put this file in C:\apache-tomcat-
7.0.2\webapps\ROOT directory. Browse through the same using URL
http://localhost:8080/hello.jsp. This would generate the following result:

JSP Declarations
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.

Following is the syntax for JSP Declarations:

<%! declaration; [ declaration; ]+ ... %>

You can write the XML equivalent of the above syntax as follows:

<jsp:declaration>
code fragment
</jsp:declaration>

Following is an example for JSP Declarations:

<%! int i = 0; %>


<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

JSP Expression
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.

23
JSP

Because the value of an expression is converted to a String, you can use an expression within
a line of text, whether or not it is tagged with HTML, in a 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.

Following is the syntax of JSP Expression:

<%= expression %>

You can write the XML equivalent of the above syntax as follows:

<jsp:expression>
expression
</jsp:expression>

Following example shows a JSP Expression:

<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>

The above code will generate the following result:

JSP Comments
JSP comment marks the text or the statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out", a part of your JSP page.

24
JSP

Following is the syntax of the JSP comments:

<%-- This is JSP comment --%>

Following example shows the JSP Comments:

<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>

The above code will generate the following result:

There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially. Here's a summary:

Syntax Purpose

<%-- comment --%> A JSP comment. Ignored by the JSP engine.

<!-- comment --> An HTML comment. Ignored by the browser.

<\% Represents static <% literal.

%\> Represents static %> literal.

\' A single quote in an attribute that uses single quotes.

\" A double quote in an attribute that uses double quotes.

25
JSP

JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the following
form:

<%@ directive attribute="value" %>

There are three types of directive tag:

Directive Description

Defines page-dependent attributes, such as scripting


<%@ page ... %>
language, error page, and buffering requirements.

<%@ include ... %> Includes a file during the translation phase.

Declares a tag library, containing custom actions, used in the


<%@ taglib ... %>
page

We would explain the JSP directive in a separate chapter — JSP - Directives

JSP Actions
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.

There is only one syntax for the Action element, as it conforms to the XML standard:

<jsp:action_name attribute="value" />

Action elements are basically predefined functions. Following table lists out the available JSP
Actions:

Syntax Purpose

jsp:include Includes a file at the time the page is requested.

jsp:useBean Finds or instantiates a JavaBean.

26
JSP

jsp:setProperty Sets the property of a JavaBean.

jsp:getProperty Inserts the property of a JavaBean into the output.

jsp:forward Forwards the requester to a new page.

jsp:plugin Generates browser-specific code that makes an OBJECT or


EMBED tag for the Java plugin.

jsp:element Defines XML elements dynamically.

jsp:attribute Defines dynamically-defined XML element's attribute.

jsp:body Defines dynamically-defined XML element's body.

jsp:text Used to write template text in JSP pages and documents.

We would explain JSP actions in a separate chapter — JSP - Actions

27
JSP

JSP Implicit Objects


JSP supports nine automatically defined variables, which are also called implicit objects. These
variables are:

Objects Description

request This is the HttpServletRequest object associated with the


request.

response This is the HttpServletResponse object associated with the


response to the client.

out This is the PrintWriter object used to send output to the


client.

session This is the HttpSession object associated with the request.

application This is the ServletContext object associated with


application context.

config This is the ServletConfig object associated with the page.

pageContext This encapsulates use of server-specific features like higher


performance JspWriters.

page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.

Exception The Exception object allows the exception data to be


accessed by designated JSP.

28
JSP

We would explain JSP Implicit Objects in a separate chapter — JSP - Implicit Objects.

29
JSP

Control-Flow Statements
You can use all the APIs and building blocks of Java in your JSP programming including
decision-making statements, loops, etc.

Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line
with HTML text included between the Scriptlet tags.

<%! int day = 3; %>


<html>
<head><title>IF...ELSE Example</title></head>
<body>
<% if (day == 1 | day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body>
</html>

The above code will generate the following result:

Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside Scriptletas:

<%! int day = 3; %>


<html>
<head><title>SWITCH...CASE Example</title></head>
<body>
<%
switch(day) {
case 0:
out.println("It\'s Sunday.");
30
JSP

break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
}
%>
</body>
</html>

The above code will generate the following result:

Loop Statements
You can also use three basic types of looping blocks in Java: for, while,and do…while blocks
in your JSP programming.

Let us look at the following for loop example:

<%! int fontSize; %>


31
JSP

<html>
<head><title>FOR LOOP Example</title></head>

<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
<font color="green" size="<%= fontSize %>">
JSP Tutorial
</font><br />
<%}%>
</body>
</html>

The above code will generate the following result:

Above example can be written using the while loop as follows:

<%! int fontSize; %>


<html>
<head><title>WHILE LOOP Example</title></head>
<body>
<%while ( fontSize <= 3){ %>
<font color="green" size="<%= fontSize %>">
JSP Tutorial
32
JSP

</font><br />
<%fontSize++;%>
<%}%>
</body>
</html>

The above code will generate the following result:

JSP Operators
JSP supports all the logical and arithmetic operators supported by Java. Following table lists
out all the operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom.

Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >> >>> << Left to right

33
JSP

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= Right to left


<<= &= ^= |=

Comma , Left to right

JSP Literals
The JSP expression language defines the following literals:

• Boolean: true and false

• Integer: as in Java

• Floating point: as in Java

• String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is
escaped as \\.

• Null: null

34
JSP ─ DIRECTIVES JSP

In this chapter, we will discuss Directives in JSP. These directives provide directions and
instructions to the container, telling it how to handle certain aspects of the JSP processing.

A JSP directive affects the overall structure of the servlet class. It usually has the following
form:

<%@ directive attribute="value" %>

Directives can have a number of attributes which you can list down as key-value pairs and
separated by commas.

The blanks between the @ symbol and the directive name, and between the last attribute and
the closing %>, are optional.

There are three types of directive tag:

Directive Description

<%@ 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

The page Directive


The page directive is used to provide instructions to the container. These instructions pertain
to the current JSP page. You may code page directives anywhere in your JSP page. By
convention, page directives are coded at the top of the JSP page.

Following is the basic syntax of the page directive:

<%@ page attribute="value" %>

You can write the XML equivalent of the above syntax as follows:

35
JSP

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

Attributes
Following table lists out the attributes associated with page directive:

Attribute Purpose

buffer Specifies a buffering model for the output stream.

autoFlush Controls the behavior of the servlet output buffer.

contentType Defines the character encoding scheme.

Defines the URL of another JSP that reports on Java


errorPage
unchecked runtime exceptions.

Indicates if this JSP page is a URL specified by another JSP


isErrorPage
page's errorPage attribute.

Specifies a superclass that the generated servlet must


extends
extend.

Specifies a list of packages or classes for use in the JSP as


import
the Java import statement does for Java classes.

Defines a string that can be accessed with the servlet's


info
getServletInfo() method.

isThreadSafe Defines the threading model for the generated servlet.

language Defines the programming language used in the JSP page.

Specifies whether or not the JSP page participates in HTTP


session
sessions

36
JSP

Specifies whether or not the EL expression within the JSP


isELIgnored
page will be ignored.

isScriptingEnabled Determines if the scripting elements are allowed for use.

Check for more details related to all the above attributes at Page Directive.

JSP - The page Directive


The page directive is used to provide instructions to the container that pertain to the current
JSP page. You may code the page directives anywhere in your JSP page. By convention, page
directives are coded at the top of the JSP page.

Following is the basic syntax of page directive:

<%@ page attribute="value" %>

You can write the XML equivalent of the above syntax as follows:

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

Attributes
Following table lists out the attributes associated with the page directive:

Attribute Purpose

buffer Specifies a buffering model for the output stream.

autoFlush Controls the behavior of the servlet output buffer.

contentType Defines the character encoding scheme.

errorPage Defines the URL of another JSP that reports on Java


unchecked runtime exceptions.

isErrorPage Indicates if this JSP page is a URL specified by another JSP


page's errorPage attribute.

37
JSP

extends Specifies a superclass that the generated servlet must


extend.

import Specifies a list of packages or classes for use in the JSP as


the Java import statement does for Java classes.

info Defines a string that can be accessed with the servlet's


getServletInfo() method.

isThreadSafe Defines the threading model for the generated servlet.

language Defines the programming language used in the JSP page.

session Specifies whether or not the JSP page participates in HTTP


sessions.

isELIgnored Specifies whether or not the EL expression within the JSP


page will be ignored.

isScriptingEnabled Determines if the scripting elements are allowed for use.

The buffer Attribute


The buffer attribute specifies the buffering characteristics for the server output response
object.

You may code a value of "none" to specify no buffering so that the servlet output is
immediately directed to the response object or you may code a maximum buffer size in
kilobytes, which directs the servlet to write to the buffer before writing to the response object.

To direct the servlet to write the output directly to the response output object, use the
following:

<%@ page buffer="none" %>

Use the following to direct the servlet to write the output to a buffer of size not less than 8
kilobytes:

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

The autoFlush Attribute


38
JSP

The autoFlush attribute specifies whether buffered output should be flushed automatically
when the buffer is filled, or whether an exception should be raised to indicate the buffer
overflow.

A value of true (default) indicates automatic buffer flushing and a value of false throws an
exception.

The following directive causes the servlet to throw an exception when the servlet's output
buffer is full:

<%@ page autoFlush="false" %>

This directive causes the servlet to flush the output buffer when full:

<%@ page autoFlush="true" %>

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

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

The contentType Attribute


The contentType attribute sets the character encoding for the JSP page and for the generated
response page. The default content type is text/html, which is the standard content type for
HTML pages.

If you want to write out XML from your JSP, use the following page directive:

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

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

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

The following directive sets the content type as a Microsoft Word document:

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

You can also specify the character encoding for the response. For example, if you wanted to
specify that the resulting page that is returned to the browser uses ISO Latin 1, you can use
the following page directive:

39
JSP

<%@ page contentType="text/html:charset=ISO-8859-1" %>

The errorPage Attribute


The errorPage attribute tells the JSP engine which page to display if there is an error while
the current page runs. The value of the errorPage attribute is a relative URL.

The following directive displays MyErrorPage.jsp when all uncaught exceptions are thrown:

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

The isErrorPage Attribute


The isErrorPage attribute indicates that the current JSP can be used as the error page for
another JSP.

The value of isErrorPage is either true or false. The default value of the isErrorPage attribute
is false.

For example, the handleError.jsp sets the isErrorPage option to true because it is supposed
to handle errors:

<%@ page isErrorPage="true" %>

The extends Attribute


The extends attribute specifies a superclass that the generated servlet must extend.

For example, the following directive directs the JSP translator to generate the servlet such
that the servlet extends somePackage.SomeClass:

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

The import Attribute


The import attribute serves the same function as, and behaves like, the Java import
statement. The value for the import option is the name of the package you want to import.

To import java.sql.*, use the following page directive:

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

To import multiple packages, you can specify them separated by comma as follows:

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

40
JSP

By default, a container automatically imports java.lang.*, javax.servlet.*,


javax.servlet.jsp.*, and javax.servlet.http.*.

The info Attribute


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

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

The isThreadSafe Attribute


The isThreadSafe option marks a page as being thread-safe. By default, all JSPs are
considered thread-safe. If you set the isThreadSafe option to false, the JSP engine makes
sure that only one thread at a time is executing your JSP.

The following page directive sets the isThreadSafe option to false:

<%@ page isThreadSafe="false" %>

The language Attribute


The language attribute indicates the programming language used in scripting the JSP page.

For example, because you usually use Java as the scripting language, your language option
looks like this:

<%@ page language="java" %>

The session Attribute


The session attribute indicates whether or not the JSP page uses HTTP sessions. A value of
true means that the JSP page has access to a builtin session object and a value of false
means that the JSP page cannot access the builtin session object.

Following directive allows the JSP page to use any of the builtin object session methods such
as session.getCreationTime() or session.getLastAccessTime():

<%@ page session="true" %>

The isELIgnored Attribute


The isELIgnored attribute gives you the ability to disable the evaluation of Expression
Language (EL) expressions which has been introduced in JSP 2.0.

The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as
dictated by the JSP specification. If the attribute is set to false, then expressions are not
evaluated but rather treated as static text.
41
JSP

Following directive sets an expression not to be evaluated:

<%@ page isELIgnored="false" %>

The isScriptingEnabled Attribute


The isScriptingEnabled attribute determines if the scripting elements are allowed for use.

The default value (true) enables scriptlets, expressions, and declarations. If the attribute's
value is set to false, a translation-time error will be raised if the JSP uses any scriptlets,
expressions (non-EL), or declarations.

The attribute’s value can be set to false if you want to restrict the usage of scriptlets,
expressions (non-EL), or declarations:

<%@ page isScriptingEnabled="false" %>

The include Directive


The include directive is used to include a file during the translation phase. This directive tells
the container to merge the content of other external files with the current JSP during the
translation phase. You may code the include directives anywhere in your JSP page.

The general usage form of this directive is as follows:

<%@ include file="relative url" >

The filename in the include directive is actually a relative URL. If you just specify a filename
with no associated path, the JSP compiler assumes that the file is in the same directory as
your JSP.

You can write the XML equivalent of the above syntax as follows:

<jsp:directive.include file="relative url" />

For more details related to include directive, check the Include Directive.

JSP - Include Directive


The include directive is used to include a file during the translation phase. This directive tells
the container to merge the content of other external files with the current JSP during the
translation phase. You may code include directives anywhere in your JSP page.

The general usage form of this directive is as follows:

<%@ include file="relative url" >

42
JSP

The filename in the include directive is actually a relative URL. If you just specify a filename
with no associated path, the JSP compiler assumes that the file is in the same directory as
your JSP.

You can write the XML equivalent of the above syntax as follows:

<jsp:directive.include file="relative url" />

Example
A good example of the include directive is including a common header and footer with
multiple pages of content.

Let us define following three files (a) header.jps, (b)footer.jsp, and (c)main.jsp as
follows:

Following is the content of header.jsp:

<%!
int pageCount = 0;
void addCount() {
pageCount++;
}
%>
<% addCount(); %>
<html>
<head>
<title>The include Directive Example</title>
</head>
<body>
<center>
<h2>The include Directive Example</h2>
<p>This site has been visited <%= pageCount %> times.</p>
</center>
<br/><br/>

Following is the content of footer.jsp:

<%@ include file="header.jsp" %>


<center>

43
JSP

<p>Thanks for visiting my page.</p>


</center>
<%@ include file="footer.jsp" %>

Let us now keep all these files in the root directory and try to access main.jsp. You will
receive the following output:

Refresh main.jsp and you will find that the page hit counter keeps increasing.

You can design your webpages based on your creative instincts; it is recommended you keep
the dynamic parts of your website in separate files and then include them in the main file.
This makes it easy when you need to change a part of your webpage.

The taglib Directive


The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML
tags and a tag library is a set of user-defined tags that implement custom behavior.

44
JSP

The taglib directive declares that your JSP page uses a set of custom tags, identifies the
location of the library, and provides means for identifying the custom tags in your JSP page.

The taglib directive follows the syntax given below:

<%@ taglib uri="uri" prefix="prefixOfTag" >

Here, the uri attribute value resolves to a location the container understands and
the prefix attribute informs a container what bits of markup are custom actions.

You can write the XML equivalent of the above syntax as follows:

<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />

For more details related to the taglib directive, check the Taglib Directive.

JSP - The taglib Directive


The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML
tags and a tag library is a set of user-defined tags that implement custom behavior.

The taglib directive declares that your JSP page uses a set of custom tags, identifies the
location of the library, and provides a means for identifying the custom tags in your JSP page.

The taglib directive follows the syntax given below:

<%@ taglib uri="uri" prefix="prefixOfTag" >

Where the uri attribute value resolves to a location the container understands and
the prefix attribute informs a container what bits of markup are custom actions.

You can write the XML equivalent of the above syntax as follows:

<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />

When you use a custom tag, it is typically of the form <prefix:tagname>. The prefix is the
same as the prefix you specify in the taglib directive, and the tagname is the name of a tag
implemented in the tag library.

Example
For example, suppose the custlib tag library contains a tag called hello. If you wanted to
use the hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be
used in your JSP file as follows:

<%@ taglib uri="http://www.example.com/custlib" prefix="mytag" %>


<html>

45
JSP

<body>
<mytag:hello/>
</body>
</html>

We can call another piece of code using <mytag:hello>. We will see how to develop our
custom tags and how to use them in JSP - Custom Tags tutorial.

46

You might also like