WT All Unit Notes zccurate
WT All Unit Notes zccurate
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.
<!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.
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.
17
HTML
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.
<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.
<!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>
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>
20
HTML
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>
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
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
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>
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:
In cases, where you do not want the client browser to break text, you should use a
nonbreaking space entity 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 Angry 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:
<br />
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.
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.
Example
25
HTML
<head>
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>
27
HTML
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 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
The value of the attribute may also be a space-separated list of class names. For example:
<!DOCTYPE html>
<html>
<head>
<title>The style Attribute</title>
</head>
<body>
<p style="font-family:arial; color:#FF0000;">Some text...</p>
</body>
</html>
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
Value Meaning
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>
30
HTML
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 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>
Generic Attributes
Here's a table of some other attributes that are readily usable with many of the HTML tags.
31
HTML
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>
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>
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>
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
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>
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>
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>
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>
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>
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>
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>
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>
39
HTML
CONTENT ARTICLES
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 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>
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>
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>
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>
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>
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>
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>
44
HTML
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>
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
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>
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>
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>
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>
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>
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>
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.
Attribute Description
Name Name for the property. Can be anything. Examples include, keywords,
description, author, revised, generator etc.
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>
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
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.
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.
h1 {
color: #36CFFF;
}
12
* {
color: #000000;
}
This rule renders the content of every element in our document in black.
ul em {
color: #000000;
}
.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:
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.
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.
• 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-".
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:
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.
<head>
<style type="text/css" media="...">
Style Rules
............
</style>
</head>
Attributes
Attributes associated with <style> elements are:
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>
Attributes
Attribute Value Description
Example
Following is the example of inline CSS based on the above syntax:
18
<h1 style ="color:#36C;"> This is inline CSS </h1>
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.
<head>
<link type="text/css" href="..." media="..." />
</head>
Attributes
Attributes associated with <style> elements are:
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>
<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>
• 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.
<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
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:
23
Defines a measurement in points. A point
pt body {font-size: 18pt;}
is defined as 1/72nd of an inch.
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:
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.
25
#000000
#FF0000
#00FF00
#0000FF
#FFFF00
#00FFFF
#FF00FF
#C0C0C0
#FFFFFF
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.
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.
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:
The specification for JavaScript 2.0 can be found on the following site:
http://www.ecmascript.org/
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>
• 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.
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>
Hello World!
15
<!--
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, you must 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.
Example
The following example shows how to use comments in JavaScript.
/*
* 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.
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.
• There you will find the option to enable or disable javascript by right-clicking
on the value of that option -> select toggle.
• Click the Chrome menu at the top right hand corner of your browser.
• Select Settings.
• 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:
To disable JavaScript support in Opera, you should not select the Enable
JavaScript checkbox.
You can add a noscript block immediately after the script block as follows:
<html>
<body>
<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
In the following section, we will see how we can place JavaScript in an HTML file in
different ways.
<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>
Say Hello
<html>
<head>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
Hello World
22
This is web page body
<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>
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 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>
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>
Local
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.
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
• Assignment Operators
Arithmetic Operators
JavaScript supports the following arithmetic operators:
+ (Addition)
- (Subtraction)
29
* (Multiplication)
/ (Division)
% (Modulus)
++ (Increment)
-- (Decrement)
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>
Output
a + b = 43
a - b = 23
a / b = 3.3
a % b = 3
a + b + c = 43Test
a++ = 33
b-- = 10
32
Comparison Operators
JavaScript supports the following comparison operators:
== (Equal)
Checks if the value of two operands are equal or not, if yes, then
1
the condition becomes 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.
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.
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.
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.
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 />";
//-->
</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:
1 If both the operands are non-zero, then the condition becomes 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.
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 />";
//-->
</script>
37
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
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:
Ex: (A & B) is 2.
| (BitWise OR)
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.
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.
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.
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 />";
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:
= (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
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
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
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
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
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 />";
43
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
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.
? : (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 />";
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
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.
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 />";
47
//-->
</script>
<p>Set the variables to different values and different operators and then
try...</p>
</body>
</html>
Output
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.
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
Attempts to create a server socket bound to the specified port. An exception occurs if the
port is already bound by another application.
Similar to the previous constructor, the backlog parameter specifies how many incoming
clients to store in a wait queue.
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
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.
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.
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
Sets the time-out value for how long the server socket waits for a client during the accept.
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.
The Socket class has five constructors that a client uses to connect to a server:
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.
This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object.
Connects to the specified host and port, creating a socket on the local host at the specified
address and port.
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.
This method connects the socket to the specified host. This method is needed only when
you instantiated the Socket using the no-argument constructor.
Returns the input stream of the socket. The input stream is connected to the output stream
of the remote socket.
Returns the output stream of the socket. The output stream is connected to the input
stream of the remote socket
Closes the socket, which makes this Socket object no longer capable of connecting again
to any server
4 String getHostAddress
5 String getHostName
7 String toString
import java.net.*;
import java.io.*;
import java.net.*;
import java.io.*;
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.
Types
EJB is primarily divided into three categories; following table lists their names with brief
descriptions:
Type Description
Benefits
Following are the important benefits of EJB:
• 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.
OS Task Command
Open Command
Windows c:\> java -version
Console
Open Command
Linux $ java -version
Terminal
Mac Open Terminal machine:~ joseph$ java -version
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.
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
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
OS Installer name
Windows Netbeans 7.3
Linux Netbeans 7.3
Mac Netbeans 7.3
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
11
EJB
Add Server Instance wizard will open. Select JBoss and in next step enter the relevant details
to configure server in netbeans.
12
EJB
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.
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.
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.
LibrarySessionBeanRemote
package com.tutorialspoint.stateless;
import java.util.List;
import javax.ejb.Remote;
@Remote
17
EJB
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>();
}
18
EJB
19
EJB
• 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_HOME: C:\jboss-5.1.0.GA
CLASSPATH: C:\jboss-5.1.0.GA\bin\run.jar
=========================================================================
20
EJB
• Select Deploy.
21
EJB
• 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.
• 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 also provides a rich library of various JavaScript modules which simplifies the
development of web applications using Node.js to a great extent.
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.
Concepts
The following diagram depicts some important parts of Node.js which we will discuss in detail
in the subsequent chapters.
6
Node.js
7
2. ENVIRONMENT SETUP Node.js
Try the following example using the Try it option available at the top right corner of the below
sample code box (on our website):
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.
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
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
$ 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
OS Output
9
Node.js
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.
$ 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.
Step1 - ImportRequiredModule
We use the require directive to load the http module and store the returned HTTP instance
into an http variable as follows:
11
Node.js
response.end('Hello World\n');
}).listen(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.
$ node main.js
12
Node.js
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.
● 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.
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
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
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:
For example, following is the command to install a famous Node.js web framework module
called express:
18
Node.js
$ 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.
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/",
"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
• keywords - keywords
Uninstalling a Module
Use the following command to uninstall a Node.js module.
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.
Search a Module
Search a package name using NPM.
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.
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]
$ 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.
var fs = require("fs");
console.log(data.toString());
console.log("Program Ended");
$ node main.js
28
Node.js
var fs = require("fs");
console.log("Program Ended");
$ node main.js
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:
31
Node.js
// Fire an event
eventEmitter.emit('eventName');
Example
Create a js file named main.js with the following code:
32
Node.js
console.log("Program Ended.");
Now let's try to run the above program and check its output:
$ mnode main.js
connection successful.
data received successfully.
Program Ended.
var fs = require("fs");
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:
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.
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
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
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:
// 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");
eventListeners =
require('events').EventEmitter.listenerCount(eventEmitter,'connection');
console.log(eventListeners + " Listner(s) listening to connection event");
console.log("Program Ended.");
$ node main.js
38
Node.js
39
MongoDB
1. MongoDB ─ Overview
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
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.
• No complex joins.
• Tuning.
• Uses internal memory for storing the (windowed) working set, enabling faster access
of data.
7
MongoDB
8
MongoDB
3. MongoDB ─ Environment
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.
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.
10
MongoDB
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
mongo
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.
• Duplicate the data (but limited) because disk space is cheap as compare to compute
time.
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 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.
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
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
>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.
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 }
>
>show dbs
local 0.78125GB
test 0.23012GB>
19
MongoDB
7. MongoDB ─ Create Collection
Syntax
Basic syntax of createCollection() command is as follows:
db.createCollection(name, options)
Options parameter is optional, so you need to specify only the name of the collection.
Following is the list of options you can use:
20
MongoDB
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:
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
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.
• Servlets execute within the address space of a Web server. It is not necessary to
create a separate process to handle each client request.
• 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.
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.
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
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.
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:
• 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.
%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
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
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%
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
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 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.
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
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.
8
Java Servlets
After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this:
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.
9
JSP ─ OVERVIEW JSP
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.
• 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. 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.
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:
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
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.
13
JSP
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:
• 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
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%
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
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.
• 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.
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:
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.
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.
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.
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
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.
You can write the XML equivalent of the above syntax as follows:
<jsp:declaration>
code fragment
</jsp:declaration>
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.
You can write the XML equivalent of the above syntax as follows:
<jsp:expression>
expression
</jsp:expression>
<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
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
<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>
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
25
JSP
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the following
form:
Directive Description
<%@ include ... %> Includes a file during the translation phase.
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:
Action elements are basically predefined functions. Following table lists out the available JSP
Actions:
Syntax Purpose
26
JSP
27
JSP
Objects Description
page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
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.
Now look at the following switch...case block which has been written a bit differentlty
using out.println() and inside Scriptletas:
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>
Loop Statements
You can also use three basic types of looping blocks in Java: for, while,and do…while blocks
in your JSP programming.
<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>
</font><br />
<%fontSize++;%>
<%}%>
</body>
</html>
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.
33
JSP
JSP Literals
The JSP expression language defines the following literals:
• Integer: 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:
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.
Directive Description
<%@ include ... %> Includes a file during the translation phase.
<%@ taglib ... %> Declares a tag library, containing custom actions, used in the
page
You can write the XML equivalent of the above syntax as follows:
35
JSP
Attributes
Following table lists out the attributes associated with page directive:
Attribute Purpose
36
JSP
Check for more details related to all the above attributes at Page Directive.
You can write the XML equivalent of the above syntax as follows:
Attributes
Following table lists out the attributes associated with the page directive:
Attribute Purpose
37
JSP
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:
Use the following to direct the servlet to write the output to a buffer of size not less than 8
kilobytes:
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:
This directive causes the servlet to flush the output buffer when full:
Usually, the buffer and the autoFlush attributes are coded on a single page directive as
follows:
If you want to write out XML from your JSP, use the following page directive:
The following statement directs the browser to render the generated page as HTML:
The following directive sets the content type as a Microsoft Word document:
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
The following directive displays MyErrorPage.jsp when all uncaught exceptions are thrown:
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:
For example, the following directive directs the JSP translator to generate the servlet such
that the servlet extends somePackage.SomeClass:
To import multiple packages, you can specify them separated by comma as follows:
40
JSP
For example, because you usually use Java as the scripting language, your language option
looks like this:
Following directive allows the JSP page to use any of the builtin object session methods such
as session.getCreationTime() or session.getLastAccessTime():
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
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:
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:
For more details related to include directive, check the Include Directive.
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:
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:
<%!
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/>
43
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.
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.
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:
For more details related to the taglib directive, check the Taglib Directive.
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.
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:
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:
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