UNIT I Final
UNIT I Final
WEB TECHNOLOGY
VI SEMESTER
SYLLABUS
Lectures Tutorials Practical
Subject Code Subject Name
(Periods) (Periods) (Periods)
CS T63 WEB TECHNOLOGY 3 1 -
Course Objectives:
1. To learn and program features of web programming languages.
2. To understand the major components of internet and associated protocols.
3. To design an innovative application for web.
Course Outcomes:
On successful completion of this course
1. The students will get acquainted with client side and server side programming
languages for web.
2. They will understand the major components and protocols of internet application.
3. They will become capable of designing web services.
UNIT - I
Internet Principles and Components: History of the Internet and World Wide Web – HTML -
protocols – HTTP, SMTP, POP3, MIME, IMAP. Domain Name Server, Web Browsers and Web
Servers. HTML-Style Sheets-CSS-Introduction to Cascading Style Sheets-Rule-Features-
Selectors- Attributes. Client-Side Programming: The JavaScript Language- JavaScript in
Perspective-Syntax-Variables and Data Types-Statements-Operators-Literals-Functions-
Objects-Arrays-Built-in Objects-JavaScript Debuggers and Regular Expression.
UNIT - II
Server Side Programming: Servlet- strengths – Architecture - Life cycle - Generic and HTTP
servlet- Passing parameters- Server Side Include- Cookies- Filters. JSP- Engines-Syntax-
Components- Scriplets- JSP Objects-Actions-Tag Extensions- Session Tracking- Database
connectivity- Sql statements-J2EE - Introduction - Beans- EJB.
UNIT - III
XML: Introduction- Revolutions of XML-XML Basics – Defining XML Documents: DTD-XML
Schema-Namespaces – XFiles: XLink – XPointer - XPath - XML with XSL – XSL-FO-Parsing XML
using DOM-SAX-Integrating XML with database – Formatting XML on the web.
UNIT - IV
Multimedia and Web Application: Multimedia in web design, Audio and video speech
synthesis and recognition - Electronic Commerce – E-Business Model – E-Marketing – Online
Payments and Security – N-tier Architecture. Search and Design: Working of search engines -
optimization- Search interface.
UNIT - V
Web Services: Introduction to Web Services, UDDI, SOAP, WSDL, Web Service Architecture,
Developing and deploying web services. Ajax – Improving web page performance using Ajax,
Programming in Ajax.
TOTAL PERIODS: 60
TEXT BOOKS
1. Deitel and Deitel, Goldberg, “Internet and World Wide Web – How to Program”,
Pearson Education Asia, 2001.
2. Uttam K.Roy, “Web Technologies”, Oxford University Press, 2012.
3. Rajkamal, “Web Technology”, Tata McGraw-Hill, 2001.
4. Ron Schmelzer, Travis Vandersypen, Jason Bloomberg, Madhu Siddalingaiah, Sam
hunting, Micheal D.Qualls, David Houlding, Chad Darby, Diane Kennedy, “XML and Web
Services”, Sams, Feburary 2002.
5. Eric Newcomer, “Understanding Web Services: XML, WSDL, SOAP, and UDDI”, Addison-
Wesley, 2002.
REFERENCE BOOKS
1. Phillip Hanna, “JSP 2.0 - The Complete Reference”, McGraw-Hill, 2003.
2. Mathew Eernisse, “Build Your Own AJAX Web Applications”, SitePoint, 2006.
UNIT-I
Internet Principles and Components: History of the Internet and World Wide Web –
HTML - protocols – HTTP, SMTP, POP3, MIME, IMAP. Domain Name Server, Web
Browsers and Web Servers. HTML-Style Sheets-CSS-Introduction to Cascading Style
Sheets-Rule-Features- Selectors- Attributes. Client-Side Programming: The JavaScript
Language- JavaScript in Perspective-Syntax-Variables and Data Types-Statements-
Operators-Literals-Functions-Objects-Arrays-Built-in Objects-JavaScript Debuggers and
Regular Expression.
2 MARKS
1. Define internet?
Network is an interconnection of systems to share data and information. Internet is network of
network or collection of heterogeneous networks.
The Internet is a global system that consists of millions of public, private, academic, business, and
government networks of local to global scope. It allows all the computers connected to it to exchange
information with one another.
7. What is protocol?
A protocol is a set of rules or an agreement that specifies a common language that computer on a
network use for communication with other computers. It specifies on how the computer talk with
each other.
A protocol is a set of rules that define the syntax and semantics of the connection, communication, and
data transfer between two computing end-points.
Unordered List:
It starts with <ul> and ends with </ul>
Attributes of Unordered lists
Type
TYPE = FILLROUND or TYPE = SQUARE
Example:
<UL TYPE = FILLGROUND>
<LI> CSE </LI>
<LI> IT </LI>
</UL>
Output:
CSE
IT
START: Alters the numbering sequence can be set to any numeric value.
VALUE: Change the numbering sequence in the middle of an ordered list.
Example:
<OL TYPE = “1” START = 5>
<LI> CSE </LI>
<LI> IT </LI>
</OL>
Output:
5. CSE
6. IT
27. What is the use of frames in html give the syntax of frames?
Frames are used to call many html files at the same time. This can be done using <FRAMESET>
</FRAMESET> tags.
Attributes of Frames:
ROWS – This attribute is used to divide the screen into multiple rows. It can be set equal to a list
of values. Depending on the required size of each row. The values can a number of pixels.
Expressed as a percentage of the screen resolution.
The symbol *, which indicates the remaining space.
COLS – This attribute is used to divide the screen into multiple columns.
Example:
<FRAMESET ROWS = “30 %,*”> => Divides the screen into 2 rows, occupying the remaining space.
<FRAMESET COLS = “50%, 50 %”> => Divides the first row into 2 equal columns.
<FRAME SRC = “file1.html”>
<FRAME SRC = “file2.html”>
<FRAMESET COLS = “50%, 50 %”> => Divides the second row into 2 equal columns.
<FRAME SRC = file3.html”>
<FRAME SRC = file4.html”>
</FRAMESET>
Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format
of email to support:
Text in character sets other than ASCII.
Non-text attachments: audio, video, images, application programs etc.
Message bodies with multiple parts.
Header information in non-ASCII character sets.
Example:
#para1 {
text-align: center;
color: red;
}
Example:
All HTML elements with class="center" will be red and center-aligned:
.center {
text-align: center;
color: red;
}
Example:
h1, h2, p {
text-align: center;
color: red;
}
[class*="te"] {
background: yellow;
}
Example:
document.getElementById("demo").innerHTML = "Hello Dolly.";
Window object
where
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
In JavaScript, regular expressions are often used with the two string methods: search() and
replace().
1. The search() method uses an expression to search for a match, and returns the position of
the match.
2. The replace() method returns a modified string where the pattern is replaced.
11 MARKS
Internet:
The internet is a collection of interconnected computer networks, linked by copper wires, fiber
optic cables, wireless connections etc.
Network is an interconnection of systems to share data and information. Internet is a network of
network or collection of heterogeneous networks.
The internet (also known as net) is the worldwide, publicly accessible system of interconnected
computer networks that transmit data by packet switching using the standard Internet Protocol
(IP).
It consists of millions of smaller domestic, academic, business and government networks, which
together carry various information services such as
Electronic mail
Online chat
Interlinked web pages
Other documents of WWW
Internetworks (Networks):
When two or more networks are connected, they become an internetworks or networks
LAN R LAN
R R
LAN R WA R LAN
N
Web:
The web is a collection of interconnected documents, linked by hyperlinks and URLs and is accessible
using the Internet.
Applications of internet:
Electronic mail
World Wide Web
FTP
Telnet
Chat & Online transaction
Usage:
Internet was limited to universities and research institutions; then the military began using the
internet.
The government decided to allow access to the internet for commercial purposes.
The WWW became commercially viable during 1996-98 when a large number of dot-com
companies used it for placing their services on the web.
In past, most computer applications run on computers that were not connected to one another,
whereas today’s applications can be written to communicate among the world’s computers.
The internet mixes computing & communication technologies. It makes our work easier. It makes
information instantly and conveniently accessible worldwide.
It enables individuals and small business to get worldwide exposure. It is changing the way
business is done.
People can search for the best prices on virtually any product or service special interest
communities can stay in touch with one another.
HTTP – Communication between a web server and a web browser.
HTTP is used for sending requests from a web client (browser) to a web server, returning web
contents (web pages) from the server back to the client.
</HTML>
are the first and last tags in a page. All the content in HTML goes within these tags, which tell the
browser, or any other program reading that page that the file is a web page.
With these tags lie the header tags <HEAD> ……</HEAD>; the HEAD tags are always first and do
not contain the page’s actual content.
The only content the page title enabled through the TITLE tags.
The TITLE tags occur within the HEAD tags and are the name of the browser window that is
currently active.
The HEAD tag can also contain script.
The syntax for the HEAD section
1. TITLE – Document title
2. LINK – Site structure
3. BASE – Document location
4. SCRIPT – Java script and VB script
Example:
<Html>
<Head>
<Title> Example Of Web </Title>
</Head>
</Html>
Black - #000000
The default background, text and link colors for the web page are white, black and blue.
Heading tags:
Heading in HTML are to be used like heading in Books and Newspapers. Headings divide sections of
text and improve page readability.
The above six levels of headings defined by HTML.
<H1>……</H1> - Level 1 Header
<H2>……</H2> - Level 2 Header
<H3>……</H3> - Level 3 Header
<H4>……</H4> - Level 4 Header
<H5>……</H5> - Level 5 Header
<H6>……</H6> - Level 6 Header
Example:
<HTML>
<HEAD>
<TITLE> HEADING OG VARIOUS SIZE </TITLE>
</HEAD>
<BODY>
<H1> IP </H1>
<H2> Web </H2>
.
.
.
<H6> Technology </H6>
</BODY>
</HTML>
Example:
<HTML>
<HEAD>
<TITLE> Page with HTML Format tag </TITLE>
</HEAD>
<BODY>
<B> India is one of the developing country </B>
<BR>
<I> Web Technology </I>
<U> Internet Programming </U>
<P> Welcome to web technology laboratory </P>
</BODY>
</HTML>
Output:
Web Technology
Internet Programming
Lists of text:
The most commonly list are of 2 types
1. Ordered Lists (OL)
Example:
<HTML>
<HEAD>
<TITLE> Using Lists </TITLE>
</HEAD>
<BODY>
<HR>
<UL>
<B> MVIT
<LI>CSE
<LI>IT
</B>
</UL>
Dept
<OL>
<LI> Computer
<LI> Information
</OL>
</BODY>
</HTML>
Output:
MVIT
CSE
IT
Dept
1. Computer
2. Information
Example:
<HTML>
<HEAD>
<TITLE> Using definition lists </TITLE>
</HEAD>
<BODY>
<U> <H2> Bharath infotech </H2> </U>
<Font size = 2 >
<DL>
<DT> The company </DT>
<DD> Mr. X is the CEO of the company</DD>
<DD> Mr. Y & Z are the incharge of QC</DD>
</DL>
</Font>
</BODY>
</HTML>
Output:
Bharath Infotech
The Company
Mr. X is the CEO of the company
Mr. Y & Z are the incharge of QC
Font tag:
<Font color = “Red” Face = “Times” size = 5>
All data displayed here is red in color and has the times font and the size is 5
</Font>
Linking:
The most important capability of the HTML is its ability to create hyperlinks to documents and
make the World Wide Web as a collection of linked documents.
The links are created using anchor <a>…..</a> element.
<a href = “location of the page”> </a>
It is used to hyperlink the web page.
<Img src = “s.jpg” width =”25” height = ”25” align = “top”>…….</img>
This element requires an attribute to mark the location of the object to get linked. The address
of the object is specified using href attribute.
The href attribute of the tag tells the browser to get another html document of the web.
Example:
<html>
<head>
<title> Linking <title>
</head>
<body>
<h1 align=center> My favorite search sites</h1>
<p align=center> The yahoo!: <a href=””> http://www.yahoo.com </a> </p>
<p align=center> The Google: <a href=”> http://www.google.com </a> </p>
</body>
</html>
Output:
Internal linking:
To create links to external documents. HTML has facilities to include internal links also by
assigning a location name to any individual point in an HTML document.
This location name can then be added to the page URL
For internal linking also, the anchor tag is used.
Syntax:
To create name the following tag is used
<a name=”location”> </a>
To refer to the location use
<a href = “#name”> text </a>
Example:
<html>
<head>
<title> Internal Linking <title>
</head>
<body>
<h1 align=center> My book </h1>
<p> the book contains the following chapters </p>
<br>
<a href = “#chap1” > 1. Introduction </a> <br>
<a href = “#chap2” > 2. Topics1 </a> <br>
<a href = “#chap3” > 3. Topics2 </a> <br>
<a name = “chap1” > </a>
<h3 align = “center”> Chapter 1 </h3>
<p> The text is here </p> <br>
<a name = “chap2” > </a>
<h3 align = “center”> Chapter 2 </h3>
<p> The text is here </p> <br>
<a name = “chap3” > </a>
<h3 align = “center”> Chapter 3 </h3>
<p> The text is here </p> <br>
</body>
</html>
Output:
My book
The book contain the following chapters
1. Introduction
2. Topics 1
3. Topics 2
Chapter 1
The text is here
Chapter 2
The text is here
Embedding Images:
Images can be embedded into the web page. To add images as a background for the whole web
page, the following format is used,
<body background = “bg.gif”>
To include the image as a normal figure in the web page the <img> tag is used.
The image tag has the following attributes
src
height
width
border
align
alt
The src attribute is used to specify the location of the image, height and width, specify the size.
alt attribute which is provided for browsers that have images turned off or that cannot have
images.
The value of alt attribute will appear on screen in the place of the images.
Example:
< img src = “url “ height = “144” border = “1” width = “200” alt = “An image is here”>
</img>
The other related tag is <map> which is used to create hot spots. The syntax is
<map name = “ “>
……
</map>
Example:
The following code creates a hot spot of rectangular shape and has the hyperlink in the coordinates
mentioned.
<map>
<area shape = “rect” cords =”23, 45, 56, 89” href = “source.html”>
</map>
Frames:
Frame layout is one in which the browser windows is broken into multiple region called frames.
Each frame contains different HTML documents.
The <frameset> tag is a container for frames and replaces the body tag. </frameset>
<frame> tag is used to place the contents into the frame.
Example:
Example:
Divides the window into 2 regions in row wise
<frameset rows = “30%,70%”>
The <frame> tag is used to place different HTML documents in each frame.
<frame src = “ “ frameborder = “0|1” name = “name” scrolling = “yes|no|auto”>
Example:
<html>
<head>
<title> Internal Linking <title>
</head>
<frameset cols = “40% , * “>
<frame src=”list1.html”>
<frame src=”l.html”>
</frameset>
</html>
Other tags:
& – is used to insert an ampersand
The tag <del> is used to strike through text with a horizontal line.
The tag <sub> and <aup> are used to turn the text into subscript and superscript.
To draw a horizontal line in the web page <hr> tag is used. This tag has 3 attributes
width – to specify the width of the line
size – to specify the height of the line
noshade – eliminates the default shading effect and instead display the horizontal rule as
a solid color bar.
Example:
<hr noshade width = “50%” size = 5 align = “center”>
Tables:
This form tag is the HTMLs best way of arranging information in space and controlling layout
Table element to format a table
The various tag in table as
<table>……</table>
align = left, center, right
border = make a border around the table & its cells
1. The <tr> element (table row) inserts a row in the table.
2. The <td> element (table detail) inserts a cell within a row
3. The <th> element (table header) to add headings to the rows and columns of the table.
Example:
<table>
<tr>
<td> apples
<td> celery
</tr>
<tr>
<td> oranges
<td> carrots
</tr>
</table>
Output:
apples celery
oranges carrots
<caption> tag is used to be added to row and column headings. By default it will be aligned in center
of a table.
<border> is used for draw a border around the tables and the individual cells. Specify the border
width in pixels.
Example:
<table border = 1>
<caption> Fruits and vegetables </caption>
<tr>
<th> Fruits
<th> vegetables
</tr>
<tr>
<td> apples
<td> celery
</tr>
<tr>
<td> oranges
<td> carrots
</tr>
</table>
Output:
Fruits and Vegetables
fruits vegetables
apples celery
oranges carrots
Color can be added to tables by using the bgcolor = and bordercolor = attributes. These attributes
are available in the Table, <tr> and <td> elements; so user can apply colors to all the cell in a table,
selected rows and individual cells.
Example:
<table border = “1” cellspacing = “10%” cellpadding = “10%”> …. </table>
Spanning rows:
The two types of attributes are
colspan – to span column
rowspan – to span rows
Example:
<table border = “2”>
<tr>
<th colspan = 3> Tic Tac Games </th>
</tr>
<tr>
<td> X </td>
<td> O </td>
<td> X </td>
</tr>
</table>
Example:
<table border = “2”>
<tr>
<th rowspan = 3> Tic Tac Games </th>
</tr>
<tr>
<td> X </td>
<td> O </td>
<td> X </td>
</tr>
</table>
The bgcolor = attribute sets the color used to fill the background of the cell before text and images
are drawn.
The border color = attribute sets the color of the borders drawn around the table, row or cell.
Example:
<table border color = “navy” border = 5>
<tr bgcolor = “gray”>
<th>Fruits <th> Vegetables
</tr>
<tr>
<td bgcolor = “lime”> Apples <td bgcolor = “Aqua”>Celery
</tr>
<tr>
<td bgcolor = “lime”> Oranges <td bgcolor = “Aqua”>Carrots
</tr>
</table>
HTML Forms:
Form provides a way to prompt the user for information and to carry out the actions based on the
input.
A form consists of one or more input controls that the user uses to enter text and select choices.
Once the user provides the input, the form collects the data and sent it to a destination specified in
the form element.
To carry out the requested action, the server must have a script or other service that corresponds to
the destination.
A form can contain inputs like text fields, check boxes, passwords, radio-buttons, submit buttons
and reset buttons.
The <form> tag is used to create an HTML form.
<form name=” frm1“ action=”index.jsp “ method=”get|post” >
</form>
HTML forms are used to pass the data to the server.
Input Types:
Text Fields
Check Boxes
Password
Radio Button
Submit Button
Reset Button
Image Based Buttons
Scripted Buttons
The syntax is
<input type = “text | passwd” name =”name” value =”default_value” size=”field size”>
1. Text Fields:
<input type=”text”> defines a one line input field that a user can text into.
Example:
<form>
First name: <input type=”text” name=”first name”>
Last name: <input type=”text” name=”last name”>
</form>
The output is
First name: SMVEC
Last name:
IFET
2. Password Field:
<input type=”password”> defines a password field.
Example:
<form>
Password: <input type=”password” name=”pwd”>
</form>
3. Radio Buttons:
<input type=”radio”> defines a radio button.
Radio buttons let a user to select only one of a limited number of choices.
Example:
<form>
Gender <input type=”radio” name=”gender” value=”male” checked> Male
Gender <input type=”radio” name=”gender” value=”female”> Female
</form>
The output is
Male
Female
4. Checkboxes:
<input type=”checkbox”> defines a checkbox.
Checkboxes let a user to select one or more options of a limited number of choices.
Example:
<form>
<input type=”checkbox” name=”vehicle” value=”bike”> Bike <br>
<input type=”checkbox” name=”vehicle” value=”car”> Car
</form>
The output is
Bike
Car
5. Submit Button
<input type=”submit”> defines a submit button.
A submit button is used to send the form data to a server. The data is sent to the page specified
in the form’s action attribute.
The file defines in the action attribute usually does something with the receiving input.
<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>
Username:
Click the “submit” button, the browser will send your input to a page called “filename”.
6. Text Area:
This tag sets up a multiple line input text window.
The Syntax is
<textarea name=”name” rows=”no of rows” cols=”no of cols” accesskey=”shortcut
key”></textarea>
Example:
Give the comments here <br>
<textarea name=”comments” rows=10 cols=20>
</textarea>
Output:
Example:
<form name=”form1”>
Text<input type=”text” name=”textfield” size=”20”> <br>
<select name=”select1”>
<option> Item1</option>
<option> Item2</option>
</select>
</form>
Output:
8. Image Button:
<input type=”image” src=” “ name=”submit” value=”submit”>
9. Filename:
<input type=”file” name=”filename” value=” “ size=25> Browser
Example:
Browse
Output:
Source Program:
<html>
<head>
<title> Frame </title>
</head>
<body>
<center> <h1>Form Submission </h1> </center>
<form action=" home.jsp" method="get">
Login Name: <input type="text" name="login" size=20> <br>
Password: <input type="password" name="pass" size=20> <br>
Birthdate: <input type="text" name="DOB" size=20> <br>
Gender: <input type="radio" name="gender" value="F" checked> Female
<input type="radio" name="gender" value="m"> Male <br> <br>
Department
<select name="dept">
<option> CSE</option>
<option> IT</option>
</select> <br>
Give the comments here <br>
<textarea name="comments" rows=10 cols=20> </textarea>
<input type="button" value="check" OnClick="validate()"><br>
<input type="submit" value="login" OnClick="submit()">
<input type="reset" value="clear" OnClick="clear">
</form>
</body>
</html>
Client Server
HTTP Request
Message
HTTP Response
Message
Start Line
Header Line
“GET/home/web/cs336/syll.so9 HTTP/1.0\r\n”
Command
Resource
Protocol & Carriage Return
Pathname (UNIX
Version & Line-Feed
filename Syntax)
Number
i. Request Method
The various methods supported by HTTP are:
METHODS DESCRIPTIONS
GET Gets a file from the server (or) tells the server the client wants to get some resource.
POST Sends user information to the server (or) tells the server the client wants to get
some resources and information will be sent by the client that may modify the
request (ex: Submitting the form).
HEAD Gets information about a file from the server.
PUT Sends a file to be stored on the server (transfers a file from the client to the server).
DELETE Deletes a file on the server.
OPTIONS Requests the available server options.
URL Format:
Example:
Method: //host: port/path/filename
http://www.google.com:80/icuse/cs336/syllabus.pdf
Example:
GET/HTTP/1.0
HTTP/1.0 200 OK
Date: Mon, 12 Dec 2011 11:40:40 GMT
Server: Apache/1.3.3.7 (UNIX)
Last_Modified: Wed, 08 Jan 2003 12:10:10 GMT
E tag: “3f80F-1b6-3e1cb03b”
Server receives a request and uses its URL to decide how to handle it.
Accept-Range: bytes
Content-Length: 438
Connection: close
Content-Type: text/html
Start Line
Headers
A Blank Line
Body
Etag (Entity Tag) header is used to determine if a cached version of the requested resource is
identical to the current version of the resource on the server.
Content-Type specifies the internet media type of the data conveyed by the HTTP message.
Content-Length indicates it length in bytes.
The HTTP/1.1 Web Server publishes its ability to respond to requests for certain byte range
of the document – accept ranges bytes.
Connection: Close is sent in a header. It means that the web server will close the TCP
connection immediately after the transfer of this response.
Status Code:
SMTP provides for mail exchanges between users on the same or different computers and supports
are
Sending a single message to one or more recipients.
Sending messages that include text, audio, video format or graphics file.
Sending messages to users on networks.
User User
SMTP Client
SMTP Server
INTERNET
User A User B
UA
UA
A mail gateway which is a relay MTA that can receive mail prepared by a protocol other than
SMTP and transform it to SMTP format before sending it.
It can also receive mail in SMTP format and change it to another format before sending it.
User A User B
MTA Client
Mail Server
SMTP:
It is used to exchange mail messages between mail servers (MTA).
UA
File
UA System
Addresses
To deliver mail, a mail handling system must use a unique addressing system.
The addressing system used by SMTP as 2 parts
A local part
A domain name, separated by an @ sign
e-Mail Address
Localpart @ domain name
Local Part
The local part defines the name of a special file called the user mailbox, where all of the mail
received for a user is stored for retrieval by the user agent.
Domain Name
The 2nd part of the address is the domain name.
An organization usually selects one or more hosts, to receive and send e-mail. They are called
mail exchangers.
The domain name assigned to each mail exchanger from the DNS database.
Example: [email protected]
The actual mail transfer is done through mail transfer agent (MTA).
To send mail, a system must have a client MTA and to receive mail, a system must have a
server MTA.
Client sends command and server responds with command status message.
Status messages include ASCII encoded numeric status code and text string.
SMTP Commands
The SMTP provides a two way communication between the client and the server (remote)
MTA.
The client MTA sends commands to the server MTA, which turns, sends replies back to the
client MTA.
SMTP refers to the exchange of SMTP commands and replies between two hosts as mail
transactions.
Commands Descriptions
HELO Establishes SMTP connection, identify the sender (client).
MAIL FROM e-mail address of the sender.
RCPT TO e-mail address of the recipients.
BODY Body of the mail.
DATA Sender ready to transmit a series of lines of text, each ends with \r\n.
A line containing only a period ‘.’ Indicates the end of the data.
VRFY Verify that an e-mail address is valid.
EXPN Expands an alias (group e-mail address).
Data Format:
ASCII only – must convert binary to an ASCII representation to send via e-mail.
Example:
Date: Sat, 27 Jan 02 13:26:24 GMT
From: [email protected]
To: [email protected]
Subject: meeting
Let’s get together Monday at 1pm.
R 220 [email protected] SMTP service at 29 Jan 02 05:17:11 GMT
S HELO [email protected]
R 250 [email protected]
S mail from: <[email protected]>
R 250 mail Accepted
S RCPT TO: <[email protected]>
R 250 Recipient Accepted
Sender DATA
R 354 start mail input; end with <CRLF>. <CRLF>
S Date: Sat, 27 Jan 02 13:26:21 GMT
S From: [email protected]
S To: [email protected]
S Subject: meeting
S
S Let’s get together Monday at 1pm.
S
R 250 OK
S QUIT
R 221 [email protected] service closing transmission channel
SMTP Replies:
POP commands:
POP commands and replies are formatted as ASCII lines and all replies start with either
“+OK” or “-ERR”.
The various POP commands are
Command Description
USER Requires a name that identifies the user (Specify username).
PASS Specify password for the user/server.
STAT Get mailbox status (no. of messages in the mailbox).
LIST Get a list of messages and size, one per line, termination line contains a
period.
RETR Retrieves message from mailbox.
DELE Marks a message for deletion.
LAST The server returns the highest message no accessed.
RSET Unmarks all messages marked for deletion.
QUIT Remove marked messages and close the TCP connection.
Example:
QSMTP
char “mailmessage[]”
{
“HELO user: host\r\n”;
“MAIL FROM: [email protected]\r\n”;
“RCPT TO: [email protected]\r\n”;
“DATA\r\n”;
“This is my friend\r\n\r\n”;
“QUIT\r\n”
NULL
};
QPOP3
char “popmessage[]”
{
“USER your_mailbox_id\r\n”,
“PASS your_password\r\n”,
“STAT\r\n”,
“LIST\r\n”,
“RETR\r\n”,
“DELE\r\n”,
“QUIT\r\n”,
NULL
};
SMTP or POP3 based client program establishes a connection; it sends a command and waits
for the server to respond.
SMTP to transfer mail messages across the internet and POP3 to retrieve mail from the
internet.
The two protocols are
QSMTP
QPOP3
QSMTP used for send mail to send e-mail messages using SMTP
QPOP3 – get mail to retrieve e-mail messages using SMTP
Features of MIME:
MIME transforms non-ASCII data at the sender site to NVT ASCII data and delivers them to
the client MTA to be sent through the Internet.
The message at the receiving side is transformed back to the original data.
NVT(Network Virtual Terminal)
MIME Headers:
The 5 header fields to internet e-mail messages.
1. MIME version
2. Content type
3. Content transfer encoding
4. Content id
5. Content description
1. MIME-Version:
This header defines the version of MIME used.
The current version is 1.1
MIME-Version: 1.1
2. Content type:
This header defines the type of data used in the body of the message.
The content type and the content subtype are separated by a slash.
Depending on the subtype, the header may contain other parameters.
Content-Type : < type / sub-type >
2. Content –Transfer:
This header defines the method used to encode the messages into 0’s and 1’s for transport.
Content -Transfer – Encoding: < type >
Base-64
4. Content-Id:
This header uniquely identifies the whole message in a multiple-message environment.
Content-Id: id = < content-id >
5. Content-Description:
This header defines whether the body is image, audio, or video.
Content-Description: <description>
The feature of IMAP is the mail messages remain on the server, instead of being downloaded
to a computer.
Checking the mail with a client or web-based environment using the protocol.
IMAP supports the use of folders for mail organization, but instead of organizing the
messages on the local computer, these folders are kept on the server.
IMAP is quicker access to mail.
The message headers are initially downloaded so the user can choose to download, open and
read only this message.
Using IMAP and saving messages on the server is that the user will be restricted.
The Namespace
The namespace is the structure of the DNS database.
An inverted tree with the root node at the top.
Each node has a label.
The root node has a null node written as “ “.
Root Node
Labels
Each node in the tree must have a label
A string of upto 63(8 bit bytes)
Legal characters are a-z & A-Z
Sibling nodes must have unique label
The null label is reserved for the root node
Root
1. Generic Domains:
The generic domains define registered host according to their generic behavior.
Each node in the tree defines a domain, which is an index to the domain namespace database.
It represents as 3 character labels.
Ex: com, edu.
Sub-Domain
One domain is a sub domain of another if its apex node is a descendant of the others apex
node.
One domain is a sub domain of another if its domain name is in the other’s domain name.
Ex: sales.google.com is a subdomain of
google.com
com
Administrators can create subdomains to group hosts.
The parent domains retain links to the delegated subdomains.
Zones
The subdomain and its parent domain can now be administrated independently. These units
are called zones.
The boundary between zones is a point of delegates in the namespace.
univ
2. Country Domain:
The county domain section follows the same format as the generic domains but uses two
characters country abbreviations
Ex: .us(United States), .in(India)
3. Inverse Domain:
The inverse domain is used to map an address to a name.
For ex, when a server has received a request from a client to do a task.
The server has a file that contains a list of authorized clients; the server lists only the IP
address of the client.
If the client is on the authorized list, it can send a query to the DNS server and ask for a
mapping of address to name.
Infrastructure domains as
IPv4 reverse (address to name) lookups
IPv6 reverse lookups
DNS root server get approximately 3000 queries per second.
12. Explain about the web browser and web servers? (11 MARKS)
Web Browser:
The internet is an essential medium for communicating and interacting with people
worldwide.
A web browser is used to display web pages. Common web browsers are Netscape navigator
and internet explorer.
The web browser is the interpreter of our web sites.
Web browsers are software programs that allow users to access the web content.
Millions of people use web browsers to access the tremendous amount of information
available on the web and to store or exchange this content with other users.
The popular web browsers are
Microsoft’s Internet Explorer
Mozilla’s Firefox
Apple’s Safari
Opera Software’s Opera
Google Chrome
Web browsers, a software application used to locate, retrieve and also display content on the
worldwide web, including web pages, images, videos and other files.
As a client/server model, the browser is the client run on a computer that contacts the web
server and request information.
The web server sends the information back to the web browser which displays the results on
the computer or other internet enabled device that supports a browser.
Browsers are fully functional software suites that can interpret and display HTML web pages,
applications, java scripts, AJAX and other content hosted on web servers.
Many browsers offer plug-in which extend the capabilities of a browser so it can display
multimedia information (including sound and video) or the browser can be used to perform
tasks such as video conferencing, to design web pages or add ant phishing filters and other
security features to the browser.
Web Servers:
Web servers are computers that deliver (serves up) web pages.
Every web server has an IP address and possibly a domain name.
Ex: if you enter the URL http://www.google.com/index.html in your web browser. This sends
a request to the web server whose domain name is google.com. The server then fetches the
page named index.html and sends it to your browser.
Any computer can be turned into a web server by installing server software and connecting
the machine to the internet.
Web server software applications including public domain software from NCSA (National
Computer Security Association) and Apache web server.
The web browser includes 3 categories as
Static web document
Dynamic web document
Active web document
Static Documents:
Static documents are fixed content documents that are created and stored in a server.
The client can get only a copy of the document.
The content in the server can be changed but the user cannot change it.
When a client accesses the document, a copy of the document is sent. The user then uses a
browser to display the content.
Web document
Dynamic Document:
A dynamic document is created by a web server whenever a browser requests the document.
When a request arrives, the web server runs an application program that creates the
dynamic document.
The server returns the output of the program as a response to the browser that requested
the document.
Because a fresh document is created for each request, the contents of a dynamic document
can vary from one request to another.
Ex: Dynamic document is getting the time and date from the server.
Time and date are kinds of information that is dynamic and they change from moment to
moment.
Cricket refresh button.
Program
Client Request Server
Program Document
Client
Server
P a g e | 66 WEB TECHNOLOGY DEPARTMENT OF CSE
MANAKULA VINAYAGAR INSTITUTE OF TECHNOLOGY
Program
c. Response
A server that handles dynamic documents as
The server examines the URL to find if it defines a dynamic document.
If the URL defines a dynamic document, the server executes the program.
The server sends the output of the program to the client (browser).
Active Document:
We need a program to be a run at the client side.
Ex: we want to run a program that creates animated graphics on the screen or interacts with
the user.
The program can be run at the client side where the animation or interaction taken place.
An active document in the server is stored in the form of binary code.
Ex: Java Applet
1. Request
Get /index.html HTTP/1.1
HOST: www.google.com
Date: ……….
User-agent: Mozilla Firefox/8.9
Accept-type: text/html, image/jpeg
/*blank line*/
3. Response
HTTP/1.1 200 OK
Server: Apache Server/5.1
Location: http://www.google.com/imksmvec/coll.html
Date-time: …
Content-type: text/html
Content-length: 67
/*blank line*/
Each server has multiple ports.
Each port also has multiple sockets.
The socket at a server provides a document, a page or a resource.
A web server is software. A computer running that software connects to all servers on the
internet.
Examples: The servers are Apache web server, Netscape and Microsoft IIS (Internet
Information Server).
Web servers are also called hosts.
and host
name
Telnet 23
Resources
Path Translations
Web servers are able to map the path component of URL into
A local file system resource (static resource)
Internal or External program name (dynamic resource)
Example: http://www.google.com/path/file.html
The client user agent will translate it into a connection to www.google.com with the HTTP1.1
request.
Example:
GET/path/file.html HTTP1.1
Host: www.google.com
The server on www.google.com will append the given path of its root directory.
Load
It can handle only a limited number of concurrent client connections (usually between 2 and
80000 by default between 500 and 1000) per IP address and it can serve only a certain
number of requests per second.
Its own setting.
HTTP request type
Content type (static or dynamic document)
Hardware and software limitations of OS
Server
Server Name Foundation
1 Apache Apache
2 IIS (Internet Information Microsoft
Server)
3 Nginx Igarsysoev
4 GWS Google
5 Sun Java System Web Server Oracle
6 Lighttpd lighttpd
DHTML
2. Animate text and images in document, independently moving each element from any starting
point to any ending point.
3. Create a timer that automatically refreshes the content of a document with the latest news,
stock quotes, cricket scores, etc.
4. Animated audio and video files (visual change)
5. Create a form and then instantly read, process and respond to the data. The user enters in the
form.
6. DHTML can be
a. Internet Explorer: VB Script and JavaScript both works
b. Netscape Navigator: JavaScript
7. Forms processing (validation, calculations)
8. Changing text (moving, scrolling, blinking, etc…)
Introduction to (CSS):
CSS stands for Cascading Style Sheets
CSS describes how HTML elements are to be displayed on screen, paper, or in other
media
CSS saves a lot of work. It can control the layout of multiple web pages all at once
External style sheets are stored in CSS files.
CSS are rules or styles for organizing the layout of an HTML document including its color,
typefaces, margins, links and other formatting elements.
Style sheets make it easier to create an index because indexing software has only to read the
structural elements rather than full content page.
User includes multiple set of style sheet information.
It contains rules, composed of selectors and declarations that define how styles are applied.
The selector (HTML element, class name or ID name) is the link between the HTML document
and the style.
HTML element tags
Attributes (class, ID name)
Rule or Syntax:
A CSS rule set consists of a selector and a declaration block:
Selector { property1: value1; property2: value2; } or tagname {style_attribute value:}
h1 { color : blue; font-size : 12px; }
The selector points to the HTML element you want to style.
The declaration block contains one or more declarations separated by semicolons.
Each declaration includes a property name and a value, separated by a colon.
Example 1:
A CSS declaration always ends with a semicolon, and declaration groups are surrounded by curly
braces:
p{
color:red;
text-align:center;
}
Example 2:
<html>
<head>
<style type="text/css" >
body {background-color:yellow;}
h1 {font-size:36pt;}
h2 {color:blue;}
p {margin-left:50px;}
</style>
</head>
<body>
<h1>This header is 36 pt</h1>
<h2>This header is blue</h2>
<p>This paragraph has a left margin of 50 pixels</p>
</body>
</html>
To assign more than one kind of style information at the same time, separate the styles with
semicolon.
Example 3:
<style>
body{font: 10pt times; color: black; margin-left: 1in; margin-right: 1in}
</style>
An external style sheet to a document or documents on a site. To link a page to this style sheet
use the link element.
Ex: <link ref=style type=”text/css” href=”http://www.google.com/mystyle.css”>
Property Values:
em – overall height of current font <style = font-size: 2em>
px – pixels < style = font-size: 8px>
in – inches < style = font-size: -5in>
URL:
When URL are used as a property value, specify the keyword URL followed by the actual URL
inside parenthesis.
Ex: <body style=”background-image: url (….)”>
Image:
text-decoration underline|overline|line-through|blink
text-transform capitalize|uppercase|lowercase
15. Write a short note on Features of CSS? (6 MARKS)
A Cascading Style Sheets (CSS) file can contain positioning, layout, font, colors and style
information for an entire web site. The file can be referenced by each html file on the site.
CSS is a means of separating the content of an html document from the style and layout of that
document.
File Size
Probably the mostly useful feature of CSS is that all of the style and layout is removed from
the html, so the html page size is very much smaller. The CSS file is downloaded just once by the
visitor's browser and re-used for different pages on a web site. This reduces the bandwidth
requirements for your server and also ensures a faster download for your visitors.
Search Engines
A search engine robot will normally consider the content in the start of your html code is
more important than the text towards the end of the code. For a table based page the contents of the
navigation bar will normally show up as the page description in search engine results. With a CSS
page the navigation can be moved to the bottom of the source code, so the search engine displays
your content instead of your navigation.
Accessibility
Separating style from content makes life very easy for visitors who prefer to view only the
content of a web page, or to modify the content. These could be blind or partially sighted people who
might use a screen reader to interpret a page.
Consistency
Layout and position of navigation can be completely consistent across a site. This was
previously possible only using frame.
Easy maintenance
To change the style of an element looks across the whole site, you only have to make an edit in one
place.
Browser Compatibility
Browser compatibility is very important and CSS addresses this issue nicely. When you
decide to use CSS, you will find that it will improve the characteristic of your website while securing
your visitors with the capacity to view your website as precisely as you have designed it to be.
Appearance
CSS makes it easy to improve the appearance of a website by allowing you to create a much
more stylish website since CSS offers a wide array of expressive style capableness. With CSS, you will
actually obtain more control over your website's visual aspect. Now, designers can orchestrate the
styles and design of several web pages in a flash.
Bandwidth Savings
Once CSS takes apart your websites content from its design language, you will trim down
your file transfer magnitude significantly. These Bandwidth savings are considerable figures of
insignificant tags that are distracted from a multitude of pages. This will leave less, but more
significant captions, listings and paragraphs.
CSS Selectors:
CSS selectors allow you to select and manipulate HTML elements.
CSS selectors are used to "find" (or select) HTML elements based on their id, class, type,
attribute, grouping and more.
Example:
p{
text-align: center;
color: red;
}
2. The id Selector:
The id selector uses the id attribute of an HTML element to select a specific element.
An id should be unique within a page, so the id selector is used if you want to select a single,
unique element.
To select an element with a specific id, write a hash character, followed by the id of the
element.
The style rule below will be applied to the HTML element with id="para1":
Example:
#para1 {
text-align: center;
color: red;
}
</style>
In the example below, all HTML elements with class="center" will be red and center-aligned:
Example1:
.center{
text-align: center;
color: red;
}
You can also specify that only specific HTML elements should be affected by a class.
In the example below, all <p> elements with class="center" will be center-aligned:
Example 2:
p.center{
text-align: center;
color: red;
}
4. Grouping Selectors:
Size of the style sheets can be reduced using grouping
One can group selectors in comma-separates list.
If you have elements with the same style definitions, like this:
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
You can group the selectors, to minimize the code.
To group selectors, separate each selector with a comma.
In the example below we have grouped the selectors from the code above:
Example:
h1, h2, p {
text-align: center;
color: red;
}
Con-textual Selectors:
Setting all style properties one can create defaults and then list the expectations.
‘em’ elements within ‘H1’ a different color specify as H1 {color: blue} em {color: red} or H1,
em {color: red}
Em elements within H1 should turn red and the color format.
Several contextual selectors can be grouped together as: H1 B, H2 B, H1 em, H2 em {color:
red}
An external style sheet can be written in any text editor. The file should not contain any html
tags. The style sheet file must be saved with a .css extension.
An example of a style sheet file called "myStyle.css", is shown below:
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Example:
style.css
/*External Style Sheet*/
body {font-family: arial}
a.node {text-decoration: none}
a.hover {text-decoration: underline}
li em {font-weight: bold}
h1, em {text-decoration: underline}
ul {margin-left: 20px}
.ul {font-size: .8em;}
external.html
<html>
<head>
<title> Linking External Style Sheets</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Shopping list for <em> monday</h1>
<ul>
<li>Milk</li>
<li>Bread
<ul>
<li>White Bread</li>
<li>Wheat Bread</li>
</ul>
</li>
<li>Rice</li>
<li>Potato</li>
</ul>
<p><em>Go to the</em>
<a class="nodec" href="http://www.dietel.com">Store</a>
</p>
</body>
</html>
Output:
Example 1:
<head>
<style type="text/css" >
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
Example 2:
<html>
<head>
<title>Style Sheet</title>
<!-- Style Sheet -->
<style type="text/css">
em {font-weight: bold; color: blue}
h1 {font-family: times}
p {font-size: 12px; font-family: arial}
.special {color: blue}
</style>
</head>
<body>
<!-- Class Attribute -->
<h1 class="special"> Web Technology </h1>
<p> Deitel </p>
<h1> Client </h1>
<p class="special"> Server side<em>Computing</em></p>
</body>
</html>
Output:
An inline style may be used to apply a unique style for a single element.
An inline style loses many of the advantages of a style sheet (by mixing content with
presentation). Use this method sparingly!
To use inline styles, add the style attribute to the relevant element. The style attribute can
contain any CSS property.
Example:
The example below shows how to change the color and the left margin of a <h1> element:
<h1 style="color: blue; margin-left: 30px ;"> This is a heading. </h1>
What is JavaScript?
JavaScript is a scripting language mainly used for writing dynamic Web pages. When a script
written in JavaScript is embedded in a Web page, it will be executed by the Web browser on the
client machine.
JavaScript supports functions as first-class functions - Functions are really objects. Like regular
objects, functions can be created during execution, stored in data structure, and passed to other
functions as arguments.
JavaScript is a client – side scripting language for the World Wide Web that is similar to the
syntax of the Java programming language.
JavaScript is designed to provide limited programming functionality.
Why JavaScript?
By executing more web functionality on the user’s machine, webmasters can optimize their
servers to serve more pages.
The decrease in traffic from constant interaction with the server can also improve a server's
performance.
Because the local machine is doing the script processing, the user can view web pages much
faster.
JavaScript Syntax:
A simple JavaScript program:
<html>
<head>
<Title> Hello World </Title>
</head>
<body>
<script language=“javascript”>
document.write(“Hello,World wide web”);
</script>
</body>
</html>
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been
embedded in Netscape, Internet Explorer, and other web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript language.
JavaScript is a lightweight, interpreted programming language.
Designed for creating network-centric applications.
Complementary to and integrated with Java.
Complementary to and integrated with HTML.
Open and cross-platform
Client-side JavaScript:
Client-side JavaScript is the most common form of the language. The script should be
included in or referenced by an HTML document for the code to be interpreted by the
browser.
It means that a web page need not be a static HTML, but can include programs that interact
with the user, control the browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-
side scripts. For example, you might use JavaScript to check if the user has entered a valid e-
mail address in a form field.
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:
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.
Limitation s of JavaScript:
The JavaScript as a full-fledged programming language. It lacks the following important features
Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.
JavaScript cannot be used for networking applications because there is no such support
available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.
JavaScript is a lightweight, interpreted programming language that allows you to build
interactivity into otherwise static HTML pages.
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.
JavaScript can be placed in the <body> and the <head> sections of an HTML page.
The <script> tag alerts the browser program to start interpreting all the text between these
tags as a script.
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>
Output:
This code will produce the following result –
Hello World!
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.
Comments in JavaScript:
JavaScript supports both C-style and C++-style comments.
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.
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this
as a single-line comment, just as it does the // comment.
The HTML comment closing sequence --> is not recognized by JavaScript so it should be
written as //-->.
P a g e | 88 WEB TECHNOLOGY DEPARTMENT OF CSE
MANAKULA VINAYAGAR INSTITUTE OF TECHNOLOGY
Example:
The following example shows how to use comments in JavaScript.
<script language="javascript" type="text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
JavaScript Variables:
JavaScript variables are containers for storing data values.
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.
You can also declare multiple variables with the same var keyword as follows –
<script type="text/javascript">
var money, name;
</script>
JavaScript Identifiers:
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
JavaScript identifiers are case-sensitive.
Identifiers can be short names (like x and y), or more descriptive names (age, sum,
totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter.
Names can also begin with $ and _.
Names are case sensitive (y and Y are different variables).
Reserved words (like JavaScript keywords) cannot be used as names.
Storing a value in a variable is called variable initialization. You can do variable initialization at
the time of variable creation or at a later point in time when you need that variable.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For
another variable, you can assign a value at the time of initialization as follows.
<script type="text/javascript">
var name = "Ali";
var money;
money = 2000.50;
</script>
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.
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.
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>
Output:
This produces the following result –
local
JavaScript is a dynamic type language, means you don't need to specify type of the variable because
it is dynamically used by JavaScript engine. You need to use var here to specify the data type.
It can hold any type of values such as numbers, strings etc.
For example:
var a=40; //holding number
var b="Rahul"; //holding string
There are five types of primitive data types in JavaScript. They are as follows:
Example:
var carName = "Volvo XC60"; //Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example:
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside double quotes
var answer = 'He is called "Johnny"'; // Double quotes inside single quotes
Example:
var x1 = 34.00; // Written with decimals
var x2 = 34; // Written without decimals
Extra-large or extra small numbers can be written with scientific (exponential) notation:
Example:
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
Example:
var x = true;
var y = false;
(iv) Undefined:
In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.
Example:
var person; // Value is undefined, type is undefined
Any variable can be emptied, by setting the value to undefined. The type will also be undefined.
Example:
var car = ""; // The value is "", the typeof is string
(vi) Null:
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
Example:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.
The following code declares (creates) an array called cars, containing three items (car names):
Example:
var cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
Syntax:
/pattern/modifiers;
Example:
var patt = /w3schools/i
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
Conditional statements are used to perform different actions based on different conditions.
The if Statement:
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax:
if (condition)
{
block of code to be executed if the condition is true
}
Example:
Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18)
{
greeting = "Good day";
}
Syntax:
if (condition)
{
block of code to be executed if the condition is true
}
else
{
block of code to be executed if the condition is false
}
Example:
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
Syntax:
if (condition1)
{
block of code to be executed if condition1 is true
}
else if (condition2)
{
block of code to be executed if the condition1 is false and condition2 is true
}
else
{
block of code to be executed if the condition1 is false and condition2 is false
}
Example:
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than
20:00, create a "Good day" greeting, otherwise a "Good evening":
if (time < 10)
{
greeting = "Good morning";
}
else if (time < 20)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
Arithmetic Operators:
Arithmetic operators are used to perform arithmetic on numbers (literals or variables).
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
Comparison Operators:
JavaScript supports the following comparison operators.
Operator Description
== Equal
!= Not Equal
> Greater than
< Less than
>= Greater than or Equal
to
<= Less than or Equal to
Operator Description
&& Logical AND
|| Logical OR
! Logical NOT
Bitwise Operators:
JavaScript supports the following bitwise operators.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Not
<< Left Shift
>> Right Shift
>>> Right shift with Zero
Assignment Operators:
JavaScript supports the following assignment operators.
Operator Description
= x=y
+= x+=y
-= x-=y
*= x *= y
/= x /= y
%= x %= y
Miscellaneous 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.
Example:
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 />";
Output:
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
typeof operator:
The typeof operator is a unary operator that is placed before its single operand, which can
be of any type. Its value is a string indicating the data type of the operand.
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.
The list of the return values for the typeof Operator.
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 />";
Output:
Result => B is String
Result => A is Numeric
String literals:
A string literal is zero or more characters, either enclosed in single quotation (') marks
or double quotation (") marks. You can also use + operator to join strings. The following are
the examples of string literals:
i. string1 = "w3resource.com"
ii. string1 = 'w3resource.com'
iii. string1 = "1000"
iv. string1 = "google" + ".com"
In addition to ordinary characters, you can include special characters in strings, as shown in the
following table.
string1 = "First line. \n Second line."
Character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\' Single quote
\" Double quote
\\ Backslash character
(\)
Array literals
In Javascript an array literal is a list of expressions, each of which represents an array
element, enclosed in a pair of square brackets ' [ ] ' .
When an array is created using an array literal, it is initialized with the specified values as its
elements, and its length is set to the number of arguments specified. If no value is supplied it creates
an empty array with zero length.
Integer literals:
An integer must have at least one digit (0-9).
No comma or blanks are allowed within an integer.
It does not contain any fractional part.
It can be either positive or negative, if no sign precedes it is assumed to be positive.
The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or
"-").
Example:
8.2935
-14.72
12.4e3 [ Equivalent to 12.4 x 103 ]
4E-3 [ Equivalent to 4 x 10-3 => .004 ]
Boolean literals:
The Boolean type has two literal values:
true
false
Object literals:
An object literal is zero or more pairs of comma separated list of property names and associated
values, enclosed by a pair of curly braces.
Syntax rules:
Object literals maintain the following syntax rules:
There is a colon (:) between property name and value.
A comma separates each property name/value from the next.
There will be no comma after the last property name/value pair.
Function Invocation:
The code inside the function will execute when "something" invokes (calls) the function:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self-invoked)
Function Return:
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after
the invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example:
Calculate the product of two numbers, and return the result:
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
Calling Function:
To invoke a function somewhere later in the script, you would simply need to write the name of that
function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Output:
Click the following button to call the function
Function Parameters:
There is a facility to pass different parameters while calling a function. These passed parameters
can be captured inside the function and any manipulation can be done over those parameters. A
function can take multiple parameters separated by comma.
Example:
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Output:
Click the following button to call the function
Example:
<html>
<head>
<script language="javascript">
function showmessage()
{
alert("How are you");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click Here!" onclick="showmessage()" >
</form>
</body>
</html>
Function starts with the function keyword and code of the function is enclosed in {..} brackets.
Functions are written inside the head section of the html document, because function does not execute
when the page loads. The alert function displays the message "How are you", when you clicked on the
button ("Click Here").
Built-in functions:
The list of the built-in JavaScript functions:
alert() The alert() built-in function displays the alert dialog box.
The confirm() built-in function display the confirmation dialog box. and
confirm()
ask the user to determine from the two option .
The focus() built -in function built the pointed object active and put the
focus()
curser on the text field.
The prompt() built -in function display the prompt dialog box. Inquiring
prompt()
the user for input.
select() The select() built -in function used to select the pointed object.
write() The write() built in function used to write something on the document.
Function arguments:
Through variable you can pass argument to function. The output of the function looks on the
arguments given by you.
Example:
<html>
<head>
<script language="javascript">
function myfunction(text)
{
confirm(text)
}
</script>
</head>
<body>
<form>
<input type="button" onclick="myfunction('Do you want to delete it!')" value="Delete">
<input type="button" onclick="myfunction('Do you want to save it!')" value="Save">
</form>
</body>
</html>
Output:
Inheritance − the capability of a class to rely upon another class (or number of classes) for
some of its properties and methods.
Polymorphism − the capability to write one function or method that works in a variety of
different ways.
Object Properties:
The name:values pairs (in JavaScript objects) are called properties.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Object Definition:
You define (and create) a JavaScript object with an object literal:
Example:
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object definition can span multiple lines:
Example:
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Syntax:
objectName.propertyName
(or)
objectName["propertyName"]
Example:
person.lastName;
person["lastName"];
Syntax:
objectName.methodName()
Example:
name = person.fullName();
Example:
Try the following example; it demonstrates how to create an Object.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Output:
Book name is : Perl
Book author is : Mohtashim
Creating an Array:
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Example:
var cars = ["Saab", "Volvo", "BMW"];
Example:
var cars = new Array("Saab", "Volvo", "BMW");
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Array:
var person = ["John", "Doe", 46];
Objects use names to access its "members". In this example, person.firstName returns John:
Object:
var person = {firstName:"John", lastName:"Doe", age:46};
Examples:
var x = cars.length; // The length property returns the number of elements in cars
var y = cars.sort(); // The sort() method sort cars in alphabetical order
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is
4
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
Adding elements with high indexes can create undefined "holes" in an array:
Example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[10] = "Lemon"; // adds a new element (Lemon) to fruits
30. Explain the JavaScript Built-in Objects with an example? (11 MARKS)
The various Built-in Objects in JavaScript are
1. Math object
2. String object
3. Date object
4. Boolean objects
5. Number objects
6. Array object
7. Regular Expression object
8. Document object
9. Window object
Example:
Math.min(0, 150, 30, 20, -8, -200); // returns -200
Method Description
abs(x) Returns the absolute value of x
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
Syntax:
var mystring = new String(“Hello World”);
Or
var mystring = “Hello World”;
Method Description
charAt() Returns the character at the specified index (position)
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a new joined strings
fromCharCode() Converts Unicode values to characters
indexOf() Returns the position of the first found occurrence of a specified
value in a string
lastIndexOf() Returns the position of the last found occurrence of a specified
value in a string
localeCompare() Compares two strings in the current locale
match() Searches a string for a match against a regular expression, and
returns the matches
replace() Searches a string for a specified value, or a regular expression, and
returns a new string where the specified values are replaced
Method Description
anchor() Creates an anchor
big() Displays a string using a big font
blink() Displays a blinking string
bold() Displays a string in bold
fixed() Displays a string using a fixed-pitch font
fontcolor() Displays a string using a specified color
fontsize() Displays a string using a specified size
italics() Displays a string in italic
link() Displays a string as a hyperlink
small() Displays a string using a small font
strike() Displays a string with a strikethrough
sub() Displays a string as subscript text
sup() Displays a string as superscript text
Date and time processing can be performed based on the computer’s local time zone or based on
World Time Standard’s Coordinated Universal Time (UTC) - formerly called Greenwich Mean
Time (GMT).
There are four ways of instantiating a date:
1. var d = new Date();
2. var d = new Date (milliseconds);
3. var d = new Date (dateString);
4. var d = new Date (year, month, day, hours, minutes, seconds, milliseconds);
Date Methods:
When a Date object is created, a number of methods allow you to operate on it.
Date methods allow you to get and set the year, month, day, hour, minute, second, and
millisecond of objects, using either local time or UTC (universal, or GMT) time.
Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
getTime() Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() Returns the time difference between UTC time and local time, in minutes
getUTCDate() Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear() Returns the year, according to universal time (four digits)
getUTCHours() Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
getUTCMonth() Returns the month, according to universal time (from 0-11)
getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
parse() Parses a date string and returns the number of milliseconds since midnight of
January 1, 1970
Boolean Methods:
Method Description
toString() Converts a boolean value to a string, and returns the result
valueOf() Returns the primitive value of a boolean
Number Methods:
Method Description
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
toPrecision(x) Formats a number to x length
toString() Converts a number to a string
valueOf() Returns the primitive value of a number
Syntax:
var patt=new RegExp(pattern,modifiers);
(or)
var patt=/pattern/modifiers;
pattern specifies the pattern of an expression
modifiers specify if a search should be global, case-sensitive, etc.
Modifiers:
Modifiers are used to perform case-insensitive and global searches:
Method Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than stopping after the first match)
m Perform multiline matching
Brackets:
Brackets are used to find a range of characters:
Method Description
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase z
[A-z] Find any character from uppercase A to lowercase z
[adgk] Find any character in the given set
[^adgk] Find any character outside the given set
(red|blue|green) Find any of the alternatives specified
Meta-characters:
Meta-characters are characters with a special meaning:
Method Description
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
\0 Find a NUL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
\uxxxx Find the Unicode character specified by a hexadecimal number xxxx
Quantifiers:
Method Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of X to Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n Matches any string that is not followed by a specific string n
Method Description
global Specifies if the "g" modifier is set
ignoreCase Specifies if the "i" modifier is set
lastIndex The index at which to start the next match
multiline Specifies if the "m" modifier is set
source The text of the RegExp pattern
Method Description
compile() Compiles a regular expression
exec() Tests for a match in a string. Returns the first match
test() Tests for a match in a string. Returns true or false
When an HTML document is loaded into a web browser, it becomes a document object.
The document object is the root node of the HTML document and the "owner" of all other nodes:
element nodes,
text nodes,
attribute nodes,
Method Description
document.close() Closes the output stream previously opened with
document.open()
document.cookie Returns all name/value pairs of cookies in the document
document.domain Returns the domain name of the server that loaded the
document
document.getElementById() Returns the element that has the ID attribute with the
specified value
document.getElementsByName() Returns a NodeList containing all elements with a specified
name
document.getElementsByTagName() Returns a NodeList containing all elements with the specified
tag name
document.lastModified Returns the date and time the document was last modified
document.open() Opens an HTML output stream to collect output from
document.write()
document.write() Writes HTML expressions or JavaScript code to a document
document.writeln() Adds a newline character after each statement
Method Description
alert() Displays an alert box with a message and an OK button
close() Closes the current window
blur() Removes focus from the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
setInterval() Calls a function or evaluates an expression at specified intervals (in milliseconds)
setTimeout() Calls a function or evaluates an expression after a specified number of
milliseconds
JavaScript Debugging:
A mistake in a program or a script is referred to as a bug.
The process of finding and fixing bugs is called debugging and is a normal part of the
development process.
It is difficult to write JavaScript code without a debugger.
It contains syntax errors, or logical errors, that are difficult to diagnose.
When JavaScript code contains errors, nothing will happen. There are no error messages, and
you will get no indications where to search for errors.
JavaScript Debuggers:
Searching for errors in programming code is called code debugging.
Debugging is not easy. But fortunately, all modern browsers have a built-in debugger.
Built-in debuggers can be turned on and off, forcing errors to be reported to the user.
With a debugger, you can also set breakpoints (places where code execution can be stopped), and
examine variables while the code is executing.
Normally, otherwise follow the steps at the bottom of this page, you activate debugging in your
browser with the F12 key, and select "Console" in the debugger menu.
Example:
<html>
<body>
<h1>My First Web Page</h1>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
The most basic way to track down errors is by turning on error information in your browser. By
default, Internet Explorer shows an error icon in the status bar when an error occurs on the page.
Double-clicking this icon takes you to a dialog box showing information about the specific error that
occurred.
Since this icon is easy to overlook, Internet Explorer gives you the option to automatically show
the Error dialog box whenever an error occurs.
To enable this option, select Tools → Internet Options → Advanced tab. and then finally check
the "Display a Notification About Every Script Error" box option as shown below.
Error Notifications:
Error notifications that show up on Console or through Internet Explorer dialog boxes are the
result of both syntax and runtime errors. These error notifications include the line number at which the
error occurred.
Chrome
Open the browser.
From the menu, select tools.
From tools, choose developer tools.
Finally, select Console.
Internet Explorer
Open the browser.
Syntax:
var patt=new RegExp(pattern,modifiers);
or
var patt=/pattern/modifiers;
RegExp Modifiers:
i. Modifiers are used to perform case-insensitive and global searches.
ii. The i modifier is used to perform case-insensitive matching.
iii. The g modifier is used to perform a global match (find all matches rather than stopping after the
first match).
Example 1:
Do a case-insensitive search for "w3schools" in a string:
var str="Visit W3Schools";
var patt1=/w3schools/i;
The marked text below shows where the expression gets a match:
W3Schools
Example 2:
Do a global search for "is":
The marked text below shows where the expression gets a match:
Is this all there is?
Example 3
Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;
The marked text below shows where the expression gets a match:
Is this all there is?
test ():
The test () method searches a string for a specified value, and returns true or false, depending on
the result.
The following example searches a string for the character "e":
Example:
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
true
exec():
The exec() method searches a string for a specified value, and returns the text of the found value.
If no match is found, it returns null.
Example:
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
var str = "Visit W3Schools";
var n = str.search(/w3schools/i);
Example:
Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:
var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "W3Schools");