Mean Stack Technologies Full Notes | PDF | File Transfer Protocol | Networking
0% found this document useful (0 votes)
399 views

Mean Stack Technologies Full Notes

Mean Stack Technoloy Lecture Notes II MTech JNTUK

Uploaded by

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

Mean Stack Technologies Full Notes

Mean Stack Technoloy Lecture Notes II MTech JNTUK

Uploaded by

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

UNIT I: Introduction to Web: Internet and World Wide Web, Domain name service, Protocols: HTTP, FTP,

SMTP. Html5 concepts, CSS3, Anatomy of a web page. XML: Document type Definition, XML schemas,
Document object model, XSLT, DOM and SAX Approaches

Internet and World Wide Web

1. Internet :
The internet is a globally connected network system facilitating worldwide communication and access to data resources
through a huge collection of personal, public, business, academic and government networks. it’s gov erned by agencies
just like Internet Assigned Numbers Authority (or IANA) that establish universal protocols.
2. World Wide Web (WWW) :
World Wide Web (WWW), byname Web, is leading information retrieval service of web (the worldwide computer
network). Online gives users access to a huge array of documents that are connected to every other by means of
hypertext or hypermedia links—i.e., hyperlinks, electronic connections that link related pieces of data so as to permit a
user quick access to them. Hypertext allows the user to pick a word or phrase from text and thereby access other
documents that contain additional information concerning that word or phrase.

Difference between Internet and WWW

S.No. INTERNET WWW

Internet is a global WWW stands for World


1
network of networks. wide Web.

World Wide Web which


Internet is a means of
is a collection of
connecting a computer
2 information which is
to any other computer
accessed via the
anywhere in the world.
Internet.

WWW is service on top


3 Internet is infrastructure.
of that infrastructure.

Web can be viewed as


Internet can be viewed
4 collection of books on
as a big book-store.
that store.

At some advanced level, At some advanced


to understand we can level, to understand we
5
think of the Internet as can think of the WWW
hardware. as software.

WWW is more software-


Internet is primarily
6 oriented as compared to
hardware-based.
the Internet.

English scientist Tim


It is originated
7 Berners-Lee invented
sometimes in late 1960s.
the World Wide Web in

Page 1
1989.

Internet is superset of WWW is a subset of the


8
WWW. Internet.

The first version of the


In the beginning WWW
9 Internet was known as
was known as NSFNET.
ARPANET.

10 Internet uses IP address. WWW uses HTTP.

Domain name service

An application layer protocol defines how the application processes running on different systems, pass the messages to each other.

o DNS stands for Domain Name System.


o DNS is a directory service that provides a mapping between the name of a host on the network and its numerical address.
o DNS is required for the functioning of the internet.
o Each node in a tree has a domain name, and a full domain name is a sequence of symbols specified by dots.
o DNS is a service that translates the domain name into IP addresses. This allows the users of networks to utilize user-friendly names
when looking for other hosts instead of remembering the IP addresses.
o For example, suppose the FTP site at EduSoft had an IP address of 132.147.165.50, most people would reach this site by specifying
ftp.EduSoft.com. Therefore, the domain name is more reliable than IP address.

DNS is a TCP/IP protocol used on different platforms. The domain name space is divided into three different sections: generic domains,
country domains, and inverse domain.

Generic Domains

o It defines the registered hosts according to their generic behavior.


o Each node in a tree defines the domain name, which is an index to the DNS database.
o It uses three-character labels, and these labels describe the organization type

Page 2
Label Description

aero Airlines and aerospace companies

biz Businesses or firms

com Commercial Organizations

coop Cooperative business Organizations

edu Educational institutions

gov Government institutions

info Information service providers

int International Organizations

mil Military groups

museum Museum & other nonprofit organizations

name Personal names

net Network Support centers

org Nonprofit Organizations

pro Professional individual Organizations

Country Domain

The format of country domain is same as a generic domain, but it uses two-character country abbreviations (e.g., us for the United
States) in place of three character organizational abbreviations.

Inverse Domain

The inverse domain is used for mapping an address to a name. When the server has received a request from the client, and the server
contains the files of only authorized clients. To determine whether the client is on the authorized list or not, it sends a query to the DNS
server and ask for mapping an address to the name.

Page 3
Working of DNS

o DNS is a client/server network communication protocol. DNS clients send requests to the. server while DNS servers send responses
to the client.
o Client requests contain a name which is converted into an IP address known as a forward DNS lookups while requests containing
an IP address which is converted into a name known as reverse DNS lookups.
o DNS implements a distributed database to store the name of all the hosts available on the internet.
o If a client like a web browser sends a request containing a hostname, then a piece of software such as DNS resolver sends a
request to the DNS server to obtain the IP address of a hostname. If DNS server does not contain the IP address associated wi th a
hostname, then it forwards the request to another DNS server. If IP address has arrived at the resolver, which in turn completes the
request over the internet protocol.

Protocols: HTTP, FTP, SMTP

HTTP:

o HTTP stands for HyperText Transfer Protocol.


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

Features of HTTP:

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

HTTP Transactions

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

Messages

HTTP messages are of two types: request and response. Both the message types follow the same message format.

Request Message: The request message is sent by the client that consists of a request line, headers, and sometimes a body.

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

Uniform Resource Locator (URL)

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

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

FTP

o FTP stands for File transfer protocol.


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

Objectives of FTP

o It provides the sharing of files.


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

Why FTP?

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

Mechanism of FTP

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

There are two types of connections in FTP

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

FTP Clients

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

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

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

SMTP

o SMTP stands for Simple Mail Transfer Protocol.


o SMTP is a set of communication guidelines that allow software to transmit an electronic mail over the internet is called Simple
Mail Transfer Protocol.
o It is a program used for sending messages to other computer users based on e-mail addresses.
o It provides a mail exchange between users on the same or different computers, and it also supports:
o It can send a single message to one or more recipients.
o Sending message can include text, voice, video or graphics.
o It can also send the messages on networks outside the internet.
o The main purpose of SMTP is used to set up communication rules between servers. The servers have a way of identifying
themselves and announcing what kind of communication they are trying to perform. They also have a way of handling the errors
such as incorrect email address. For example, if the recipient address is wrong, then receiving server reply with an error message of
some kind.

Page 7
Components of SMTP

o First, we will break the SMTP client and SMTP server into two components such as user agent (UA) and mail transfer agent (MTA ).
The user agent (UA) prepares the message, creates the envelope and then puts the message in the envelope. The mail transfer
agent (MTA) transfers this mail across the internet.

o SMTP allows a more complex system by adding a relaying system. Instead of just having one MTA at sending side and one at
receiving side, more MTAs can be added, acting either as a client or server to relay the email.

o The relaying system without TCP/IP protocol can also be used to send the emails
to users, and this is achieved by the use of the mail gateway. The mail gateway is
a relay MTA that can be used to receive an email.

Page 8
Working of SMTP

1. Composition of Mail: A user sends an e-mail by composing an electronic mail message using a Mail User Agent (MUA). Mail User
Agent is a program which is used to send and receive mail. The message contains two parts: body and header. The body is the
main part of the message while the header includes information such as the sender and recipient address. The header also
includes descriptive information such as the subject of the message. In this case, the message body is like a letter and header is
like an envelope that contains the recipient's address.
2. Submission of Mail: After composing an email, the mail client then submits the completed e-mail to the SMTP server by using
SMTP on TCP port 25.
3. Delivery of Mail: E-mail addresses contain two parts: username of the recipient and domain name. For
example, vivek@gmail.com, where "vivek" is the username of the recipient and "gmail.com" is the domain name.
If the domain name of the recipient's email address is different from the sender's domain name, then MSA will send the mail to the
Mail Transfer Agent (MTA). To relay the email, the MTA will find the target domain. It checks the MX record from Domain Name
System to obtain the target domain. The MX record contains the domain name and IP address of the recipient's domain. Once the
record is located, MTA connects to the exchange server to relay the message.
4. Receipt and Processing of Mail: Once the incoming message is received, the exchange server delivers it to the incoming server
(Mail Delivery Agent) which stores the e-mail where it waits for the user to retrieve it.
5. Access and Retrieval of Mail: The stored email in MDA can be retrieved by using MUA (Mail User Agent). MUA can be accessed
by using login and password.

Html5 concepts

HTML5 is the latest version of HTML, the markup language used to build structure or content on World Wide
Web. HTML5 is the latest web standard by W3C. Earlier HTML was used only to build webpage structure,
but HTML5 is a full on package to build websites, handle presentation, add functionalities and Web APIs.

HTML5 is the recommended version to build modern web applications as it is light and fastest version
of Hypertext Mark up Language, the code that describes web pages. HTML5 was formed in 2011.

Page 9
HTML5 Stack
Html5 is the combination of three web technologies:→

HTML → to build webpage structure,


CSS → to enhance look and feel( presentation layer), and
Javascript → to add functionality to HTML elements.

The term HTML5 means not only HTML, it is a combination of HTML, CSS and Javascript with APIs. For
example, drawing and animation using canvas, offline storage, microdata, audio and video, drag and
drop, geolocation, embedded fonts, web APIs etc. HTML5 includes new semantic tags and some old tags

HTML + CSS + JAVASCRIPT = HTML5

Why HTML5
HTML5 has been designed to deliver almost everything you'd want to do on web without requiring additional
software such as browser plugins. It does everything from animation to apps, music to movies, and can also
be used to build complicated web applications that run in your browser.

HTML5 isn't proprietary, so you don't need to pay royalties to use it. It's also cross-platform, which means it
doesn't care whether you're using a tablet or a smart phone, a net-book, notebook, ultra-book or a Smart
TV if your browser supports HTML5, it should work flawlessly.

HTML5 Changed Elements


These elements were already there in HTML4/XHTML. But in HTML5, the definition or usage has been changed.

1. a tag is now Hyperlink, not anchor


2. a tag <a> can have both inline and block child elements.
3. b tag is offset text conventionally styled in bold
4. i tag is offset text conventionally styled in italic
5. u tag is offset text conventionally styled with an underline
6. cite tag is cited title of work
7. hr tag is Thematic Break, not Horizontal Rule
8. input tag is Input Control.
9. meta tag is meta data.
10. s tag is struck text.
11. small tag is small print.
12. dl tag is description list, not definition list.

HTML Versions

Year Achievement

1989 HTML Formed

Page 10
Year Achievement

1995 HTML 2

1995 CSS

1995 JAVASCRIPT

1997 HTML 4

1998 CSS 2

2000 XHTML 1

2001 XHTML 1.1

2009 HTML5

2015 HTML5.1

2017 HTML5.2

HTML5 Browsers Support


HTML5 is supported by latest browsers only. The first browser support of html5 was seen in 2011. Here is the
list of supported browsers for html5.

 Chrome 4 and above


 Firefox 3.6 and above
 Opera 11 and latest versions
 Safari 5.1 for Mac, Iphones and Ipads
 Internet Explorer 9 and above
 Edge 12 and above Browsers

HTML5 Browsers Support


HTML5 is supported by latest browsers only. The first browser support of html5 was seen in 2011. Here is the
list of supported browsers for html5.

 Chrome 4 and above


 Firefox 3.6 and above
 Opera 11 and latest versions
 Safari 5.1 for Mac, Iphones and Ipads
 Internet Explorer 9 and above

Page 11
 Edge 12 and above Browsers

 HTML5 Doctype
 HTML5 Doctype is short, and easy to remember. Unlike, HTML4 and XHTML, there is no DTD. As per W3C,
same doctype will be used in later versions of HTML.

 <!DOCTYPE HTML> // New and shorter Doctype, no DTD Required

 HTML5 Template
 Default Template for HTML5 based websites.
 <!doctype html>
 <html lang="en"> //lang embedded in html
 <head>

 <title>HTML5 Page</title>
 <meta charset="utf-8"> //Short charset meta tag
 <link href="style.css" rel="stylesheet"> //No Type attribute
 <script src="file.js"></script> //No Type attribute required
 </head>

 <body>
 <h1>My First HTML5 page.</h1>
 </body>

 </html>

HTML5 Semantic Elements


HTML5 includes new tags or new elements. These tags or elements includes new media tags, semantic tags,
svg, canvas etc. HTML5 is now more semantic than html4. Here is a list of new tags in html5, with their
meaning, use and example..

HTML5 New Tags List


 Article

 Section

 Aside

 Details

 Summary

 Time

 BDI

 Command

 Figure

 Figcaption

 Picture

 Footer

 Header

 Mark

 Meter

Page 12
 Nav

 Progress

 HTML5 Canvas

 HTML5 SVG

 Wbr

 Article
 An article defines a complete or an Self Contained composition in a webpage. An Article could be a Blog
post, forum, newspaper article, an independent content, user comment.
 An article must have an heading or subheading, i.e h1-h6

 <article>
 <h2>Heading for Article</h2>
 </article>

 Section
 An Section represents an generic section of a document. Section could be various sections of an article with
heading.
 An section can include various chapters of a book or various webpage sections,
like introductions, content, contact info etc.
 An section must have an heading. h2-h6

 <article>
 <h1>Article Heading</h1>
 <section>
 <h2>Subheading 1 for Section</h2>
 </section>
 <section>
 <h2>Subheading 2 for Section</h2>
 </section>
 </article>

Aside
Aside is the sidebar of a container. The content inside aside is related to content next to it. Aside could be
sibling of div, section or article. But the content inside aside is relevant to adjacent sibling.

aside is use for links, sidebars, for ads and other content we want to put aside.

Aside Example

<aside>

<p>Aside</p>

</aside>

Details
Defines additional details that the user can view or hide. Content inside <details> is hidden. Only <summary> is
visible to user. User can click on summary to view details .

Page 13
Summary
Summary is the visible part of details. Except summary, everything details is hidden.

Details Example
Click to see details

<details>

<summary>Click To See</summary>

<p>Hello</p>

</details>

Details Example with open


An additional open attribute can open details on page load..

Click to see detailsHello

<details open>

<summary>Click To See</summary>

<p>Hello</p>

</details>

Time
Time tag is an inline level element, used to represents a time or exact date in Gregorian calender.

Time Tag Example


New Batch Timings are 10:00 AM.

<p> New Batch Timings are <time>10:00</time> AM.</p>

Time Tag with datetime


An additional datetime attribute can write datetime in ISO String.

New Batch Timings are 10:00 AM.

Page 14
<p> New Batch Timings are <time datetime="2017-12-08T10:00">10:00</time> AM.</p>

Bi-Directional Isolation (BDI)


BDI or Bi-Directional Isolation tag is used to add text with opposite direction and to isolate from other text if direction is
unknown.

<p>Hello friend</p>

<p lang="he"> <bdi>‫<שלום‬/bdi> friend</p>

Command
Command Tag is an obsolete element of Html5. It represents a command, which a user can invoke.

<command>

<command type="command">

<command type="radio">

<command type="checkbox">

command tag is obsolete now. Even major browsers doesn't support command tag. Try avoid it.

Figure
Figure tag Specifies self-contained content, like images, illustrations, diagrams, code listings, etc. Figure can
have figcaption child to explain what figure is showing.

Figcaption
Figcaption is the caption of figure element.

<figure>

<img src="img/path" alt="...">

<figcaption> caption for image</figcaption>

</figure>

Picture
HTML5 picture tag is used to show either high or low resolution image for Desktop, Mobile or particular device. We can
set two or more different images for different screens or resolutions, and browser will load a single resource from server,

Page 15
based on criteria. Like High quality images for Macbook and Full HD screens, medium quality images for normal screens
and small image for mobiles.

Picture tags can enhance performance of a website.

<picture>

<source srcset="img/logo-sm.png" media="(max-width: 460px)">

<img src="img/logo.png" alt="Tech Altum Logo">

</picture>

To test picture tag, minimize your browsers screen, or if using smartphone, use landscape and portrait mode to test.

HTML5 Removed Tags


With HTML5, some presentational tags are removed. These tags still get browser support, but W3C validator shows
errors. Here is a list of some removed elements in html5.

HTML5 Removed Tags or Elements

<acronym>

<applet>

<basefont>

<big>

<center>

<dir>

<font>

<frame>

<frameset>

<marquee>

<noframes>

<strike>

<tt>

Page 16
HTML5 New Attributes
HTML5 introduced new attributes. All these attributes are functional and easy to use. HTML5 also removed so
many attributes as they are presentational, not functional.
html5-removed-attributes. Here is a list of html5 attributes.

HTML5 Attributes List

 Async
 contenteditable
 data
 datetime
 download
 draggable
 hidden
 list
 max
 min
 minlength
 open

 role

CSS3

CSS stands for Cascading Style Sheets. CSS is a standard style sheet language used for describing the presentation (i.e. the layout
and formatting) of the web pages.

Prior to CSS, nearly all of the presentational attributes of HTML documents were contained within the HTML markup (specifically
inside the HTML tags); all the font colors, background styles, element alignments, borders and sizes had to be explicitly described
within the HTML.

As a result, development of the large websites became a long and expensive process, since the style information were repeatedly
added to every single page of the website.

To solve this problem CSS was introduced in 1996 by the World Wide Web Consortium (W3C), which also maintains its standard. CSS
was designed to enable the separation of presentation and content. Now web designers can move the formatting information of the
web pages to a separate style sheet which results in considerably simpler HTML markup, and better maintainability.

CSS3 is the latest version of the CSS specification. CSS3 adds several new styling features and improvements to enhance the web
presentation capabilities.

What You Can Do with CSS


There are lot more things you can do with CSS.

 You can easily apply same style rules on multiple elements.


 You can control the presentation of multiple pages of a website with a single style sheet.
 You can present the same page differently on different devices.
 You can style dynamic states of elements such as hover, focus, etc. that isn't possible otherwise.
 You can change the position of an element on a web page without changing the markup.
 You can alter the display of existing HTML elements.

Page 17
 You can transform elements like scale, rotate, skew, etc. in 2D or 3D space.
 You can create animations and transitions effects without using any JavaScript.
 You can create print friendly version of your web pages.

The list does not end here, there are many other interesting things that you can do with CSS. You will learn about all of them in
detail in upcoming chapters.

Advantages of Using CSS


The biggest advantage of CSS is that it allows the separation of style and layout from the content of the document. Here are some
more advantages, why one should start using CSS?

 CSS Save Lots of Time — CSS gives lots of flexibility to set the style properties of an element. You can write CSS once; and then the
same code can be applied to the groups of HTML elements, and can also be reused in multiple HTML pages.
 Easy Maintenance — CSS provides an easy means to update the formatting of the documents, and to maintain the consistency
across multiple documents. Because the content of the entire set of web pages can be easily controlled using one or more style
sheets.
 Pages Load Faster — CSS enables multiple pages to share the formatting information, which reduces complexity and repetition in
the structural contents of the documents. It significantly reduces the file transfer size, which results in a faster page loading.
 Superior Styles to HTML — CSS has much wider presentation capabilities than HTML and provide much better control over the
layout of your web pages. So you can give far better look to your web pages in comparison to the HTML presentational elements
and attributes.
 Multiple Device Compatibility — CSS also allows web pages to be optimized for more than one type of device or media. Using
CSS the same HTML document can be presented in different viewing styles for different rendering devices such as desktop, cell
phones, etc

Including CSS in HTML Documents


CSS can either be attached as a separate document or embedded in the HTML document itself. There are three methods of
including CSS in an HTML document:

 Inline styles — Using the style attribute in the HTML start tag.
 Embedded styles — Using the <style> element in the head section of a document.
 External style sheets — Using the <link> element, pointing to an external CSS file.

In this tutorial we will cover all these three methods for inserting CSS one by one.

Inline Styles
Inline styles are used to apply the unique style rules to an element by putting the CSS rules directly into the start tag. It can be
attached to an element using the style attribute.

The style attribute includes a series of CSS property and value pairs. Each "property: value" pair is separated by a semicolon (;),
just as you would write into an embedded or external style sheets. But it needs to be all in one line i.e. no line break after the
semicolon, as shown here:

Example
<h1 style="color:red; font-size:30px;">This is a heading</h1>
<p style="color:green; font-size:22px;">This is a paragraph.</p>
<div style="color:blue; font-size:14px;">This is some text content.</div>

Using the inline styles are generally considered as a bad practice. As style rules are embedded directly inside the HTML tag, it causes
the presentation to become mixed with the content of the document; which makes the code hard to maintain and negates the
purpose of using CSS.

Embedded Style Sheets

Page 18
Embedded or internal style sheets only affect the document they are embedded in.

Embedded style sheets are defined in the <head> section of an HTML document using the <style> element. You can define any
number of <style> elements in an HTML document but they must appear between the <head> and </head> tags. Let's take a look at
an example:

Example
<!DOCTYPE html>
<html lang="en">
<head>
<title>My HTML Document</title>
<style>
body { background-color: YellowGreen; }
p { color: #fff; }
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph of text.</p>
</body>
</html>

External Style Sheets


An external style sheet is ideal when the style is applied to many pages of the website.

An external style sheet holds all the style rules in a separate document that you can link from any HTML file on your site. External
style sheets are the most flexible because with an external style sheet, you can change the look of an entire website by changing just
one file.

You can attach external style sheets in two ways — linking and importing.

Linking External Style Sheets


Before linking, we need to create a style sheet first. Let's open your favorite code editor and create a new file. Now type the
following CSS code inside this file and save it as "style.css".

Example

body {
background: lightyellow;
font: 18px Arial, sans-serif;
}
h1 {
color: orange;
}

An external style sheet can be linked to an HTML document using the <link> tag. The <link> tag goes inside the <head> section, as
you can see in the following example:

<!DOCTYPE html>

<html lang="en">

<head> <title>My HTML Document</title>

<link rel="stylesheet" href="css/style.css">

</head>

<body> <h1>This is a heading</h1>

<p>This is a paragraph of text.</p>

</body> </html>

Page 19
What is Selector?
A CSS selector is a pattern to match the elements on a web page. The style rules associated with that selector will be applied to the
elements that match the selector pattern.

Selectors are one of the most important aspects of CSS as they allow you to target specific elements on your web page in vari ous
ways so that they can be styled.

Several types of selectors are available in CSS, let's take a closer look at them:

Universal Selector
The universal selector, denoted by an asterisk (*), matches every single element on the page.

The universal selector may be omitted if other conditions exist on the element. This selector is often used to remove the default
margins and paddings from the elements for quick testing purpose.

Let's try out the following example to understand how it basically works:

Example
Try this code »

* {
margin: 0;
padding: 0;
}
The style rules inside the * selector will be applied to every element in a document.

Note: It is recommended not to use the universal selector (*) too often in a production environment, since this selector matches
every element on a web page that puts too much of unnecessary pressure on the browsers. Use element type or class selector
instead.

Element Type Selectors


An element type selector matches all instance of the element in the document with the corresponding element type name. Let's try
out an example to see how it actually works:

Example
Try this code »

p {
color: blue;
}
The style rules inside the p selector will be applied on every <p> element (or paragraph) in the document and color it blue, regardless
of their position in the document tree.

Id Selectors
The id selector is used to define style rules for a single or unique element.

The id selector is defined with a hash sign (#) immediately followed by the id value.

Example
Try this code »

Page 20
#error {
color: red;
}
This style rule renders the text of an element in red, whose id attribute is set to error.

Note: The value of an id attribute must be unique within a given document — meaning no two elements in your HTML document
can share the same id value.

Class Selectors
The class selectors can be used to select any HTML element that has a class attribute. All the elements having that class will be
formatted according to the defined rule.

The class selector is defined with a period sign (.) immediately followed by the class value.

Example
Try this code »

.blue {
color: blue;
}
The above style rules renders the text in blue of every element in the document that has class attribute set to blue. You can make it
a bit more particular. For example:

Example
Try this code »

p.blue {
color: blue;
}
The style rule inside the selector p.blue renders the text in blue of only those <p> elements that has class attribute set to blue, and
has no effect on other paragraphs.

Descendant Selectors
You can use these selectors when you need to select an element that is the descendant of another element, for example, if you want
to target only those anchors that are contained within an unordered list, rather than targeting all anchor elements. Let's see how it
works:

Example
Try this code »

ul.menu li a {
text-decoration: none;
}
h1 em {
color: green;
}
The style rules inside the selector ul.menu li a applied to only those <a> elements that contained inside an <ul> element having
the class .menu, and has no effect on other links inside the document.

Similarly, the style rules inside the h1 em selector will be applied to only those <em> elements that contained inside the <h1> element
and has not effect on other <em> elements.

Page 21
Child Selectors
A child selector is used to select only those elements that are the direct children of some element.

A child selector is made up of two or more selectors separated by a greater than symbol ( >). You can use this selector, for instance,
to select the first level of list elements inside a nested list that has more than one level. Let's check out an example to understand
how it works:

Example
Try this code »

ul > li {
list-style: square;
}
ul > li ol {
list-style: none;
}
The style rule inside the selector ul > li applied to only those <li> elements that are direct children of the <ul> elements, and has
no effect on other list elements.

Adjacent Sibling Selectors


The adjacent sibling selectors can be used to select sibling elements (i.e. elements at the same level). This selector has th e syntax like:
E1 + E2, where E2 is the target of the selector.

The selector h1 + p in the following example will select the <p> elements only if both the <h1> and <p> elements share the same
parent in the document tree and <h1> is immediately precedes the <p> element. That means only those paragraphs that come
immediately after each <h1> heading will have the associated style rules. Let's see how this selector actually works:

Example
Try this code »

h1 + p {
color: blue;
font-size: 18px;
}
ul.task + p {
color: #f0f;
text-indent: 30px;
}

General Sibling Selectors


The general sibling selector is similar to the adjacent sibling selector (E1 + E2), but it is less strict. A general sibling selector is made
up of two simple selectors separated by the tilde ( ∼) character. It can be written like: E1 ∼ E2, where E2 is the target of the selector.

The selector h1 ∼ p in the example below will select all the <p> elements that preceded by the <h1> element, where all the elements
share the same parent in the document tree.

Example
Try this code »

h1 ∼ p {
color: blue;
font-size: 18px;
}
ul.task ∼ p {

Page 22
color: #f0f;
text-indent: 30px;
}
There are more sophisticated selectors like attribute selectors, pseudo-classes, pseudo-elements. We will discuss about these
selectors in detail in the upcoming chapters.

Grouping Selectors
Often several selectors in a style sheet share the same style rules declarations. You can group them into a comma-separated list to
minimize the code in your style sheet. It also prevents you from repeating the same style rules over and over again. Let's take a look:

Example
Try this code »

h1 {
font-size: 36px;
font-weight: normal;
}
h2 {
font-size: 28px;
font-weight: normal;
}
h3 {
font-size: 22px;
font-weight: normal;
}
As you can see in the above example, the same style rule font-weight: normal; is shared by the selectors h1, h2 and h3, so it can
be grouped in a comma-separated list, like this:

Example
Try this code »

h1, h2, h3 {
font-weight: normal;
}
h1 {
font-size: 36px;
}
h2 {
font-size: 28px;
}
h3 {
font-size: 22px;
}

Setting Color Property


The color property defines the text color (foreground color in general) of an element.

For instance, the color property specified in the body selector defines the default text color for the whole page. Let's try out the
following example to see how it works:

Example
Try this code »

body {
color: #ff5722;
}
Note: The color property normally inherits the color value from their parent element, except the case of anchor elements. For
example, if you specify color for the body element it will automatically be passed down to the headings, paragraphs, etc.

Page 23
Defining Color Values
Colors in CSS most often specified in the following formats:

 a color keyword - like "red", "green", "blue", "transparent", etc.


 a HEX value - like "#ff0000", "#00ff00", etc.
 an RGB value - like "rgb(255, 0, 0)"

CSS3 has introduced several other color formats such as HSL, HSLA and RGBA that also support alpha transparency. We'll learn
about them in greater detail in CSS3 color chapter.
For now, let's stick to the basic methods of defining the color values:

Color Keywords
CSS defines the few color keywords which lets you specify color values in an easy way.

These basic color keywords are: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and
yellow. The color names are case-insensitive.

Example
Try this code »

h1 {
color: red;
}
p {
color: purple;
}
Modern web browsers however practically support many more color names than what are defined in the CSS standard, but to be on
the safer side you should use hex color values instead.

See the reference on CSS color names, for a complete list of possible color names.

HEX Color Values


Hex (short for Hexadecimal) is by far the most commonly used method of defining color on the web.

Hex represent colors using a six-digit code, preceded by a hash character, like #rrggbb, in which rr, gg, and bb represents the red,
green and blue component of the color respectively.

The value of each component can vary from 00 (no color) and FF (full color) in hexadecimal notation, or 0 and 255 in decimal
equivalent notation. Thus #ffffff represents white color and #000000 represents black color. Let's take a look the following
example:

Example
Try this code »

h1 {
color: #ffa500;
}
p {
color: #00ff00;
}
Note: Hexadecimal or Hex refers to a numbering scheme that uses 16 characters as its base. It uses the numbers 0 through 9 and
the letters A, B, C, D, E and F which corresponds to the decimal numbers 10, 11, 12, 13, 14 and 15 respectively.

Page 24
Tip: If hexadecimal code of a color has value pairs, it can also be written in shorthand notation to avoid extra typing, for example,
the hex color value #ffffff can be also be written as #fff, #000000 as #000, #00ff00 as #0f0, #ffcc00 as #fc0, and so on.

RGB Color Values


Colors can be defined in the RGB model (Red, Green, and Blue) using the rgb() functional notation.

The rgb() function accepts three comma-separated values, which specify the amount of red, green, and blue component of the
color. These values are commonly specified as integers between 0 to 255, where 0 represent no color and 255 represent full or
maximum color.

The following example specifies the same color as in the previous example but in RGB notation.

Example
Try this code »

h1 {
color: rgb(255, 165, 0);
}
p {
color: rgb(0, 255, 0);
}
Note: You can also specify RGB values inside the rgb() function in percentage, where 100% represents full color, and 0% (not simply
0) represents no color. For example, you can specify the red color either as rgb(255, 0, 0) or rgb(100%, 0%, 0%) .

Tip: If R, G, and B are all set to 255, i.e. rgb(255, 255, 255) , the color would be white. Likewise, if all channels are set to 0,
i.e. rgb(0, 0, 0), the color would be black. Play with the RGB values in the following demonstration to understand how it actually
works.

Anatomy of a web page

Starting at the top of the web page, let's go through the anatomy of a web page:

Page Title

The page tile is set using the <title> </title> set of tags in the head section of the html coding. This is the only web page element within the head section
of the web page the visitor will see.

URL (Domain Name)

The URL is the domain name of the website. If the visitor just typed www.domainname.com they would be taken to the home page of the website.

File Name

File name is the web page file name. It cannot contain any spaces! The file name can be written as one long name (e.g. basichtmlarticles.htm), with
hyphens (e.g. basic-html-articles.htm, as shown in the image above) or with underscores (e.g. basic_html_articles.htm).

Page 25
When you create a web page you have to give it a name. The file name has what is called an extension at the end of it.

The extension at the end of the file name tells the browser what kind of file it is. A HTML document would have an extension of .htm or html. If your web
page uses a certain programming language it would have the appropriate extension. e.g. .php is for the PHP programming language, .asp is for the ASP
programming language.

Note: Servers and some browsers will not render (show) your page if you refer to it differently in your links than the way it is actually named. Basic-
Html-Articles.htm is different from basic-html-articles.htm to some servers and browsers. To combat this problem always name your files with lower case
letters. This way you don't have to remember how you capitalized a file name.

Scroll Bars

Scroll bars are on the right side and bottom of the browser window. If there is a scroll bar at the bottom (horizontal scroll bar) your web page content is
too wide for the browser window.

A web page layout should be designed so there is no horizontal scroll bar. You need to test your web page at different resolutions and on different
operating systems to see if the way the page is laid out will result in horizontal scroll bars when viewed at smaller resolut ions or by different operating
systems.

One way to avoid this problem is to use a flexible (fluid) design. A flexible design will adjust to the browser window size. As long as all your elements add
up to less than the browser width there will not be a horizontal scroll bar.

Next, we will look at the web page content portion of the anatomy of a web page.

Header

The header is at the very top of the web page. It usually contains a logo for the website.

Navigation

A website can use a left navigation system, a right navigation system or a navigation system that spans horizontally right under the header or above the
header.

The navigation system of a website has to be consistent throughout the website so the visitor will learn your navigation syst em. Changing the navigation
system from page to page is confusing to the visitor and they will get frustrated and leave!

Page 26
Web Page Content

Web page content includes everything between the <body> and </body> tags. We have already looked at some of the web page cont ent, the header
and navigation system. Also considered web page content is the web page footer (we will discuss this next) and the center section of this page that you
are looking at now.

Footer

The footer is the bottom section of the web page.

This section is where you usually put your copyright notice, link to your privacy policy and your website contact information.

Summary of Anatomy of a Web Page

In this tutorial we have looked at the anatomy of a web page from top to bottom. We started with the page title, moved onto t he website URL and web
page file name, discussed vertical and horizontal scroll bars, then moved onto the web page content. The web page content portion of the anatomy of a
web page consists of everything between the <body> and </body> tags including the header, navigation, center web page content and the web page
footer.

XML: Document type Definition(DTD)

What is a DTD?
DTD stands for Document Type Definition.

A DTD defines the structure and the legal elements and attributes of an XML document.

Valid XML Documents


A "Valid" XML document is "Well Formed", as well as it conforms to the rules of a DTD:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The DOCTYPE declaration above contains a reference to a DTD file. The content of the DTD file is shown and explained below.

XML DTD

Page 27
The purpose of a DTD is to define the structure and the legal elements and attributes of an XML document:

Note.dtd:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

The DTD above is interpreted like this:

 !DOCTYPE note - Defines that the root element of the document is note
 !ELEMENT note - Defines that the note element must contain the elements: "to, from, heading, body"
 !ELEMENT to - Defines the to element to be of type "#PCDATA"
 !ELEMENT from - Defines the from element to be of type "#PCDATA"
 !ELEMENT heading - Defines the heading element to be of type "#PCDATA"
 !ELEMENT body - Defines the body element to be of type "#PCDATA"

Tip: #PCDATA means parseable character data.

Using DTD for Entity Declaration


A DOCTYPE declaration can also be used to define special characters or strings, used in the document:

Example
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE note [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
]>

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>

When to Use a DTD?


With a DTD, independent groups of people can agree to use a standard DTD for interchanging data.

With a DTD, you can verify that the data you receive from the outside world is valid.

You can also use a DTD to verify your own data.

When NOT to Use a DTD?

Page 28
XML does not require a DTD.

When you are experimenting with XML, or when you are working with small XML files, creating DTDs may be a waste of time.

If you develop applications, wait until the specification is stable before you add a DTD. Otherwise, your software might stop working
because of validation errors.

XML schemas

An XML Schema describes the structure of an XML document, just like a DTD.

An XML document with correct syntax is called "Well Formed".

An XML document validated against an XML Schema is both "Well Formed" and "Valid".

XML Schema
XML Schema is an XML-based alternative to DTD:

<xs:element name="note">

<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>

</xs:element>

The Schema above is interpreted like this:

 <xs:element name="note"> defines the element called "note"


 <xs:complexType> the "note" element is a complex type
 <xs:sequence> the complex type is a sequence of elements
 <xs:element name="to" type="xs:string"> the element "to" is of type string (text)
 <xs:element name="from" type="xs:string"> the element "from" is of type string
 <xs:element name="heading" type="xs:string"> the element "heading" is of type string
 <xs:element name="body" type="xs:string"> the element "body" is of type string

XML Schemas are More Powerful than DTD


 XML Schemas are written in XML
 XML Schemas are extensible to additions

Page 29
 XML Schemas support data types
 XML Schemas support namespaces

Why Use an XML Schema?


With XML Schema, your XML files can carry a description of its own format.

With XML Schema, independent groups of people can agree on a standard for interchanging data.

With XML Schema, you can verify data.

XML Schemas Support Data Types


One of the greatest strengths of XML Schemas is the support for data types:

 It is easier to describe document content


 It is easier to define restrictions on data
 It is easier to validate the correctness of data
 It is easier to convert data between different data types

XML Schemas use XML Syntax


Another great strength about XML Schemas is that they are written in XML:

 You don't have to learn a new language


 You can use your XML editor to edit your Schema files
 You can use your XML parser to parse your Schema files
 You can manipulate your Schemas with the XML DOM
 You can transform your Schemas with XSLT

Document object model

The document object represents the whole html document.

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

As mentioned earlier, it is the object of window. So window.document Is same as document

Properties of document object

Page 30
Methods of document object

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

The important methods of document object are as follows:

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.

Accessing field value by document object

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

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

form1 is the name of the form.

name is the attribute name of the input text.

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

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

1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;

Page 31
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>

XSLT
XSL (eXtensible Stylesheet Language) is a styling language for XML.

XSLT stands for XSL Transformations.

This tutorial will teach you how to use XSLT to transform XML documents into other formats (like transforming XML into HTML).

Online XSLT Editor


With our online editor, you can edit XML and XSLT code, and click on a button to view the result.

XSLT Example
<?xml version="1.0"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

XSLT References

Page 32
XSLT Elements

Description of all the XSLT elements from the W3C Recommendation, and information about browser support.

XSLT, XPath, and XQuery Functions

XSLT 2.0, XPath 2.0, and XQuery 1.0, share the same functions library. There are over 100 built-in functions. There are functions
for string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, and more.

XSLT is a language for transforming XML documents.

XPath is a language for navigating in XML documents.

XQuery is a language for querying XML documents.

It Started with XSL


XSL stands for EXtensible Stylesheet Language.

The World Wide Web Consortium (W3C) started to develop XSL because there was a need for an XML-based Stylesheet Language.

CSS = Style Sheets for HTML


HTML uses predefined tags. The meaning of, and how to display each tag is well understood.

CSS is used to add styles to HTML elements.

XSL = Style Sheets for XML


XML does not use predefined tags, and therefore the meaning of each tag is not well understood.

A <table> element could indicate an HTML table, a piece of furniture, or something else - and browsers do not know how to display
it!

So, XSL describes how the XML elements should be displayed.

XSL - More Than a Style Sheet Language


XSL consists of four parts:

 XSLT - a language for transforming XML documents


 XPath - a language for navigating in XML documents
 XSL-FO - a language for formatting XML documents (discontinued in 2013)
 XQuery - a language for querying XML documents

Page 33
With the CSS3 Paged Media Module, W3C has delivered a new standard for document formatting. So, since 2013, CSS3 is
proposed as an XSL-FO replacement.

What is XSLT?
 XSLT stands for XSL Transformations
 XSLT is the most important part of XSL
 XSLT transforms an XML document into another XML document
 XSLT uses XPath to navigate in XML documents
 XSLT is a W3C Recommendation

ADVERTISEMENT

XSLT = XSL Transformations


XSLT is the most important part of XSL.

XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a
browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element.

With XSLT you can add/remove elements and attributes to or from the output file. You can also rearrange and sort elements,
perform tests and make decisions about which elements to hide and display, and a lot more.

A common way to describe the transformation process is to say that XSLT transforms an XML source-tree into an XML result-
tree.

XSLT Uses XPath


XSLT uses XPath to find information in an XML document. XPath is used to navigate through elements and attributes in XML
documents.

If you want to study XPath first, please read our XPath Tutorial.

How Does it Work?


In the transformation process, XSLT uses XPath to define parts of the source document that should match one or more predefined
templates. When a match is found, XSLT will transform the matching part of the source document into the result document.

XSLT Browser Support


All major browsers support XSLT and XPath.

Page 34
XSLT - Transformation
❮ PreviousNext ❯

Example study: How to transform XML into XHTML using XSLT?

The details of this example will be explained in the next chapter.

Correct Style Sheet Declaration


The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or <xsl:transform>.

Note: <xsl:stylesheet> and <xsl:transform> are completely synonymous and either can be used!

The correct way to declare an XSL style sheet according to the W3C XSLT Recommendation is:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

XSLT <xsl:template> Element


❮ PreviousNext ❯

An XSL style sheet consists of one or more set of rules that are called templates.

A template contains rules to apply when a specified node is matched.

The <xsl:template> Element


The <xsl:template> element is used to build templates.

The match attribute is used to associate a template with an XML element. The match attribute can also be used to define a
template for the entire XML document. The value of the match attribute is an XPath expression (i.e. match="/" defines the whol e
document).

Ok, let's look at a simplified version of the XSL file from the previous chapter:

Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

Page 35
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<tr>
<td>.</td>
<td>.</td>
</tr>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

Example Explained
Since an XSL style sheet is an XML document, it always begins with the XML declaration: <?xml version="1.0" encoding="UTF-
8"?>.

The next element, <xsl:stylesheet>, defines that this document is an XSLT style sheet document (along with the version number
and XSLT namespace attributes).

The <xsl:template> element defines a template. The match="/" attribute associates the template with the root of the XML
source document.

The content inside the <xsl:template> element defines some HTML to write to the output.

The last two lines define the end of the template and the end of the style sheet.

The result from this example was a little disappointing, because no data was copied from the XML document to the output. In the
next chapter you will learn how to use the <xsl:value-of> element to select values from the XML elements.

The <xsl:value-of> Element


The <xsl:value-of> element can be used to extract the value of an XML element and add it to the output stream of the
transformation:

Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<tr>
<td><xsl:value-of select="catalog/cd/title"/></td>
<td><xsl:value-of select="catalog/cd/artist"/></td>
</tr>

Page 36
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

The <xsl:for-each> Element


The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set:

Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

XSLT <xsl:sort> Element


❮ PreviousNext ❯

The <xsl:sort> element is used to sort the output.

Where to put the Sort Information


To sort the output, simply add an <xsl:sort> element inside the <xsl:for-each> element in the XSL file:

Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

Page 37
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:sort select="artist"/>
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

The <xsl:if> Element


To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL document.

Syntax
<xsl:if test="expression">
...some output if the expression is true...
</xsl:if>

Where to Put the <xsl:if> Element


To add a conditional test, add the <xsl:if> element inside the <xsl:for-each> element in the XSL file:

Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
<th>Price</th>
</tr>
<xsl:for-each select="catalog/cd">
<xsl:if test="price &gt; 10">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
<td><xsl:value-of select="price"/></td>
</tr>

Page 38
</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

Difference Between DOM and SAX


Difference between DOM and SAX?

DOM SAX

DOM stands for Document SAX stands for the Simple API
Object Model. for XML parsing.

SAX does not need a lot of


DOM needs a lot of memory.
memory.

It is memory inefficient. It is memory efficient.

DOM parser work on the SAX work on the event-based


Document object model. XML parser.

DOM is Faster. SAX is slower.

DOM loads whole XML document SAX load a small part of XML
memory. memory.

It’s not suitable for a large XML It’s suitable for a large XML
file. file.

DOM implements DOM API. SAX impliment SAX API.

It creates internal structure It does not create the first


memory. internal Structure.

Java provides support DOM Java provides support SAX


parsers, and we can parse XML parsers, and we can parse XML

Page 39
files in java using DOM parser. files in java using SAX parser.

Page 40
UNIT II : JavaScript: The Basic of JavaScript: Objects, Primitives Operations and Expressions, Control
Statements, Arrays, Functions, Constructors, Pattern Matching using Regular Expressions. Angular Java
Script Angular JS Expressions: ARRAY, Objects, $eval, Strings, Angular JS Form Validation & Form
Submission, Single Page Application development using Angular JS.

What is JavaScript

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

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

Features of JavaScript

There are following features of JavaScript:

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

History of JavaScript

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

Page 41
Application of JavaScript

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

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

JavaScript Example

1. <script>
2. document.write("Hello JavaScript by JavaScript");
3. </script>

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

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

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

Creating Objects in JavaScript

There are 3 ways to create objects.

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

1) JavaScript Object by object literal

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

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

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

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

1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. document.write(emp.id+" "+emp.name+" "+emp.salary);
4. </script>

Output of the above example


102 Shyam Kumar 40000

2) By creating instance of Object

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>

Output of the above example


101 Ravi 50000

3) By using an Object constructor

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

The this keyword refers to the current object

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

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>

Output of the above example


103 Vimal Jaiswal 30000

Page 43
Defining method in JavaScript Object

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

The example of defining method in object is given below.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>

Output of the above example


103SonooJaiswal30000
103 Sonoo Jaiswal 45000

JavaScript Object Methods

The various methods of Object are as follows:

S.No Methods Description

1 Object.assign() This method is used to copy enumerable and own


properties from a source object to a target object

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


specified prototype object and properties.

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


attributes of the property.

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


object properties.

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


value pairs.

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


removed.

Page 44
7 Object.getOwnPropertyDescriptor() This method returns a property descriptor for the
specified property of the specified object.

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


given object.

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


(enumerable or not) found.

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


properties.

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


object.

12 Object.is() This method determines whether two values are the


same value.

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

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

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

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


property names.

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


object.

18 Object.seal() This method prevents new properties from being


added and marks all existing properties as non-
configurable.

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


another object.

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

Primitives Operations and Expressions

Javascript Data Types


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

1. Primitive data type


2. Non-primitive (reference) data type

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

1. var a=40;//holding number


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

JavaScript primitive data types

Page 45
There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

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

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types

The non-primitive data types are as follows:

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

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

1. var sum=10+20;

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

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
7. JavaScript Arithmetic Operators
8. Arithmetic operators are used to perform arithmetic operations on the operands. The following operators are known as
JavaScript arithmetic operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

Page 46
/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

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

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

JavaScript Comparison Operators

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

Operator Description Example

== Is equal to 10==20 = false

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

!= Not equal to 10!=20 = true

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

> Greater than 20>10 = true

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

< Less than 20<10 = false

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

JavaScript Bitwise Operators

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

Operator Description Example

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

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

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

~ Bitwise NOT (~10) = -10

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

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

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

JavaScript Logical Operators

The following operators are known as JavaScript logical operators.

Operator Description Example

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

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

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

JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

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

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

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

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

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

JavaScript Special Operators

The following operators are known as JavaScript special operators.

Operator Description

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

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

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

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

Expressions

An expression is an unit of code that JavaScript interpreter can parse and compute to produce a value.
There are simple expressions like literal values and complex which are built from simpler ones usually using operators.

Primary expressions

Page 48
Primary expressions are the simplest expressions. There are three groups of primary expressions: literal values, variable references, and some
keywords.

Literal values
Literal values are constant values:

"text" // a string literal

125 // a number literal

Variable references
Any identifier that appears in the code JavaScript interpreter assumes it is a variable and try to read its value.

x // evaluates to the value of the variable x

price // evaluates to the value of the variable price

undefined // a global variable undefined evaluates to the value undefined

Basic keywords and reserved words


The this
The this evaluates to the current object. It is used in a method to refer to the current object, for example:

this.name

this.displayName()

Other examples:

true // evaluates to the boolean true

false // evaluates to the boolean false

null //evaluate to the null value.

Function expression

Function expression defines a JavaScript function and the value of this expression is newly defined function. For example:

var sum = function (x, y) {

return x + y;

Page 49
}

var z = sum (3, 4); //7

Object initializer expression

Object initializer creates object with literal notation and the value of this expression is newly created object. It uses curly brackets surrounding
object properties separated by commas. For example:

var obj = {

prop1: "value1",

prop2: 2

};

Array initializer expression

Array initializer creates array with literal notation and the value of this expression is newly created array. It consists of square brackets
surrounding elements separated by commas. For example:

1 var arr = [1, 2, 3];

Object creation expression

Object creation expression creates a new instance of object. It uses the keyword new followed by a constructor invocation.
An example:

1 var obj = new Object();

Property access expression

There are two ways to access a property of an object: either using the object followed by a period and an identifier or using the object (or the
array) followed by square brackets with an identifier inside. It evaluates respectively to the value of an object property or an array element.

1 var obj = {x: 1, y: 2};

2 obj.x // 1

Page 50
3 obj['y'] // 2

4 var arr = [2, 3];

5 arr[1] // 3

Invocation expression

Invocation expression is used to call a function or a method in JavaScript.

1 func(arg);

2 obj.myMeth(x, y);

Parent object reference expression

Parent object reference is a new added in ECMAScript 2015 expression using the keyword super. It evaluates to a parent object.

1 super(arg1, arg2); // calls the parent constructor

2 super.meth(arg1, arg2); // calls the parent object method

Spread operator

Spread operator named also rest operator allows an iterable to expand in place where multiple arguments (for function calls) or multiple elements
(for array literals) are expected.

Function call

function sum(a, b, c) {

return a + b + c;

var items = [2, 3, 4];

var result = sum(...items); // 9

Array literal

Page 51
var motorVehicles = ['car', 'motorcycle', 'truck'];

var railedVehicles = ['train', 'tram'];

var vehicles = ['bicke', ...motorVehicles, 'airplane', 'ship', ...railedVehicles];

console.log(vehicles); // [ "bicke", "car", "motorcycle", "truck", "airplane", "ship", "train", "tram" ]

Other expressions

There are many other expressions, such as arithmetic, comparison, logical. These are covered in the chapter on operators.

Control Statements

Type of Control Statement in JavaScript


Every programming language, basically, has two types of control statements as follows:

 Conditional Statements: based on an expression passed, a conditional

statement makes a decision, which results in either YES or NO.

 Iterative Statements (Loop): These statements continue to repeat until the

expression or condition is satisfied.

1. Conditional Statements
Conditional statements in a program decide the next step based on the result. They

result in either True or False. The program moves to the next step if a condition is

Page 52
passed and true. However, if the condition is false, the program moves to another step.

These statements are executed only once, unlike loop statements.

Following are the different types of Conditional Statements:

IF

When you want to check for a specific condition with the IF condition, the inner code

block executes if the provided condition is satisfied.

Syntax:

if (condition) {

//code block to be executed if condition is satisfied

IF-ELSE

an extended version of IF. When you want to check a specific condition and two

Syntax:

if (condition)

// code to be executed of condition is true

else {

// code to be executed of condition is false

Page 53
As observed in an IF-ELSE statement, when the condition is satisfied, the first block of

code executes, and if the condition isn’t satisfied, the second block of code executes.

SWITCH

A switch statement is similar to IF and is useful when executing one code out of the

multiple code block execution possibilities based on the result of the expression passed.

Switch statements carry an expression, which is compared with values of the following

cases, and once a match is found, the code associated with that case executes.

Syntax:

switch (expression) {

case a:

//code block to be executed

Break;

case b:

//code block to be executed

Break;

case n:

//code block to be executed

Break;

default:

//default code to be executed if none of the above case is executed

The above code contains an expression at the beginning, checked and compared with

the cases included. If the expression passed matches with case a, the code block inside

the case is executed. The same applies to cases b and n, and when the expression

Page 54
passed matches with none of the cases mentioned, it code enters the default case, and

the code under the default case is executed.

Now that we have understood the conditional statements let’s learn about the second

type, i.e. Iterative Statements.

2. Iterative Statement
Looping is a powerful tool for any programming language to execute instructions

repeatedly while the expression passed is satisfied. A basic example can be printing

“Hello World” 10 times. Writing the same print statement with “Hello world“ for 10

straight times will be time-consuming and impact the execution time. And this is where

looping comes in handy. There are three Iterative statements: WHILE, DO-WHILE,

and FOR. Let’s understand each with syntax.

WHILE

One of the control flow statements, the “while” statement, executes a code block when

the condition is satisfied. The difference between “IF” and “while” is that “IF” executes

code if the condition is satisfied, while “while” continues to repeat itself until the

condition is satisfied, unlike “IF”, which executes code only once if the condition is

satisfied, “while” keeps repeating itself until the condition is satisfied.

Syntax:

Page 55
while (condition)

//code block to be executed when condition is satisfied

DO-WHILE

Similar to a while loop, with a twist that keeps a condition at the end of the loop. Also

known as Exit Control Loop, DO-WHILE executes the code and checks for the condition.

Syntax:

while

//code block to be executed when condition is satisfied

} (condition)

If the condition at the end is satisfied, the loop will repeat.

FOR

a for loop will execute a code block a number of times. Compared to other loops, FOR is

shorter and easy to debug as it contains initialization, condition, and increment or

decrement in a single line.

Syntax:

for (initialize; condition; increment/decrement)

//code block to be executed

Page 56
With initialization, the loop starts by using a declared variable. Then, the condition part

checks the exit condition for the loop. When this condition returns true, the code block

inside is executed. If the condition returns false or fails, the control moves to the

increment/decrement part, where the variable is updated. The values are updated until

the condition is satisfied.

Arrays

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

There are 3 ways to construct array in JavaScript

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

1) JavaScript array literal

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

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

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

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

1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>
Output of the above example

Sonoo
Vimal
Ratan

Page 57
2) JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

1. var arrayname=new Array();

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

Let's see the example of creating array directly.

1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>
Test it Now

Output of the above example

Arun
Varun
John

3) JavaScript array constructor (new keyword)


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

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

1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>
Test it Now

Output of the above example

Page 58
Jai
Vijay
Smith

JavaScript Array Methods

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

Methods Description

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

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

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

every() It determines whether all the elements of an array are satisfying the provided
function conditions.

flat() It creates a new array carrying sub-array elements concatenated recursively till
the specified depth.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

of() It creates a new array from a variable number of arguments, holding any type
of argument.

Page 59
pop() It removes and returns the last element of an array.

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

reverse() It reverses the elements of given array.

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

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

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

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

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

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

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

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

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

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

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

Functions

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

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

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


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

JavaScript Function Syntax

The syntax of declaring function is given below.

6.2M

1K

Polymorphism in Java | Dynamic Method Dispatch

Page 60
1. function functionName([arg1, arg2, ...argN]){
2. //code to be executed
3. }

JavaScript Function can have 0 or more arguments.

JavaScript Function Example

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

1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
Test it Now

Output of the above example

Call function (button)

JavaScript Function Arguments

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

1. <script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
Test it Now

Output of the above example

Click

Function with Return Value

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

1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());

Page 61
8. </script>
Test it Now

Output of the above example


hello javatpoint! How r u?

JavaScript Function Object

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

Syntax

1. new Function ([arg1[, arg2[, ....argn]],] functionBody)

Parameter

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

functionBody - It represents the function definition.

JavaScript Function Methods

Let's see function methods with description.

Method Description

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

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

call() It is used to call a function contains this value and an argument list.

toString() It returns the result in a form of a string.

JavaScript Function Object Examples

Example 1

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

1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>

Output

Page 62
Example 2

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

1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
Test it Now

Output:

Constructors

JavaScript Constructor Method


A JavaScript constructor method is a special type of method which is used to initialize and create an object. It is called when memory
is allocated for an object.

Points to remember

o The constructor keyword is used to declare a constructor method.


o The class can contain one constructor method only.
o JavaScript allows us to use parent class constructor through super keyword.

Constructor Method Example

Let's see a simple example of a constructor method.

1. <script>
2. class Employee {
3. constructor() {
4. this.id=101;
5. this.name = "Martin Roy";
6. }
7. }
8. var emp = new Employee();
9. document.writeln(emp.id+" "+emp.name);
10. </script>
Output:
11. 6.7M
12. 853
13. OOPs Concepts in Java

101 Martin Roy

Constructor Method Example: super keyword

Page 63
The super keyword is used to call the parent class constructor. Let's see an example.

1. <script>
2. class CompanyName
3. {
4. constructor()
5. {
6. this.company="Javatpoint";
7. }
8. }
9. class Employee extends CompanyName {
10. constructor(id,name) {
11. super();
12. this.id=id;
13. this.name=name;
14. }
15. }
16. var emp = new Employee(1,"John");
17. document.writeln(emp.id+" "+emp.name+" "+emp.company);
18. </script>
Test it Now

Output:

1 John Javatpoint

Pattern Matching using Regular Expressions

A regular expression is a sequence of characters that forms a search pattern.

The search pattern can be used for text search and text replace operations.

What Is a Regular Expression?


A regular expression is a sequence of characters that forms a search pattern.

When you search for data in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax
/pattern/modifiers;
Example
/w3schools/i;

Example explained:

Page 64
/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).

Using String Methods


In JavaScript, regular expressions are often used with the two string methods: search() and replace().

The search() method uses an expression to search for a match, and returns the position of the match.

The replace() method returns a modified string where the pattern is replaced.

Using String search() With a String


The search() method searches a string for a specified value and returns the position of the match:

Example
Use a string to do a search for "W3schools" in a string:

let text = "Visit W3Schools!";


let n = text.search("W3Schools");

The result in n will be:

Try it Yourself »

Using String search() With a Regular Expression


Example
Use a regular expression to do a case-insensitive search for "w3schools" in a string:

let text = "Visit W3Schools";


let n = text.search(/w3schools/i);

The result in n will be:

Page 65
Using String replace() With a String
The replace() method replaces a specified value with another value in a string:

let text = "Visit Microsoft!";


let result = text.replace("Microsoft", "W3Schools");

Use String replace() With a Regular Expression


Example
Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:

let text = "Visit Microsoft!";


let result = text.replace(/microsoft/i, "W3Schools");

The result in res will be:

Visit W3Schools!

Did You Notice?


Regular expression arguments (instead of string arguments) can be used in the methods above.
Regular expressions can make your search much more powerful (case insensitive for example).

Regular Expression Modifiers


Modifiers can be used to perform case-insensitive more global searches:

Modifier 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

Regular Expression Patterns


Brackets are used to find a range of characters:

Page 66
Expression Description

[abc] Find any of the characters between the brackets

[0-9] Find any of the digits between the brackets

(x|y) Find any of the alternatives separated with |

Metacharacters are characters with a special meaning:

Metacharacter Description

\d Find a digit

\s Find a whitespace character Try it


»

\b Find a match at the beginning of a word like this: \bWORD, or at the end of a
word like this: WORD\b

\uxxxx Find the Unicode character specified by the hexadecimal number xxxx Try it
»

Quantifiers define quantities:

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n Try it »

n? Matches any string that contains zero or one occurrences of n

Using the RegExp Object

Page 67
In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

Using test()
The test() method is a RegExp expression method.

It searches a string for a pattern, and returns true or false, depending on the result.

The following example searches a string for the character "e":

Example
const pattern = /e/;
pattern.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
You don't have to put the regular expression in a variable first. The two lines above can be shortened to one:

/e/.test("The best things in life are free!");

Using exec()
The exec() method is a RegExp expression method.

It searches a string for a specified pattern, and returns the found text as an object.

If no match is found, it returns an empty (null) object.

The following example searches a string for the character "e":

Example
/e/.exec("The best things in life are free!");

Angular Java Script Angular JS Expressions

What is Angular JS Expressions?


Expressions are variables which were defined in the double braces {{ }}. They are very commonly used
within Angular JS

Explain Angular.js Expressions with an example


AngularJS expressions are those that are written inside double braces {{expression}}.

Page 68
Syntax:

A simple example of an expression is {{5 + 6}}.

Angular.JS expressions are used to bind data to HTML the same way as the ng-bind directive. AngularJS
displays the data exactly at the place where the expression is placed.

Let’s look at an example of Angular.JS expressions.

In this example, we just want to show a simple addition of numbers as an expression.

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>

</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> Guru99 Global Event</h1>

<div ng-app="">
Addition : {{6+9}}
</div>

Page 69
</body>
</html>
Code Explanation:

1. The ng-app directive in our example is blank as shown in above screenshot. This only means that
there is no module to assign controllers, directives, services attached to the code.
2. We are adding a simple expression which looks at the addition of 2 numbers.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:

From the output,

 It can be seen that the addition of the two numbers 9 and 6 take place and the added value of 15
is displayed.

Angular.JS Numbers
Expressions can be used to work with numbers as well. Let’s look at an example of Angular.JS
expressions with numbers.

In this example, we just want to show a simple multiplication of 2 number variables called margin and
profit and displayed their multiplied value.

Page 70
Code Explanation:

1. The ng-init directive is used in angular.js to define variables and their corresponding values in the
view itself. It’s somewhat like defining local variables to code in any programming language. In
this case, we are defining 2 variables called margin and profit and assigning values to them.
2. We are then using the 2 local variables and multiplying their values.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:

From the output,

Page 71
 It can be clearly seen that the multiplication of the 2 numbers 2 and 200 take place, and the
multiplied value of 400 is displayed.

AngularJS Strings
Expressions can be used to work with strings as well. Let’s look at an example of Angular JS expressions
with strings.

In this example, we are going to define 2 strings of “firstName” and “lastName” and display them using
expressions accordingly.

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>

</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> Guru99 Global Event</h1>

<div ng-app="" ng-init="firstName='Guru';lastName='99'">

&nbsp;&nbsp;&nbsp;
First Name : {{firstName}}<br>&nbsp;&nbsp;&nbsp;
last Name : {{lastName}}

</div>

</body>
</html>
Code Explanation:

1. The ng-init directive is used define the variables firstName with the value “Guru” and the variable
lastName with the value of “99”.
2. We are then using expressions of {{firstName}} and {{lastName}} to access the value of these
variables and display them in the view accordingly.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:

Page 72
Angular.JS Objects
Expressions can be used to work with JavaScript objects as well.

Let’s look at an example of Angular.JS expressions with javascript objects. A javascript object consists of
a name-value pair.

Below is an example of the syntax of a javascript object.

Syntax:

var car = {type:"Ford", model:"Explorer", color:"White"};

In this example, we are going to define one object as a person object which will have 2 key value pairs of
“firstName” and “lastName”

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>

</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> Guru99 Global Event</h1>

<div ng-app="" ng-init="person={firstName:'Guru',lastName:'99'}">

&nbsp;&nbsp;&nbsp;
First Name : {{person.firstName}}<br>&nbsp;&nbsp;&nbsp;
Last Name : {{person.lastName}}

</div>

</body>
</html>
Code Explanation:

1. The ng-init directive is used to define the object person which in turn has key value pairs of
firstName with the value “Guru” and the variable lastName with the value of “99”.
2. We are then using expressions of {{person.firstName}} and {{person.secondName}} to access the
value of these variables and display them in the view accordingly. Since the actual member
variables are part of the object person, they have to access it with the dot (.) notation to access
their actual value.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Page 73
Output:

AngularJS Arrays
Expressions can be used to work with arrays as well. Let’s look at an example of Angular JS expressions
with arrays.

In this example, we are going to define an array which is going to hold the marks of a student in 3
subjects. In the view, we will display the value of these marks accordingly.

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>

<h1> Guru99 Global Event</h1>

<div ng-app="" ng-init="marks=[1,15,19]">

Student Marks<br>&nbsp;&nbsp;&nbsp;
Subject1 : {{marks[0] }}<br>&nbsp;&nbsp;&nbsp;
Subject2 : {{marks[1] }}<br>&nbsp;&nbsp;&nbsp;
Subject3 : {{marks[2] }}<br>&nbsp;&nbsp;&nbsp;
</div>

</body>
</html>
Code Explanation:

1. The ng-init directive is used define the array with the name “marks” with 3 values of 1, 15 and 19.
2. We are then using expressions of marks [index] to access each element of the array.

If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:

Page 74
Difference between expression and $eval
The $eval function allows one to evaluate expressions from within the controller itself. So while
expressions are used for evaluation in the view, the $eval is used in the controller function.

Let’s look at a simple example on this.

In this example,

We are just going to use the $eval function to add 2 numbers and make it available in the scope object so
that it can be shown in the view.

<!DOCTYPE html>
<html>
<head>
<meta chrset="UTF 8">
<title>Event Registration</title>
</head>
<body>

<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<div ng-app="sampleApp" ng-controller="AngularController">


<h1> Guru99 Global Event</h1>
{{value}}
</div>
<script>
var sampleApp = angular.module('sampleApp',[]);
sampleApp.controller('AngularController',function($scope){
$scope.a=1;
$scope.b=1;

$scope.value=$scope.$eval('a+b');
});
</script>

</body>
</html>
Code Explanation:

1. We are first defining 2 variables ‘a’ and ‘b’, each holding a value of 1.
2. We are using the $scope.$eval function to evaluate the addition of the 2 variables and assigning
it to the scope variable ‘value’.
3. We are then just displaying the value of the variable ‘value’ in the view.

Page 75
If the code is executed successfully, the following Output will be shown when you run your code in the
browser.

Output:

AngularJS Form Validation


AngularJS provides client-side form validation. It checks the state of the form and input fields (input, textarea, select), and lets you
notify the user about the current state.

It also holds the information about whether the input fields have been touched, or modified, or not.

Following directives are generally used to track errors in an AngularJS form:

o $dirty - states that value has been changed.


o $invalid - states that value entered is invalid.
o $error - states the exact error.

AngularJS Form Validation Example

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Angular JS Forms</title>
5. <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
6.
7. <style>
8. table, th , td {
9. border: 1px solid grey;
10. border-collapse: collapse;
11. padding: 5px;
12. }
13.
14. table tr:nth-child(odd) {
15. background-color: lightpink;
16. }
17.
18. table tr:nth-child(even) {

Page 76
19. background-color: lightyellow;
20. }
21. </style>
22.
23. </head>
24. <body>
25.
26. <h2>AngularJS Sample Application</h2>
27. <div ng-app = "mainApp" ng-controller = "studentController">
28.
29. <form name = "studentForm" novalidate>
30. <table border = "0">
31. <tr>
32. <td>Enter first name:</td>
33. <td><input name = "firstname" type = "text" ng-model = "firstName" required>
34. <span style = "color:red" ng-show = "studentForm.firstname.$dirty && studentForm.firstname.$invalid">
35. <span ng-show = "studentForm.firstname.$error.required">First Name is required.</span>
36. </span>
37. </td>
38. </tr>
39.
40. <tr>
41. <td>Enter last name: </td>
42. <td><input name = "lastname" type = "text" ng-model = "lastName" required>
43. <span style = "color:red" ng-show = "studentForm.lastname.$dirty && studentForm.lastname.$invalid">
44. <span ng-show = "studentForm.lastname.$error.required">Last Name is required.</span>
45. </span>
46. </td>
47. </tr>
48.
49. <tr>
50. <td>Email: </td><td><input name = "email" type = "email" ng-model = "email" length = "100" required>
51. <span style = "color:red" ng-show = "studentForm.email.$dirty && studentForm.email.$invalid">
52. <span ng-show = "studentForm.email.$error.required">Email is required.</span>
53. <span ng-show = "studentForm.email.$error.email">Invalid email address.</span>
54. </span>
55. </td>
56. </tr>
57. <tr>
58. <td>
59. <button ng-click = "reset()">Reset</button>
60. </td>
61. <td>
62. <button ng-disabled = "studentForm.firstname.$dirty &&
63. studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
64. studentForm.lastname.$invalid || studentForm.email.$dirty &&
65. studentForm.email.$invalid" ng-click="submit()">Submit</button>
66. </td>
67. </tr>
68. </table>
69. </form>

Page 77
70. </div>
71. <script>
72. var mainApp = angular.module("mainApp", []);
73. mainApp.controller('studentController', function($scope) {
74. $scope.reset = function(){
75. $scope.firstName = "Sonoo";
76. $scope.lastName = "Jaiswal";
77. $scope.email = "sonoojaiswal@javatpoint.com";
78. }
79. $scope.reset();
80. });
81. </script>
82. </body>
83. </html>

How To Build a Single Page Application Using AngularJS?


Developing an application from scratch is not easy as it seems. Everything should be researched in advance, from choosing
the best framework for the database to a team of developers. Some business persons are concerned about the cost and
search for how much it costs to develop an app, but end with inaccurate figures as the price depends on many factors.
After discussing the below steps, you might know how much time and money is required to develop a single-page
application using the latest framework.

Step 1: Create a Module

Angular follows MVC architecture, so every angular app consists of different modules.

Var app = angular.module(‘myApp’,[]);

Step 2: Define Controller

app.controller('FirstController', function($scope) {

$scope.message = 'Hello from FirstController';

});

Step 3: Deploy the AngularJS script in HTML Code

The module created in the first step and the controller performed in the second step specify both in the ng-controller
attribute.

<!doctype html>

<html ng-app="myApp">

<head>

Page 78
<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

</head>

<body ng-controller="FirstController">

<h1>{{message}}</h1>

<script src="app.js"></script>

</body>

</html>

Step 4: Create an HTML Layout for the Website


Once you successfully create the HTML layout for the website, you need to use the ng-view directive with the one place
where the HTML file of all pages will be placed in the same layout.

<!doctype html>

<html ng-app="myApp">

<head>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>

</head>

<body>

<div ng-view></div>

<script src="app.js"></script>

</body>

</html>

Step 5: Configure Routes

A templateUrl and a controller must be specified for each route. In cases where a user attempts to navigate to an unexistent
route, an exception must be handled. Then, the user can be redirected to the “/” route using an “otherwise” function.

var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider) {

Page 79
$routeProvider

.when('/', {

templateUrl : 'pages/first.html',

controller : 'FirstController'

})

.when('/blog', {

templateUrl : 'pages/second.html',

controller : 'SecondController'

})

.when('/about', {

templateUrl : 'pages/third.html',

controller : 'ThirdController'

})

.otherwise({redirectTo: '/'});

});

Step 6: Time to Build Controllers

app.controller('FirstController', function($scope) {

$scope.message = 'Hello from FirstController';

});

app.controller('SecondController', function($scope) {

$scope.message = 'Hello from SecondController';

});

Page 80
app.controller('ThirdController', function($scope) {

$scope.message = 'Hello from ThirdController';

});

Step 7: Configuring the HTML Pages

first.html

<h1>First</h1>

<h3>{{message}}</h3>

second.html

<h1>Second</h1>

<h3>{{message}}</h3>

third.html

<h1>Third</h1>

<h3>{{message}}</h3>

Step 8: Add Links to Those HTML Pages

<!doctype html>

<html ng-app="myApp">

<head>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>

</head>

<body>

<a href="#/">First</a>

<a href="#/second">Second</a>

<a href="#/third">Third</a>

Page 81
<div ng-view></div>

<script src="app.js"></script>

</body>

</html>

Step 9: Include the HTML of the Above Pages to Index.html file with Script Tag

<!doctype html>

<html ng-app="myApp">

<head>

<script
src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-
route.min.js"></script>

</head>

<body>

<script type="text/ng-template" id="pages/first.html">

<h1>First</h1>

<h3>{{message}}</h3>

</script>

<script type="text/ng-template" id="pages/second.html">

<h1>Second</h1>

<h3>{{message}}</h3>

</script>

<script type="text/ng-template" id="pages/third.html">

<h1>Third</h1>

<h3>{{message}}</h3>

</script>

Page 82
<a href="#/">First</a>

<a href="#/second">Second</a>

<a href="#/third">Third</a>

<div ng-view></div>

<script src="app.js"></script>

</body>

</html>

That’s it! After successfully performing the above steps, you can easily create single-page applications using Angular and
also simplify many other complex tasks of your projects.

Page 83
Angular JS & Node.JS – Unit-2 Web Technologies

Node.js Introduction

 Node.js is an open source server environment


 Node.js is free
 Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 Node.js uses JavaScript on the server

Why Node.js?

Node.js uses asynchronous programming!


A common task for a web server can be to open a file on the server and return the content to the client.
Here is how PHP or ASP handles a file request:

1. Sends the task to the computer's file system.


2. Waits while the file system opens and reads the file.
3. Returns the content to the client.
4. Ready to handle the next request.

Here is how Node.js handles a file request:

1. Sends the task to the computer's file system.


2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the content to the client.

Node.js eliminates the waiting, and simply continues with the next request.

Node.js runs single-threaded, non-blocking, asynchronous programming, which is very memory efficient.

What Can Node.js Do?

 Node.js can generate dynamic page content


 Node.js can create, open, read, write, delete, and close files on the server
 Node.js can collect form data
 Node.js can add, delete, modify data in your database

What is a Node.js File?

 Node.js files contain tasks that will be executed on certain events


 A typical event is someone trying to access a port on the server
 Node.js files must be initiated on the server before having any effect
 Node.js files have extension ".js"

Advantages of Node.js

1. Cross-platform compatibility: NodeJS is compatible with multiple platforms including Windows,


Unix, Linux, Mac OS X, and mobile platforms. It can be bundled with the correct package into an
executable that is entirely self-reliant.

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 22


Page 84
Angular JS & Node.JS – Unit-2 Web Technologies

2. The convenience of using one coding language

NodeJs can be learned quickly by those who are already well-versed with JavaScript. With NodeJs,
developers can use the same coding language for both front-end and back-end development. Therefore,
JavaScript is the most preferred language for full-stack development.

Thus, it offers convenience to programmers as they don’t need to switch between multiple coding
languages and they also need to deal with fewer files.

3. V8 Engine

Originally developed for Chrome, V8 Engine has now been adapted to suit web app development
purposes. The V8 Engine is one of the most superior engines that can translate JavaScript to general
machine coding language with the help of C++. Thus, the V8 Engine is ultimately helpful for servers and
all machine language-based products.

4. Facilitates quick deployment and microservice development

NodeJS is a lightweight tool that aids in the faster development and deployment of applications.
It also assists in the development of microservices. This is because NodeJs is capable of fast data
processing and provides non-locking algorithms which are extremely beneficial for the development of
microservices.

Additionally, NodeJs can also handle concurrent requests simultaneously. This is ultimately crucial for
microservices as they need to constantly and quickly communicate with each other.

5. Scalable
Most businesses nowadays prefer scalable software.

First of all, NodeJs takes care of concurrent requests. The second reason that makes NodeJs popular is
that it has a cluster module that handles load balance for all running CPU cores.
The third and most interesting feature of NodeJs is its ability to split software horizontally. It
accomplishes this with the help of child processes. This means that businesses can present different app
versions to different target audiences which helps them address the personalization preferences of
customers.

6. Commendable data processing ability

Next, NodeJs employs an event-based software development approach in which there is no defined
output order and the output is delivered solely based upon the user’s inputs.

7. Active open-source community

Being an open-source solution, NodeJs offers an extensive global community. The advantage of having a
larger community is that developers can seek help from community members to get responses for their
queries instantly. Community members share tools, modules, packages, and frameworks among each
other completely free of cost.

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 23


Page 85
Angular JS & Node.JS – Unit-2 Web Technologies

8. Additional functionality of NPM

The official package ecosystem of NodeJs is the node package manager (NPM) with a dynamic
repository of multiple tools and modules which are used by developers for app development. NPM is like
a free marketplace for developers.

NPM can help in file upload management, download updates, and establish connectivity to MySQL
databases.

9. Advanced hosting ability of NodeJs

NodeJs reduces the number of servers needed to host the application and ultimately cuts down the page
load time by 50%.

10. Fast data streaming

When data travels as different streams, processing them consumes a lot of time. So, NodeJS saves the
time that goes into processing data by processing a file simultaneously while it is being uploaded.

Node.js Process Model

Traditional Web Server Model

In the traditional web server model, each request is handled by a dedicated thread from the thread
pool. If no thread is available in the thread pool at any point of time then the request waits till the next
available thread. Dedicated thread executes a particular request and does not return to thread pool
until it completes the execution and returns a response.

Traditional Web Server Model

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 24


Page 86
Angular JS & Node.JS – Unit-2 Web Technologies

Node.js Process Model

Node.js processes user requests differently when compared to a traditional web server model. Node.js
runs in a single process and the application code runs in a single thread and thereby needs less
resources than other platforms. All the user requests to your web application will be handled by a
single thread and all the I/O work or long running job is performed asynchronously for a particular
request. So, this single thread doesn't have to wait for the request to complete and is free to handle the
next request. When asynchronous I/O work completes then it processes the request further and sends
the response.

An event loop is constantly watching for the events to be raised for an asynchronous job and
executing callback function when the job completes. Internally, Node.js uses libev for the event loop
which in turn uses internal C++ thread pool to provide asynchronous I/O.

The following figure illustrates asynchronous web server model using Node.js.

Node.js Process Model

Node.js process model increases the performance and scalability with a few caveats. Node.js is not fit
for an application which performs CPU-intensive operations like image processing or other heavy
computation work because it takes time to process a request and thereby blocks the single thread.

Node.js Modules

What is a Module in Node.js?


Consider modules to be the same as JavaScript libraries.
A set of functions you want to include in your application.

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 25


Page 87
Angular JS & Node.JS – Unit-2 Web Technologies

Built-in Modules

Node.js has a set of built-in modules which you can use without any further installation.

Include Modules

To include a module, use the require() function with the name of the module:

var http = require('http');

Now your application has access to the HTTP module, and is able to create a server:

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);

Create Your Own Modules

You can create your own modules, and easily include them in your applications.

The following example creates a module that returns a date and time object:

Example

Create a module that returns the current date and time:

exports.myDateTime = function () {
return Date();
};

Use the exports keyword to make properties and methods available outside the module file.

Save the code above in a file called "myfirstmodule.js"

Include Your Own Module

Now you can include and use the module in any of your Node.js files.

Example

Use the module "myfirstmodule" in a Node.js file:

var http = require('http');


var dt = require('./myfirstmodule');

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 26


Page 88
Angular JS & Node.JS – Unit-2 Web Technologies

http.createServer(function (req, res) {


res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);

Notice that we use ./ to locate the module, that means that the module is located in the same folder as the
Node.js file.

Save the code above in a file called "demo_module.js", and initiate the file:

Initiate demo_module.js:

C:\Users\Your Name>node demo_module.js

If you have followed the same steps on your computer, you will see the same result as the
example: http://localhost:8080

Node.js File System Module

Node.js as a File Server

The Node.js file system module allows you to work with the file system on your computer.

To include the File System module, use the require() method:

var fs = require('fs');

Common use for the File System module:

 Read files
 Create files
 Update files
 Delete files
 Rename files

Read Files

The fs.readFile() method is used to read files on your computer.

Assume we have the following HTML file (located in the same folder as Node.js):

demofile1.html

<html>
<body>

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 27


Page 89
Angular JS & Node.JS – Unit-2 Web Technologies

<h1>My Header</h1>
<p>My paragraph.</p>
</body>
</html>

Create a Node.js file that reads the HTML file, and return the content:

Example
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('demofile1.html', function(err, data) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);

Save the code above in a file called "demo_readfile.js", and initiate the file:

Initiate demo_readfile.js:

C:\Users\Your Name>node demo_readfile.js

If you have followed the same steps on your computer, you will see the same result as the
example: http://localhost:8080

Create Files

The File System module has methods for creating new files:

 fs.appendFile()
 fs.open()
 fs.writeFile()

The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be
created:

Example

Create a new file using the appendFile() method:

var fs = require('fs');

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 28


Page 90
Angular JS & Node.JS – Unit-2 Web Technologies

if (err) throw err;


console.log('Saved!');
});

The fs.open() method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified
file is opened for writing. If the file does not exist, an empty file is created:

Example

Create a new, empty file using the open() method:

var fs = require('fs');

fs.open('mynewfile2.txt', 'w', function (err, file) {


if (err) throw err;
console.log('Saved!');
});

The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a
new file, containing the specified content, will be created:

Example

Create a new file using the writeFile() method:

var fs = require('fs');

fs.writeFile('mynewfile3.txt', 'Hello content!', function (err) {


if (err) throw err;
console.log('Saved!');
});

Update Files

The File System module has methods for updating files:

 fs.appendFile()
 fs.writeFile()

The fs.appendFile() method appends the specified content at the end of the specified file:

Example

Append "This is my text." to the end of the file "mynewfile1.txt":

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 29


Page 91
Angular JS & Node.JS – Unit-2 Web Technologies

var fs = require('fs');

fs.appendFile('mynewfile1.txt', ' This is my text.', function (err) {


if (err) throw err;
console.log('Updated!');
});

The fs.writeFile() method replaces the specified file and content:

Example

Replace the content of the file "mynewfile3.txt":

var fs = require('fs');

fs.writeFile('mynewfile3.txt', 'This is my text', function (err) {


if (err) throw err;
console.log('Replaced!');
});

Delete Files

To delete a file with the File System module, use the fs.unlink() method.

The fs.unlink() method deletes the specified file:

Example

Delete "mynewfile2.txt":

var fs = require('fs');

fs.unlink('mynewfile2.txt', function (err) {


if (err) throw err;
console.log('File deleted!');
});

Rename Files

To rename a file with the File System module, use the fs.rename() method.

The fs.rename() method renames the specified file:

Example
Rename "mynewfile1.txt" to "myrenamedfile.txt":

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 30


Page 92
Angular JS & Node.JS – Unit-2 Web Technologies

var fs = require('fs');
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
if (err) throw err;
console.log('File Renamed!');
});

Upload Files

You can also use Node.js to upload files to your computer.

Node.js URL Module


The Built-in URL Module

The URL module splits up a web address into readable parts.

To include the URL module, use the require() method:

var url = require('url');

Parse an address with the url.parse() method, and it will return a URL object with each part of the address
as properties:

Example

Split a web address into readable parts:

var url = require('url');


var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8080'


console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'

var qdata = q.query; //returns an object: { year: 2017, month: 'february' }


console.log(qdata.month); //returns 'february'

Node.js File Server

Now we know how to parse the query string, and in the previous chapter we learned how to make
Node.js behave as a file server. Let us combine the two, and serve the file requested by the client.

Create two html files and save them in the same folder as your node.js files.

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 31


Page 93
Angular JS & Node.JS – Unit-2 Web Technologies

summer.html

<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>

winter.html

<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>

Create a Node.js file that opens the requested file and returns the content to the client. If anything goes
wrong, throw a 404 error:

demo_fileserver.js:

var http = require('http');


var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {


var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);

Remember to initiate the file:

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 32


Page 94
Angular JS & Node.JS – Unit-2 Web Technologies

Initiate demo_fileserver.js:

C:\Users\Your Name>node demo_fileserver.js

If you have followed the same steps on your computer, you should see two different results when
opening these two addresses:

http://localhost:8080/summer.html

Will produce this result:

Summer

I love the sun!

http://localhost:8080/winter.html

Will produce this result:

Winter

I love the snow!

Node.js Events

Node.js is perfect for event-driven applications.

Events in Node.js

Every action on a computer is an event. Like when a connection is made or a file is opened.

Objects in Node.js can fire events, like the readStream object fires events when opening and closing a
file:

Example
var fs = require('fs');
var rs = fs.createReadStream('./demofile.txt');
rs.on('open', function () {
console.log('The file is open');
});

Events Module

Node.js has a built-in module, called "Events", where you can create-, fire-, and listen for- your own
events.

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 33


Page 95
Angular JS & Node.JS – Unit-2 Web Technologies

To include the built-in Events module use the require() method. In addition, all event properties and
methods are an instance of an EventEmitter object. To be able to access these properties and methods,
create an EventEmitter object:

var events = require('events');


var eventEmitter = new events.EventEmitter();

The EventEmitter Object

You can assign event handlers to your own events with the EventEmitter object.

In the example below we have created a function that will be executed when a "scream" event is fired.

To fire an event, use the emit() method.

Example
var events = require('events');
var eventEmitter = new events.EventEmitter();

//Create an event handler:


var myEventHandler = function () {
console.log('I hear a scream!');
}

//Assign the event handler to an event:


eventEmitter.on('scream', myEventHandler);

//Fire the 'scream' event:


eventEmitter.emit('scream');

Vignan’s LARA Institute of Technology and Science, Vadlamudi. Page 34


Page 96
lOMoARcPSD|37177639

9. Security and Access Control: Implement security measures such as access


control, firewalls, encryption, and identity and access management (IAM) to protect
your application and data on the cloud platform.
10. Continuous Deployment and DevOps: Consider setting up continuous
integration and deployment (CI/CD) pipelines to automate the process of building,
testing, and deploying your application updates. Use DevOps practices to streamline
development, deployment, and operations.

It's important to refer to the documentation and resources provided by the specific
cloud platform you choose, as the deployment process may vary depending on the
platform and services you utilize.

UNIT-IV

RESTful Web Services:

RESTful web services, or simply REST (Representational State Transfer), are a


popular architectural style used for designing networked applications. RESTful
services enable communication between systems over the internet, allowing clients to
access and manipulate resources on a server using a set of predefined operations.

Here are some key concepts and principles associated with RESTful web services:

1. Resources: In REST, everything is treated as a resource, such as an object, a


document, or a data entity. Resources are identified by unique URIs (Uniform
Resource Identifiers) and can be accessed via HTTP methods.
2. HTTP Methods: RESTful services utilize the standard HTTP methods for
performing different operations on resources. The commonly used methods are:
 GET: Retrieves the representation of a resource.
 POST: Creates a new resource.
 PUT: Updates an existing resource.
 DELETE: Deletes a resource.

Page 97
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

3. Uniform Interface: RESTful services follow a uniform interface constraint,


which means they have a consistent set of principles and conventions for interacting
with resources. This includes the use of HTTP methods, URIs, and standard response
codes.
4. Stateless: REST is stateless, which means that each request from a client to a
server must contain all the necessary information to understand and process the
request. The server does not maintain any client state between requests.
5. Representation: Resources are represented in a standardized format, such as
JSON (JavaScript Object Notation) or XML (eXtensible Markup Language). Clients
and servers can exchange representations of resources to communicate and perform
operations.
6. Hypermedia as the Engine of Application State (HATEOAS): HATEOAS is a
principle of REST that suggests including hyperlinks in the response to guide clients
on how to interact with the available resources. These hyperlinks provide a self-
descriptive API that allows clients to navigate the application state.

By following these principles, RESTful web services provide a scalable and flexible
architecture for building distributed systems. They are widely used for developing
web APIs, enabling different client applications (web, mobile, IoT, etc.) to interact
with server resources over the internet in a standardized manner.

RESTful Web Services Using the Uniform Interface:

RESTful web services adhere to the principles of the uniform interface, which
provides a consistent and standardized way for clients to interact with server
resources. The uniform interface in REST is based on the following key elements:

1. Resource Identification: Each resource in a RESTful service is uniquely


identified by a URI (Uniform Resource Identifier). URIs are used by clients to access
and manipulate the resources. For example, a URI like /users/123 can represent a
specific user resource with the ID 123.

Page 98
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

2. HTTP Methods: RESTful services utilize the standard HTTP methods to


perform different operations on resources. The commonly used methods are:
 GET: Retrieves the representation of a resource. Clients use this method
to retrieve data from the server.
 POST: Creates a new resource. Clients use this method to submit data to
the server for creation.
 PUT: Updates an existing resource. Clients use this method to send the
updated representation of a resource to the server.
 DELETE: Deletes a resource. Clients use this method to request the
removal of a resource from the server.
By using these HTTP methods, clients can perform specific actions on resources using
a uniform interface.
3. Representation: Resources in RESTful services are represented in a
standardized format, such as JSON or XML. Clients and servers exchange
representations of resources as part of their communication. The representation format
can be negotiated between the client and server using the Accept and Content-Type
headers in the HTTP request and response.
4. Self-Descriptive Messages: RESTful services rely on self-descriptive
messages, which means that each message contains enough information for the
recipient (client or server) to understand and process it. The messages typically
include metadata, such as HTTP headers, that provide additional context and
instructions.
5. Hypermedia Controls (HATEOAS): The principle of Hypermedia as the Engine
of Application State (HATEOAS) suggests including hyperlinks in the response to
guide clients on how to interact with the available resources. These hyperlinks are
embedded within the response and provide navigation links to related resources.
Clients can follow these links to discover and access other resources, allowing for a
self-descriptive API.

By following the principles of the uniform interface, RESTful web services provide a
standardized and interoperable approach for clients to interact with server resources.

Page 99
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

The uniformity of the interface simplifies client implementation and enables loose
coupling between the client and server, promoting scalability and flexibility in
distributed systems.

Designing URIs:

When designing URLs for RESTful web services, it's important to follow best
practices and adhere to the principles of REST. Here are some guidelines to consider:

1. Use Nouns to Represent Resources: URLs should be designed to represent


resources in a RESTful manner. Use nouns to identify the resources rather than verbs.
For example, use /users to represent a collection of users or /users/{id} to represent a
specific user.
2. Use Plural Nouns for Collections: When representing a collection of resources,
use plural nouns in the URL. For example, /users instead of /user for a collection of
users.
3. Maintain Consistency: Ensure consistency in your URL design throughout the
API. Use a consistent naming convention for resources and avoid unnecessary
variations. For example, if you use /users to represent users, be consistent and avoid
using /customers for a similar resource.
4. Avoid Nested URLs for Simplicity: Keep URLs simple and avoid excessive
nesting or deep hierarchies. Nested URLs can become complex and difficult to
manage. If necessary, limit the depth of nesting to a reasonable level.
5. Use Hyphens or Underscores for Readability: When separating words in a
URL, you can use hyphens (-) or underscores (_) for improved readability. For
example, /user-profiles or /user_profiles.
6. Include Resource Identifiers: Include resource identifiers in the URL to
represent individual resources. For example, /users/{id} to represent a specific user by
their ID.

Page 100
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

7. Use Query Parameters for Filtering, Sorting, and Pagination: Use query
parameters to handle filtering, sorting, and pagination requirements. For example,
/users?role=admin&sort=name to retrieve users filtered by role and sorted by name.
8. Avoid Including Actions in URLs: Instead of including actions (verbs) in
URLs, use appropriate HTTP methods to perform actions on resources. For example,
use POST to create a new resource, PUT to update a resource, and DELETE to
delete a resource.
9. Versioning: If you anticipate making changes to your API in the future,
consider incorporating versioning into the URL structure. For example, /v1/users to
represent the first version of the users resource.
10. Follow Security Considerations: Ensure URLs don't expose sensitive
information and implement proper security measures, such as authentication and
authorization, to protect your API.

Remember, designing URLs for RESTful web services should focus on creating a
clear, intuitive, and consistent structure that represents resources and promotes ease of
use for clients interacting with your API.

Weblinking:

Web linking, also known as Hypermedia as the Engine of Application State


(HATEOAS), is an important concept in RESTful web services. It involves including
hyperlinks within API responses to guide clients on how to interact with available
resources. The use of web links enables clients to discover and navigate the API
dynamically.

Here are some key points to understand about web linking in RESTful web services:

1. Hypermedia Controls: In RESTful services, API responses include hypermedia


controls or links. These links provide navigational information and options for clients
to perform actions on related resources. The links are typically embedded within the
response body or included in specific response headers.

Page 101
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

2. Resource Relationships: Web links help define relationships between resources.


They allow clients to traverse from one resource to another by following the provided
links. For example, a user resource may contain links to related resources such as their
posts or comments.
3. Self-Descriptive API: The inclusion of hyperlinks makes the API self-
descriptive. Clients can understand the available actions and resources by following
the links provided in the responses. This eliminates the need for clients to have prior
knowledge of the API structure and enables them to navigate and interact with
resources dynamically.
4. Discoverability: Web links facilitate the discoverability of resources within the
API. Clients can start with a known entry point, such as the API root URL, and
explore available resources by following the links provided in the responses. This
allows for a more flexible and adaptable client-server interaction.
5. Reduced Coupling: By relying on hypermedia controls, clients and servers
achieve loose coupling. Clients are not tightly bound to specific URI patterns or API
versions but instead rely on the provided links to navigate the API. This promotes
decoupling and allows for easier evolution and versioning of the API.
6. Link Relation Types: Links in RESTful services often include relation types
that indicate the semantics of the link. Common relation types include "self" (link to
the current resource), "next" (link to the next page in a paginated collection), "prev"
(link to the previous page), and custom relation types specific to the API's domain.
7. Link Format: Links typically include the URI of the related resource along with
other optional information such as the link's relation type and human-readable title.
The format commonly used to represent links in JSON is:

“rel”: “relation-type” ,

“href” : “https://example.com/resourse “,

“title” : “Link-Title”

Page 102
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

By incorporating web linking into RESTful web services, APIs become more self-
descriptive, discoverable, and adaptable. Clients can navigate the API dynamically by
following the provided links, reducing coupling and promoting a more flexible client-
server interaction.

Conditional Requests :

Conditional requests are a feature in RESTful web services that allow clients to
perform requests with certain conditions, enabling more efficient and optimized
interactions with the server. Conditional requests are based on HTTP headers and
status codes to indicate the conditions and responses to those conditions. Here are the
key components of conditional requests in RESTful web services:

1. ETag (Entity Tag): An ETag is an identifier associated with a specific version


of a resource. The server generates an ETag and includes it in the response headers
when a resource is requested. The ETag can be viewed as a unique fingerprint of the
resource's current state.
1. If-Match Header: Clients can include the ‘If-Match’header in their requests to
specify that the request should only be processed if the provided ETag matches the
current ETag of the resource on the server. If the ETags match, the request is
processed; otherwise, a ‘412 Precondition Failed’ status code is returned.
2. If-None-Match Header: The ‘If-None-Match’header allows clients to request a
resource only if it has been modified since a specified ETag value. If the current ETag
matches the provided ETag, the server returns a ‘304 Not Modified’ status code
without sending the resource again. This saves bandwidth and reduces unnecessary
data transfers.
3. Last-Modified Header: The ‘Last-Modified’ header is a timestamp indicating
the last modification time of a resource. It is returned by the server in the response
headers. Clients can include the ‘If-Modified-Since’ header in subsequent requests to
check if the resource has been modified since the specified timestamp. If the resource
has not been modified, the server returns a ‘304 Not Modified’ status code.

Page 103
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

4. If-Modified-Since Header: Clients can include the ‘If-Modified-Since’ header


in a request with a timestamp to indicate that the request should only be processed if
the resource has been modified since the provided timestamp. If the resource has not
been modified, the server returns a ‘304 Not Modified’ status code.

By utilizing these conditional request mechanisms, clients can minimize unnecessary


data transfer and reduce server load by only requesting and retrieving resources that
have been modified since their last retrieval. This helps improve performance and
efficiency in RESTful web service interactions.

ReactJS:

ReactJS, often referred to as React, is an open-source JavaScript library for building


user interfaces (UIs) and developing web applications. It was created by Facebook and
released in 2013. React allows developers to create reusable UI components and
efficiently update and render them when the underlying data changes.

Key features of React include:

1. Component-Based Architecture: React uses a component-based approach,


where UIs are built by combining reusable components. Each component manages its
own state and can be composed together to create complex user interfaces.
2. Virtual DOM: React introduces a virtual representation of the actual browser
Document Object Model (DOM) called the Virtual DOM. React's Virtual DOM allows
it to efficiently update and render only the necessary components when the application
state changes, leading to improved performance.
3. JSX: React utilizes JSX (JavaScript XML), which is an extension to JavaScript
syntax. It allows developers to write HTML-like code within JavaScript, making it
easier to define the structure and appearance of components.
4. Unidirectional Data Flow: React follows a unidirectional data flow, also known
as one-way data binding. Data flows from parent components to child components,
ensuring a predictable state management and making it easier to debug and understand
the application's behavior.

Page 104
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

5. React Native: React Native, a framework built on top of React, enables the
development of native mobile applications for iOS and Android platforms using
JavaScript. With React Native, developers can write a single codebase that runs on
multiple platforms, providing a significant advantage for cross-platform app
development.

React has gained popularity due to its simplicity, performance optimizations, and a
large ecosystem of community-driven libraries and tools. It is widely used by both
small and large organizations to build interactive and dynamic web applications.
Additionally, React's component-based architecture and declarative nature make it
easier to test, maintain, and collaborate on projects.

Obstacles and Roadblocks n React JS:

While React JS is a popular and powerful framework for building web applications,
developers may encounter certain obstacles or roadblocks during their journey. Here
are a few common challenges and ways to overcome them:

1. Learning Curve: React has a learning curve, especially for developers who are
new to JavaScript frameworks or have a background in different frameworks. It may
take time to grasp concepts like JSX, component lifecycle, state management, and
React's overall philosophy. To overcome this, it's recommended to follow official
documentation, tutorials, and online courses that provide step-by-step guidance.
Practice building small projects and gradually increase the complexity as you gain
more familiarity with React.
2. State Management: As applications grow in size and complexity, managing
application state becomes more challenging. React itself doesn't provide a built-in
solution for state management, so developers often rely on external libraries such as
Redux, MobX, or React Context API. These libraries help manage state in a more
structured and scalable manner. Understanding the principles and patterns of state
management libraries can help overcome this roadblock.

Page 105
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

3. Performance Optimization: While React's Virtual DOM efficiently updates and


renders components, it's still possible to encounter performance issues, especially
when dealing with large datasets or complex UIs. Common performance optimization
techniques in React include implementing shouldComponentUpdate or React.memo to
prevent unnecessary re-renders, using keys properly when rendering lists, and
employing code-splitting and lazy loading to improve initial load times. Profiling tools
like React DevTools and browser developer tools can help identify performance
bottlenecks and optimize the application.
4. Integration with Legacy Code: Integrating React into an existing codebase or
working with legacy code can be challenging. It's essential to understand how React
fits into the existing architecture and decide whether to introduce React incrementally
or refactor the entire codebase. Consider using React's integration capabilities, such as
ReactDOM.render() to embed React components into existing pages, or using React in
combination with other frameworks or libraries as needed.
5. Testing: Writing comprehensive and reliable tests for React components and
application logic is crucial for maintaining code quality. However, testing React
components may require additional setup and understanding of testing libraries like
Jest, Enzyme, or React Testing Library. Investing time in learning testing best
practices, writing unit tests for components, and using tools to simulate user
interactions can help ensure the stability and maintainability of your React
applications.

Remember that overcoming obstacles in React is a natural part of the learning process.
Don't hesitate to seek help from the vibrant React community through forums,
discussion boards, or social media groups. Many developers have faced similar
challenges and can provide guidance and insights to help you overcome any
roadblocks you encounter.

React’s Future: React has established itself as one of the most popular
JavaScript libraries for building user interfaces, and its growth and adoption continue
to be strong. Here are a few aspects that indicate a promising future for React:

Page 106
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

1. Continued Growth: React's popularity and usage have been steadily increasing
over the years, and there is no sign of a decline. Its large community of developers and
extensive ecosystem of libraries, tools, and resources contribute to its continued
growth and support.
2. React Native and Mobile Development: React Native, the framework built on
top of React, has gained significant traction in the mobile app development space. It
enables developers to build native mobile apps for multiple platforms using React and
JavaScript. With the rise of mobile app development and the demand for cross-
platform solutions, React Native is likely to play a crucial role in the future of mobile
development.
3. React Server Components: React Server Components is an experimental
feature introduced by the React team. It aims to bring the benefits of React's
component model to the server-side rendering (SSR) process. This can potentially
improve performance and facilitate seamless code sharing between client and server.
While still in the early stages of development, React Server Components could shape
the future of server-side rendering in React applications.
4. React as a UI Framework: React's component-based architecture and its ability
to create reusable UI components make it a powerful tool for building user interfaces.
With the rise of component-based development and design systems, React is likely to
continue playing a prominent role in the development of UI frameworks and libraries.
5. React Concurrent Mode: React Concurrent Mode is an upcoming feature aimed
at improving the performance and responsiveness of React applications. It introduces
new patterns and APIs to handle asynchronous rendering, allowing components to
work on different priorities and enable more interactive user experiences. Once fully
released, Concurrent Mode has the potential to further enhance React's capabilities
and user experience.

It's worth noting that the web development landscape is constantly evolving, and new
frameworks and technologies emerge over time. However, React's strong community
support, continuous updates, and the backing of Facebook make it well-positioned for
a promising future in the web development space.

Page 107
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

It's always a good practice to stay updated with the latest releases and developments in
the React ecosystem to leverage the newest features and best practices as they become
available.

Keeping Up with the Changes in ReactJS :

Keeping up with the changes in ReactJS is important to stay updated with the latest
features, improvements, and best practices. Here are some tips to help you stay
informed:

1. Official Documentation: The ReactJS documentation is the primary and most


reliable source of information. It provides comprehensive guides, tutorials, API
references, and examples. Regularly visit the official React documentation website
(https://reactjs.org/) to explore the latest updates and new features.
2. React Blog: The React team maintains an official blog
(https://reactjs.org/blog/) where they share announcements, updates, and insights
about React. Subscribe to the blog's RSS feed or sign up for the React newsletter to
receive notifications about new releases and important updates.
3. GitHub Repository: React's GitHub repository
(https://github.com/facebook/react) is where the React source code resides. By
monitoring the repository, you can keep track of the latest commits, issues, and
discussions. Additionally, you can star the repository to receive notifications about
new releases and updates.
4. Community Forums and Discussion Boards: Participate in React-related
forums and discussion boards to connect with the community, ask questions, and share
knowledge. The React subreddit (https://www.reddit.com/r/reactjs/) and the Reactiflux
Discord community (https://www.reactiflux.com/) are popular platforms for
discussions and Q&A.
5. React Conferences and Meetups: Attend React conferences and local meetups
to learn from industry experts, listen to talks, and engage in discussions about the

Page 108
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

latest trends and updates in React. These events often provide valuable insights and
networking opportunities.
6. Follow Influencers and Experts: Follow influential developers, React core team
members, and experts on social media platforms like Twitter and LinkedIn. They often
share their thoughts, insights, and updates about React, keeping you informed about
the latest happenings.
7. Newsletters and Podcasts: Subscribe to React-focused newsletters and podcasts
that provide regular updates and insights about React. Some popular newsletters
include "React Status" (https://react.statuscode.com/) and "React Digest"
(https://reactdigest.net/). Podcasts like "React Podcast" and "React Native Radio" also
cover React-related topics.
8. Open Source Projects and Libraries: Explore open source projects and libraries
built on top of React. These projects often reflect the latest trends and best practices in
React development. Following their repositories and documentation can help you stay
updated.

Remember that React is an evolving ecosystem, and it's important to allocate time
regularly to stay up to date. Experiment with new features, read release notes, and
consider updating your projects to newer versions of React when appropriate. By
actively engaging with the React community and staying informed about the latest
developments, you can ensure that your React skills and projects remain relevant and
up to date.

Working with the Files in ReactJS

Working with files in ReactJS typically involves handling file uploads, processing file
data, and interacting with the user's filesystem. Here's a high-level overview of file-
related operations in ReactJS:

1. File Input and Uploads: To enable file uploads, you can use the HTML ‘<input
type="file">’ element. In React, you can create a controlled component that handles
the file input value and listens to changes using the ‘onChange’ event. You can then

Page 109
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

retrieve the selected file(s) from the input element and perform actions like displaying
file information, validating file types/sizes, and initiating file uploads to a server or
cloud storage.
2. File Processing: Once a file is uploaded or selected by the user, you may need
to process its contents. Common scenarios include reading file data, parsing file
formats (e.g., CSV, JSON), or performing client-side transformations. The FileReader
API or third-party libraries like Papa Parse or XLSX can be used to read and process
file data in various formats.
3. File Downloads: React provides ways to initiate file downloads from the client-
side. You can create a link (‘<a>’) element with the desired file URL and set the
‘download’ attribute to specify the desired file name. Clicking on this link triggers the
download. Alternatively, you can use third-party libraries or APIs for more advanced
download functionality, such as generating files dynamically or downloading files
from external sources.
4. Drag and Drop: React allows you to implement drag-and-drop functionality to
enable users to drag files from their filesystem and drop them onto a designated area
in the application. By handling the ‘drag’ and ‘drop’ events, you can retrieve the
dropped files, validate them, and perform actions accordingly.
5. File Validation and Error Handling: When working with files, it's important to
validate user inputs and handle errors gracefully. You can check file types, sizes, and
other properties to ensure they meet your application's requirements. Display
appropriate error messages or feedback to the user if the file is invalid or if any errors
occur during file operations.
6. Third-Party Libraries: React has a vast ecosystem of third-party libraries that
can simplify file-related tasks. Libraries like react-dropzone, react-filepond, and react-
dropzone-uploader provide pre-built components and APIs for handling file uploads
and drag-and-drop functionality. Evaluate these libraries to see if they meet your
specific requirements and integrate them into your React application.

Page 110
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

Remember to consider security aspects when dealing with file uploads and processing.
Implement server-side validation and sanitization to prevent malicious file uploads
and potential security vulnerabilities.

Working with files in ReactJS often involves a combination of JavaScript, HTML, and
CSS, along with the React component lifecycle and state management. By
understanding these concepts and utilizing appropriate libraries and APIs, you can
effectively handle file-related operations in your React applications.

Pure React:

Pure React, also known as Vanilla React, refers to using React without any additional
libraries or frameworks. It means leveraging only the core capabilities and APIs
provided by React itself, without relying on external dependencies like state
management libraries or UI frameworks.

When working with pure React, you primarily use React's core concepts, including
components, JSX, state, and lifecycle methods. Here's an overview of how these key
aspects work in pure React:

1. Components: React is built around the concept of components, which are


reusable, self-contained pieces of UI. Components can be functional components
(using functions) or class components (using ES6 classes). Components encapsulate
their own logic and state and can be composed together to build complex UIs.
2. JSX: JSX is a syntax extension for JavaScript that allows you to write HTML-
like code within your JavaScript code. It is used to define the structure and appearance
of React components. JSX makes it easier to write and visualize the component
hierarchy.
3. State: React components can have state, which is an object that stores data that
can change over time. State allows you to manage dynamic data within a component
and triggers re-rendering when the state updates. In pure React, you typically use the
setState method to update the component's state and trigger a re-render.

Page 111
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

4. Lifecycle Methods: React components have lifecycle methods that are called at
different stages of a component's life, such as mounting, updating, and unmounting.
These methods allow you to perform actions at specific points in the component's
lifecycle, like initializing state, making API calls, or cleaning up resources.

By using these core features of React, you can build interactive user interfaces and
handle user interactions effectively. However, keep in mind that as your application
grows in complexity, you may need to consider additional libraries or patterns for state
management, routing, and other advanced functionalities. Redux, React Router, and
other libraries can be introduced as needed, based on your project requirements.

Using pure React can be beneficial in terms of simplicity, learning the core concepts
deeply, and having full control over your application. It also helps to have a better
understanding of how React works under the hood. However, it's important to strike a
balance between leveraging the power of React itself and utilizing third-party libraries
to enhance productivity and maintainability in larger projects

Pagesetup n ReactJS:

In ReactJS, setting up pages involves creating components that represent different


pages or views of your application. Here's a general approach to setting up pages in
ReactJS:

1. Create Page Components: Identify the different pages or views of your


application and create separate components for each page. These components will
serve as the containers for the content and functionality specific to each page. For
example, you might have components like HomePage, AboutPage, ContactPage, etc.
2. Define Routes: To handle navigation between pages, you need to set up routing
in your React application. React Router is a popular library for handling routing in
React. Install React Router using npm or yarn, and define routes in your application.
Routes specify the URL paths and the corresponding page components to render. For

Page 112
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

example, you can define a route for the home page ("/") to render the HomePage
component.
3. Render Pages: In your main application component, typically named App,
import the necessary page components and set up the routing configuration provided
by React Router. Inside the component, use the Router and Route components from
React Router to map the defined routes to their respective page components. This
ensures that the correct page component is rendered based on the current URL.
4. Linking and Navigation: Use the Link component from React Router to create
links between different pages within your application. The Link component generates
anchor tags with proper URL routing, allowing users to navigate between pages
without reloading the entire application. For example, you can use the Link
component to create a navigation bar with links to different pages.
5. Page Content and Functionality: Each page component should contain the
specific content and functionality relevant to that page. Customize the content, layout,
and behavior of each page according to its requirements. You can utilize other React
components, state management techniques, and API integrations as needed for each
page.

By following this approach, you can set up pages in your ReactJS application, enable
routing between them, and define the content and functionality specific to each page.
React Router provides a flexible and powerful way to handle page navigation and
URL routing in React applications, making it easier to create multi-page applications
or single-page applications with multiple views.

Virtual DOM in ReactJS:

The Virtual DOM is a key concept in ReactJS that contributes to its efficient rendering
and performance optimizations. Here's an explanation of what the Virtual DOM is and
how it works:

1. What is the Virtual DOM? The Virtual DOM is a lightweight representation of


the actual browser Document Object Model (DOM). It is a JavaScript object that

Page 113
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

mirrors the structure of the real DOM but lacks the ability to directly interact with the
browser.
2. How does the Virtual DOM work? When a React component's state or props
change, React creates a new Virtual DOM representation of the component and
compares it with the previous Virtual DOM. This process is known as reconciliation
or diffing.
3. Reconciliation process: React's reconciliation process involves three main
steps:
a. Diffing: React compares the new Virtual DOM with the previous one, identifying
the differences between them. It efficiently determines which parts of the UI need to
be updated.
b. Re-rendering: React updates only the necessary parts of the real DOM based on the
differences identified during the diffing process. It minimizes the number of actual
changes made to the DOM.
c. Patching: React updates the affected elements in the real DOM by applying the
necessary changes in an optimized manner, resulting in an updated UI.
4. Benefits of the Virtual DOM:
 Performance Optimization: The Virtual DOM allows React to minimize
costly direct manipulations of the real DOM by efficiently updating only the
necessary parts. This helps to improve the overall performance of React
applications.
 Reusability and Maintainability: React's component-based architecture,
combined with the Virtual DOM, enables the reusability of components and
modular development. Components can be composed, updated independently,
and easily maintained.
 Cross-platform Support: The Virtual DOM works consistently across
different platforms and browsers, providing a unified approach to UI rendering
and making React suitable for multi-platform development.

It's important to note that the Virtual DOM is an implementation detail of React. It
abstracts away the low-level manipulations of the real DOM, making it easier for

Page 114
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

developers to work with and reason about UI updates. However, understanding the
Virtual DOM can help in optimizing React applications and utilizing React's
performance features effectively.

React Elements: In ReactJS, React Elements are the building blocks used to
describe and represent the UI hierarchy. They are lightweight JavaScript objects that
represent components, DOM elements, or fragments. React Elements are created
using JSX or React's createElement() function.

Here's an overview of React Elements and how they are used in React:

1. Creating React Elements:


 JSX: JSX is a syntax extension in React that allows you to write HTML-like
code within JavaScript. JSX is used to define React Elements by wrapping them in
tags that resemble HTML or custom components. For example:

const element = <h1>Hello, World!</h1>;


 createElement(): React also provides a createElement() function to create React
Elements directly without JSX. The createElement() function takes three arguments:
the element type (component or DOM element name), optional properties or
attributes, and child elements. For example:

const element = React.createElement('h1', null, 'Hello, World!');


2. Structure and Properties: React Elements have a specific structure that consists
of a type, properties (also known as props), and children. The type can be a string
representing a DOM element (e.g., 'div', 'span') or a reference to a custom component.
Properties are key-value pairs that provide additional information to the element.
Children can be other React Elements or text content. For example:
const element = <div className="container">Hello, <strong>React</strong>!</div>;
>React</strong>!</div> ;

Page 115
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

3. Rendering React Elements: React Elements are typically rendered to the actual
DOM using ReactDOM's render() function. The render() function takes a React
Element and a target DOM node as arguments and inserts the rendered output into the
target node. For example:
4. const element = <h1>Hello, World!</h1>;
ReactDOM.render(element, document.getElementById('root'));
4. React Components and React Elements: React Components are reusable and
self-contained units of UI logic. When you define a component, you create React
Elements that represent instances of that component. Components are used to
compose the UI hierarchy by creating and nesting React Elements.
5. Immutable Nature: React Elements are immutable, meaning they cannot be
modified directly. Instead, when a change occurs in the application state or props,
React creates a new set of React Elements and performs a reconciliation process to
update the UI efficiently.

React Elements form the foundation of React's declarative approach to building user
interfaces. They describe the desired UI structure and appearance, and React takes
care of efficiently updating and rendering the UI based on changes to the Elements or
underlying data.

React DOM:

ReactDOM is a package in React that provides the methods and APIs for rendering
React components to the actual browser DOM. It acts as the bridge between React's
virtual representation of the UI (Virtual DOM) and the real DOM.

Here are some key aspects of ReactDOM:

1. ReactDOM.render(): The render() method from ReactDOM is used to render a


React element or component to a target DOM element in the HTML document. It
takes two arguments: the React element or component to render and the target DOM
node where the rendered output will be inserted. For example:

Page 116
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

Import ReactDom from ‘react-dom’;


Const element = <h1> Hello,world!</h1>;
ReactDom.render
ReactDOM.render(element, document.getElementById('root'));

In this example, the element is rendered and inserted into the DOM element with the
id 'root'.

2. ReactDOM.hydrate(): The hydrate() method is similar to render(), but it is


specifically used for server-side rendering (SSR). It hydrates a server-rendered HTML
into a React application, attaching event listeners and preserving the interactivity of
the rendered UI. The usage is similar to render(), but it is typically used in
combination with server-side rendering frameworks.
3. ReactDOM.unmountComponentAtNode(): This method is used to unmount
and remove a React component from the DOM. It takes a DOM node as an argument
and removes the component rendered within that node. For example:
ReactDOM.unmountComponentAtNode(document.getElementById('root'));

4. Other Methods: ReactDOM provides additional methods for working with the
DOM, such as:
 ReactDOM.findDOMNode(): This method returns the DOM node
associated with a mounted React component. It should be used with caution as
it is considered an escape hatch and is discouraged in most cases.
 ReactDOM.createPortal(): This method allows rendering React
components into a different DOM subtree, typically outside the current
component's hierarchy. It is useful for scenarios like modals or overlays.

Overall, ReactDOM serves as the interface between React components and the
browser's DOM. It facilitates the rendering of React components, updates to the UI
based on changes in React Elements, and the management of component lifecycles.

Children:

Page 117
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

Children

In React, the concept of "children" refers to the content that is nested inside a
component. It allows you to pass arbitrary content or components as props to a parent
component and render them within the parent's JSX structure.

To understand how children work, let's consider an example:

import React from 'react';

const ParentComponent = ({ children }) => {

return (

<div>

<h1>Parent Component</h1>

{children}

</div>

); };

const App = () => {

return (

<ParentComponent>

<p>This is a child element.</p>

<button>Click me!</button>

</ParentComponent>

); };

export default App;

In this example, we have a ‘ParentComponent’ that accepts a prop called ‘children’.


Inside the ‘ParentComponent’ JSX, we include ‘{children}’ which will render
whatever content is passed as the children of the component.

Page 118
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

When the’ ParentComponent ‘is rendered, the children will be inserted at the
location of ‘{children}’ in the JSX. So, the rendered output will look like this:

The’ children’ prop can also be an array or multiple elements. For example:

<ParentComponent>

<p>First child</p>

<p>Second child</p>

</ParentComponent>

In this case, the ‘children’ prop will be an array of two paragraph elements, and they
will be rendered accordingly.

Using the concept of children, you can create reusable components that wrap and
render different content depending on how they are used. It provides a flexible way to
compose components and build complex UI structures in React.

Constructing Elements with Data in ReactJS:

In React, you can construct elements with data by dynamically generating and
rendering components based on the data you have. This is commonly done using
JavaScript's array methods, such as’ map()’, to iterate over the data and generate a
collection of components.

Here's an example of constructing elements with data in React:

import React from 'react';

const data = [

{ id: 1, name: 'John' },

Page 119
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

{ id: 2, name: 'Jane' },

{ id: 3, name: 'Bob' }

];

const App = () => {

return (

<div>

<h1>User List</h1>

<ul>

{data.map(user => (

<li key={user.id}>{user.name}</li>

))}

</ul>

</div>

);

};

export default App;

In this example, we have an array called ‘data’ that contains user objects. The ‘App’
component renders a list of users by mapping over the ‘data’ array using the ‘map()’
method. For each user, a ‘<li>’ element is generated with the user's name as the
content. The ‘key’ prop is set to the ‘id’ property of each user, which helps React
efficiently update and re-render the list.

The rendered output will look like this:

<div>

Page 120
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

<h1>User List</h1>

<ul>

<li>John</li>

<li>Jane</li>

<li>Bob</li>

</ul>

</div>

By dynamically generating elements with data, you can easily handle lists, tables, or
any other structured data in your React components. This approach allows for
flexibility and reusability, as the components can adapt to different datasets.

By dynamically generating elements with data, you can easily handle lists, tables, or
any other structured data in your React components. This approach allows for
flexibility and reusability, as the components can adapt to different datasets.

React Components:

In React, components are the building blocks of a user interface. They are reusable,
self-contained pieces of code that encapsulate a specific functionality and render a part
of the UI. React components can be either class-based or function-based.

Class-based components (prior to React 16.8) are defined using ES6 classes and
extend the ‘React.Component’ class. They have a ‘render() ‘method that returns the
JSX to be rendered. Here's an example of a class-based component:

import React from 'react';

class MyComponent extends React.Component {

render() {

Page 121
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

return <h1>Hello, World!</h1>;

Function-based components (introduced in React 16.8 with the introduction of Hooks)


are defined as JavaScript functions. They receive props as input and return JSX.
Here's an example of a function-based component:

import React from 'react';

const MyComponent = (props) => {

return <h1>Hello, {props.name}!</h1>;

};

Components can also accept and handle props, which are essentially the properties or
configuration values passed to a component from its parent component. Props allow
components to be dynamic and customizable. Here's an example of a component that
accepts props:

import React from 'react';

const Greeting = (props) => {

return <h1>Hello, {props.name}!</h1>;

};

const App = () => {

return <Greeting name="John" />;

};

In this example, the ‘Greeting’ component receives the ‘name’ prop and renders a
personalized greeting.

Page 122
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

Components can be composed together to create complex UI structures. They can also
maintain an internal state using the ‘useState’ hook (in function components) or by
extending the ‘React.Component’ class and using the ‘state’ property (in class
components). State allows components to manage and update their data over time.

React components follow a unidirectional data flow, where the parent component
passes data down to child components via props. Changes in the data are propagated
from the top-level component down to its children, triggering re-renders as needed.

By organizing the UI into components, React provides a modular and reusable


approach to building user interfaces, making it easier to develop and maintain
complex applications.

DOM Rendering:

DOM rendering in React refers to the process of taking React components and
rendering them as elements in the browser's Document Object Model (DOM). React
uses a virtual DOM (a lightweight copy of the actual DOM) to efficiently update and
reconcile changes in the UI.

When you render a React component, it generates a virtual representation of the


component's UI structure called a React element. This element is a plain JavaScript
object that describes what should be rendered. React uses this element and its
associated components to build a virtual DOM tree.

Once the virtual DOM tree is constructed, React compares it with the previous version
of the virtual DOM (from the previous render) to identify any differences. This
process is known as reconciliation.

React determines the minimal set of changes needed to update the actual DOM based
on the differences found during reconciliation. It then applies these changes to the real
DOM, resulting in an updated user interface.

Page 123
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

The ReactDOM library provides the render() function, which is used to render a
React component or element onto the real DOM. Here's an example:

import React from 'react';

import ReactDOM from 'react-dom';

const App = () => {

return <h1>Hello, world!</h1>;

};

In this example, we have a simple’ App ‘component that renders an ‘<h1>’ element
with the text "Hello, world!". The ‘ReactDOM.render()’ function is used to render
the ‘App’ component into the DOM. The resulting output is inserted into the element
with the ‘id’, "root" in the HTML file.

React components are designed to be reusable and composable, allowing you to build
complex UI structures by combining smaller components. When changes occur to the
component's state or props, React efficiently updates only the necessary parts of the
DOM, resulting in better performance compared to traditional manual DOM
manipulation.

By using the virtual DOM and reconciliation process, React abstracts away the
complexities of directly interacting with the real DOM, making it easier to build
interactive and responsive user interfaces.

Factories:

In the context of React, a factory is a function or a higher-order component (HOC)


that generates and returns a new React component. Factories are often used to create
components with pre-configured props or behavior, allowing for code reuse and
abstraction.

There are two common types of factories in React:

Page 124
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

1. Component Factories: These are functions that create and return React
components. They can be used to generate components with specific props or
behaviors. Here's an example of a component factory:

import React from 'react';

const createCustomComponent = (propValue) => {

return (props) => (

<div>

<h1>{props.title}</h1>

<p>{propValue}</p>

</div>

);

};

In this example, createCustomComponent is a component factory that takes a


propValue argument and returns a new component. The returned component renders a
<div> with an <h1> and a <p> tag. The title prop is passed to the generated
component, and propValue is used as the content of the <p> tag. The factory allows
you to create multiple instances of the component with different values.

2. Higher-Order Component (HOC) Factories: HOCs are functions that take a


component as input and return a new enhanced component. HOC factories are
functions that generate and return HOCs. They are commonly used to add additional
behavior or wrap components with certain functionalities. Here's an example:

import React from 'react';

Page 125
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

const withLogger = (WrappedComponent) => {

return (props) => {

console.log('Component Rendered:', WrappedComponent.name);

return <WrappedComponent {...props} />;

};

};

// Usage:

const MyComponent = (props) => {

return <div>{props.message}</div>;

};

const EnhancedComponent = withLogger(MyComponent);

const App = () => {

return <EnhancedComponent message="Hello, World!" />;

};

// Usage:

const CustomComponent = createCustomComponent('Custom Value');

const App = () => {

return <CustomComponent title="Hello Factory" />;

};

In this example, withLogger is an HOC factory that takes a


component (WrappedComponent) and returns a new HOC. The returned
HOC logs the name of the wrapped component when it renders
and then renders the wrapped component with the passed props.
The factory allows you to create multiple enhanced components
with different functionalities.

Page 126
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

Factories in React provide a powerful way to generate


components with desired configurations or behaviors. They allow
for code reuse, abstraction, and composition of components,
making it easier to build scalable and maintainable React
applications.

Page 127
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

 Faster Processing: SAX can be faster than DOM for large XML files since it
processes data in a streaming manner without the need to construct and store the entire
document tree.
 Suitable for Large Documents: SAX is suitable for scenarios where memory
usage is a concern or when you need to process large XML documents sequentially
without requiring random access to the entire document structure.

The choice between DOM and SAX depends on the specific requirements of your
application. Use DOM when you need random access, modification, and querying
capabilities for XML documents. On the other hand, if you have memory constraints
or need to process large XML files sequentially, SAX provides a lightweight and
efficient solution for parsing and processing XML dataV

UNIT-V

MongoDB:

MongoDB is a popular open-source NoSQL database management system. It is


designed to store and manage large volumes of unstructured data. Here are some key
concepts and features of MongoDB:

1. Document-Oriented: MongoDB stores data in flexible, JSON-like documents


called BSON (Binary JSON) documents. BSON documents are schema-less, meaning
each document can have a different structure, allowing for easy storage and retrieval
of complex data.
2. Collections: MongoDB organizes documents into collections, which are
analogous to tables in relational databases. Collections are schema-less and can
contain documents with varying structures.
3. CRUD Operations: MongoDB supports CRUD operations (Create, Read,
Update, Delete) for working with data. You can insert documents into a collection,
query and retrieve documents based on various criteria, update existing documents,
and delete documents.

Page 128
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

4. Query Language: MongoDB uses a powerful and flexible query language that
allows you to retrieve specific documents from a collection. The query language
supports a wide range of operators for filtering, sorting, and aggregating data.
5. Indexing: MongoDB supports indexing to improve query performance. Indexes
are data structures that store a subset of the data in a more efficient format, enabling
faster data retrieval.
6. Replication: MongoDB provides replication for high availability and data
redundancy. Replication allows you to create multiple copies of data across different
servers, ensuring that if one server fails, another can take its place.
7. Sharding: MongoDB supports sharding, which allows you to distribute data
across multiple servers or clusters. Sharding enables horizontal scaling and can handle
large amounts of data by dividing it into smaller chunks called shards.
8. Geospatial Indexing: MongoDB has built-in support for geospatial data,
allowing you to store and query location-based information such as points, polygons,
and distances.
9. Aggregation Framework: MongoDB provides a powerful Aggregation
Framework that allows you to perform complex data processing and analysis
operations, including grouping, sorting, filtering, and transforming data.
10. Integration with Programming Languages: MongoDB offers official drivers for
various programming languages, making it easy to interact with the database from
applications written in languages like JavaScript, Python, Java, C#, and more.

MongoDB is widely used in modern web development, particularly in scenarios where


flexibility, scalability, and performance are crucial. It is often used in conjunction with
JavaScript-based frameworks like Node.js for full-stack JavaScript development.

Architecture of Mongodb

The architecture of MongoDB revolves around the principles of scalability, flexibility,


and performance. MongoDB follows a distributed, document-oriented architecture

Page 129
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

that allows for horizontal scaling and efficient handling of large volumes of data. Here
are the key components and concepts in the architecture of MongoDB:

1. Nodes: MongoDB deployments consist of one or more nodes. A node is an


instance of the MongoDB server that stores and manages data. Nodes can be
distributed across different servers or cloud instances.
2. Replica Sets: A replica set is a group of MongoDB nodes that work together to
provide high availability and data redundancy. A replica set typically consists of
multiple nodes, with one primary node that handles all write operations and one or
more secondary nodes that replicate data from the primary node.
3. Sharding: Sharding is a technique used in MongoDB to horizontally partition
data across multiple nodes or clusters. Sharding allows for distributing data based on a
shard key, which determines how data is divided and distributed. Each shard contains
a subset of the data, enabling efficient scaling and performance.
4. Shards: Shards are individual nodes or clusters that store a portion of the data.
They can be standalone MongoDB nodes or replica sets. Each shard is responsible for
storing and managing a specific range of data based on the shard key.
5. Config Servers: Config servers store metadata and configuration information
about the sharded cluster. They maintain a mapping between data and the shards that
contain it. Config servers allow for dynamic scaling and management of the sharded
cluster.
6. Routing and Query Routing: In a sharded environment, the MongoDB router,
also known as the mongos process, acts as an interface between clients and the
underlying shards. The router receives queries from clients, determines the relevant
shards based on the shard key, and routes the queries to the appropriate shards for
processing.
7. Balancer: The balancer is a component that automatically redistributes data
across shards to ensure an even distribution and optimal performance. The balancer
monitors the data distribution and migrates chunks of data between shards as needed.

Page 130
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

8. WiredTiger Storage Engine: MongoDB utilizes the WiredTiger storage engine


as its default storage engine. WiredTiger provides efficient data compression,
concurrency control, and transaction support, enhancing performance and scalability.
9. Drivers and APIs: MongoDB provides official drivers and APIs for various
programming languages, allowing developers to interact with the database from their
applications. These drivers abstract the complexity of the underlying MongoDB
architecture and provide a convenient interface for CRUD operations, query
execution, and data manipulation.

Overall, MongoDB's architecture offers a flexible and scalable approach to handling


large volumes of data. It leverages replica sets for high availability and fault tolerance,
sharding for horizontal scaling, and efficient data distribution across nodes. The
combination of these components enables MongoDB to deliver high-performance and
flexible database solutions for modern applications.

Features of mongodb

MongoDB offers a wide range of features that make it a popular choice for modern
application development. Here are some key features of MongoDB:

1. Document-Oriented: MongoDB is a document-oriented database, where data is


stored in flexible, schema-less JSON-like documents called BSON. This allows for
easy storage and retrieval of complex, hierarchical data structures.
2. Flexible Schema: MongoDB's flexible schema allows documents in a
collection to have different structures, making it easier to handle evolving data models
without the need for migrations or downtime. This flexibility is particularly useful in
agile development and prototyping.
3. Scalability: MongoDB supports horizontal scalability through sharding.
Sharding distributes data across multiple nodes or clusters, allowing for linear

Page 131
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

scalability as data volumes grow. It enables applications to handle high traffic and
large datasets by dividing data into smaller subsets called shards.
4. High Availability: MongoDB provides high availability through replica sets. A
replica set is a group of MongoDB nodes that maintain multiple copies of the data. If a
primary node fails, a secondary node automatically takes over, ensuring continuous
availability of the database.
5. Indexing and Querying: MongoDB supports various types of indexes, including
single-field, compound, geospatial, and text indexes. Indexing improves query
performance by enabling efficient data retrieval based on specified criteria.
MongoDB's flexible query language allows for powerful querying capabilities,
including rich filtering, sorting, and aggregation operations.
6. Full-Text Search: MongoDB offers built-in full-text search capabilities that
allow you to perform complex text-based queries on textual data within documents. It
supports text indexes and powerful search operators to perform text search efficiently.
7. Aggregation Framework: MongoDB provides a powerful Aggregation
Framework that allows for data transformation, grouping, filtering, and analysis
operations. It enables developers to perform complex data processing within the
database, reducing the need for additional data processing layers.
8. Geospatial Capabilities: MongoDB has built-in support for geospatial data and
offers various geospatial operators and indexes. This enables storing and querying of
location-based data, making it suitable for applications involving geolocation and
mapping.
9. ACID Transactions: Starting from version 4.0, MongoDB supports multi-
document ACID transactions, allowing you to maintain data consistency and integrity
across multiple operations. Transactions ensure that a group of database operations
either succeeds in its entirety or fails entirely.
10. Security: MongoDB provides robust security features, including authentication,
authorization, and role-based access control (RBAC). It also supports Transport Layer
Security (TLS) encryption for secure communication between clients and the
database.

Page 132
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

11. Integration and Ecosystem: MongoDB offers official drivers and libraries for
various programming languages, making it easy to integrate MongoDB with different
application stacks. Additionally, MongoDB has a thriving ecosystem with a wide
range of tools, frameworks, and community resources to support developers.

These features make MongoDB a flexible, scalable, and developer-friendly database


solution for building modern applications. Its document-oriented nature, rich querying
capabilities, and ability to handle complex data make it well-suited for use cases such
as content management systems, real-time analytics, e-commerce platforms, and
more.

Examples of mongodb

1. Content Management Systems (CMS): MongoDB can be used as the backend


database for content management systems. It allows for flexible schema design,
making it easy to store and retrieve various types of content such as articles, images,
videos, and user-generated data.
2. Real-Time Analytics: MongoDB is well-suited for real-time analytics
applications. It can store and process large volumes of data in real-time, enabling
businesses to analyze and gain insights from streaming data, user interactions, and
system logs.
3. E-commerce Platforms: MongoDB can power e-commerce platforms by
storing product catalogs, user profiles, shopping carts, and order data. Its flexible
schema allows for easy modifications to product attributes or customer data without
downtime. MongoDB's ability to handle high traffic and scale horizontally is
beneficial for handling a large number of product listings and user interactions.
4. Internet of Things (IoT): MongoDB is used in IoT applications for storing
sensor data, monitoring devices, and managing real-time data streams. Its ability to
handle high data ingestion rates, flexibility in handling different data formats, and
support for geospatial data make it suitable for managing and analyzing IoT data.

Page 133
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

5. Social Networks and User-generated Content: MongoDB's document-oriented


model is ideal for storing and querying user-generated content in social networks. It
can efficiently handle the storage and retrieval of user profiles, posts, comments, and
relationships between users.
6. Location-based Services: MongoDB's geospatial capabilities make it a good fit
for applications that involve location-based services. It can store and query geospatial
data such as coordinates, polygons, and distances, enabling the development of
applications like mapping, location-based recommendations, and tracking systems.
7. Content Caching and Personalization: MongoDB can be used as a caching
layer to store frequently accessed data in memory, reducing the load on backend
systems. It allows for fast retrieval and updates of cached content, making it suitable
for applications that require high-performance content delivery and personalized user
experiences.

These examples demonstrate the versatility and applicability of MongoDB in various


domains. MongoDB's flexibility, scalability, and performance make it a popular
choice for modern applications that handle large volumes of data and require agile
data modeling.

database collection and creation in mongodb

In MongoDB, a collection is a grouping of MongoDB documents. It is analogous to a


table in relational databases. Collections are schema-less, meaning that each document
in a collection can have a different structure. Here's how you can create a database and
collection in MongoDB:

1. Connect to MongoDB: First, you need to establish a connection to your


MongoDB server. You can use the MongoDB shell or a programming language-
specific MongoDB driver to connect. Here's an example using the MongoDB shell:
Shell copycode

mongo

Page 134
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

2. Create a Database: In MongoDB, you can create a new database by using the
use command. If the database doesn't exist, MongoDB will create it when you insert
data into it. For example, to create a database called "mydatabase", run the following
command:

Shell copycode

Use mydatabase

3. Create a Collection: Once you have a database, you can create a collection by
simply starting to insert documents into it. When you insert the first document,
MongoDB will create the collection if it doesn't already exist. For example, to create a
collection called "mycollection" and insert a document into it, run the following
command

" })
4. Verify Collection Creation: To verify that the collection has been created, you
can use the show collections command or db.getCollectionNames() method. For
example:

show collections

or

Page 135
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

This will display a list of collections in the current database, and you should see
"mycollection" in the list.

Congratulations! You have now created a database and a collection in MongoDB. You
can continue inserting more documents into the collection or perform various
operations like querying, updating, and deleting documents within the collection.

Deploying appilications in monodb:

MongoDB is a database management system and is not directly involved in the


deployment of applications. However, I can provide guidance on how to deploy an
application that uses MongoDB as its database.

When deploying an application that uses MongoDB, you need to consider the
following steps:

1. Set Up MongoDB: Ensure that you have a MongoDB server or cluster


available for your application to connect to. This could be a local MongoDB
installation or a cloud-hosted MongoDB service like MongoDB Atlas.
2. Connect to MongoDB: Update your application's database configuration to
point to the MongoDB server or cluster. Provide the necessary connection details such
as the host, port, and credentials (username and password).
3. Prepare Application Files: Package your application files, including the
necessary server-side code, client-side code, and any dependencies. This may involve
bundling your code using build tools like webpack or creating a Docker container.
4. Choose a Hosting Environment: Select a hosting environment where you will
deploy your application. It could be a cloud service provider like AWS, Azure, or
Google Cloud, or a dedicated server or VPS provider.

Page 136
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

5. Deploy Application Files: Depending on your hosting environment, there are


various ways to deploy your application files. Some common methods include:
 Using FTP or SFTP to upload the files to a server.
 Using version control systems like Git to clone the repository onto the
server.
 Using deployment tools or platforms like Heroku or Netlify that
integrate with MongoDB and provide seamless deployment workflows.
6. Set Environment Variables: Ensure that your application has the necessary
environment variables set, including the MongoDB connection details and credentials.
This is important for securely accessing your MongoDB database.
7. Test and Verify: Once deployed, thoroughly test your application to ensure that
it can successfully connect to the MongoDB database and perform the expected
operations. Verify that the application functions as intended in the deployment
environment.

Remember to follow best practices for security, performance, and scalability when
deploying your application. It's also important to consider backup and disaster
recovery strategies for your MongoDB database to safeguard your data.

webhosting and domains

Web hosting and domains are essential components for making a website accessible
on the internet. Here's a brief overview of each:

1. Web Hosting: Web hosting involves the storage and serving of website files and
data on servers that are connected to the internet. When you choose a web hosting
service, you essentially rent space on a server where you can store your website files,
databases, and other resources.

Types of Web Hosting:

Page 137
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

 Shared Hosting: Multiple websites are hosted on a single server, sharing its
resources.
 Virtual Private Server (VPS) Hosting: Provides dedicated resources within a
shared environment by creating virtual servers.
 Dedicated Hosting: Offers an entire physical server dedicated to a single
website or application.
 Cloud Hosting: Utilizes a network of interconnected servers to distribute
resources and ensure scalability.

Web hosting providers typically offer various plans with different features and pricing
options. When selecting a web hosting provider, consider factors like reliability,
performance, security measures, customer support, and the specific needs of your
website or application.

2. Domain: A domain is the unique address or URL that users type into their
browsers to access a website. For example, "example.com" is a domain. Domain
names provide a more user-friendly way to identify websites instead of using IP
addresses.

Domain Registration and Management:

 Registering a Domain: You can register a domain through domain registrars,


which are companies authorized to manage domain names. Registrars allow you to
search for available domain names and, upon registration, assign the domain to your
website.
 Domain Extensions: Domains can have various extensions like .com, .org,
.net, .io, and many more. The choice of extension depends on the nature and purpose
of your website.
 Domain Renewal: Domains are registered for a specific period, typically a year.
It's important to renew your domain registration before it expires to maintain
ownership and prevent someone else from registering it.

Page 138
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

 Domain DNS Management: DNS (Domain Name System) is responsible for


translating domain names into IP addresses. DNS management allows you to
configure DNS records, such as A records, CNAME records, and MX records, to point
your domain to the appropriate server or hosting provider.

It's worth noting that some web hosting providers also offer domain registration
services, simplifying the process by managing both web hosting and domain
management under a single provider.

In summary, web hosting provides the infrastructure and resources for storing and
serving website files, while domains give your website a unique address on the
internet. These two components work together to make your website accessible to
users worldwide

Deployment using cloud paltforms:

Deploying applications using cloud platforms is a popular choice due to their


scalability, flexibility, and ease of management. Here's a general overview of
deploying applications using cloud platforms:

1. Choose a Cloud Platform: Select a cloud platform that suits your application's
requirements. Popular cloud platforms include Amazon Web Services (AWS),
Microsoft Azure, Google Cloud Platform (GCP), and IBM Cloud. Consider factors
like pricing, available services, scalability options, and integration capabilities.
2. Set Up an Account: Create an account on the chosen cloud platform and set up
the necessary billing and account settings.
3. Prepare Your Application: Ensure your application is ready for deployment.
This involves packaging your application files, including any dependencies, and
preparing any necessary configuration files.
4. Select Deployment Method: Cloud platforms offer various deployment
methods, depending on your application's architecture and specific requirements:

Page 139
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

 Virtual Machines (VMs): Deploy your application on virtual machines


provided by the cloud platform. You can configure the VMs with the required
operating system, software, and networking settings.
 Containers: Use containerization technologies like Docker to package
your application and its dependencies into a container image. Deploy the
containers using container orchestration platforms like Kubernetes or managed
container services provided by the cloud platform.
 Serverless: Consider serverless computing options like AWS Lambda,
Azure Functions, or Google Cloud Functions. In serverless architecture, the
cloud platform manages the infrastructure, and you focus on writing code in the
form of functions or serverless workflows.
 Platform as a Service (PaaS): Some cloud platforms offer PaaS solutions
like AWS Elastic Beanstalk, Azure App Service, or GCP App Engine. These
platforms provide managed environments for deploying and running your
applications, handling much of the underlying infrastructure setup.
5. Configure Deployment Settings: Set up the deployment configuration specific
to your chosen deployment method. This may include defining the number of
instances, specifying networking settings, assigning resources, and configuring load
balancing and auto-scaling options.
6. Deploy Your Application: Upload or push your application files to the cloud
platform using the provided deployment tools or command-line interfaces. The cloud
platform will handle the deployment process based on your configuration.
7. Configure DNS and Domain: If you have a custom domain, configure DNS
settings to point the domain to your deployed application. This typically involves
updating DNS records, such as adding A or CNAME records, to associate your
domain with the cloud platform's provided IP or URL.
8. Monitor and Scale: Monitor your deployed application's performance, resource
usage, and errors using the cloud platform's monitoring and logging tools. Based on
the traffic and demand, scale your application horizontally (adding more instances) or
vertically (increasing resources) to ensure optimal performance.

Page 140
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)
lOMoARcPSD|37177639

9. Security and Access Control: Implement security measures such as access


control, firewalls, encryption, and identity and access management (IAM) to protect
your application and data on the cloud platform.
10. Continuous Deployment and DevOps: Consider setting up continuous
integration and deployment (CI/CD) pipelines to automate the process of building,
testing, and deploying your application updates. Use DevOps practices to streamline
development, deployment, and operations.

It's important to refer to the documentation and resources provided by the specific
cloud platform you choose, as the deployment process may vary depending on the
platform and services you utilize.

UNIT-IV

RESTful Web Services:

RESTful web services, or simply REST (Representational State Transfer), are a


popular architectural style used for designing networked applications. RESTful
services enable communication between systems over the internet, allowing clients to
access and manipulate resources on a server using a set of predefined operations.

Here are some key concepts and principles associated with RESTful web services:

1. Resources: In REST, everything is treated as a resource, such as an object, a


document, or a data entity. Resources are identified by unique URIs (Uniform
Resource Identifiers) and can be accessed via HTTP methods.
2. HTTP Methods: RESTful services utilize the standard HTTP methods for
performing different operations on resources. The commonly used methods are:
 GET: Retrieves the representation of a resource.
 POST: Creates a new resource.
 PUT: Updates an existing resource.
 DELETE: Deletes a resource.

Page 141
Downloaded by Dr.V. Murugesh (murugesh72@gmail.com)

You might also like