WEB AND INTERNET TECHNOLOGIES - Unit 1-5
WEB AND INTERNET TECHNOLOGIES - Unit 1-5
Syllabus: A Brief Introduction to Internet, The World Wide Web, Web Browsers, Web
Servers, Uniform Resource Locators, MIME, HTTP. HTML5: Evolution of HTML and
XHTML, Basic Syntax, Document Structure, Links, Images, Multimedia, Lists, Tables,
Creating Forms, Cascading Style sheets.
Introduction to Internet
The Internet is a worldwide system of interconnected computer networks. The computers
and computer networks exchange information using TCP/IP (Transmission Control
Protocol/Internet Protocol) to communicate with each other. The computers are connected via the
telecommunications networks, and the Internet can be used for e-mailing, transferring files and
accessing information on the World Wide Web.
The World Wide Web is a system of Internet servers that use HTTP (Hypertext Transfer
Protocol) to transfer documents formatted in HTML (Hypertext Mark-up Language). These are
viewed by using software for web browsers such as Netscape, Safari, Google Chrome and Internet
Explorer. Hypertext enables a document to be connected to other documents on the web through
hyperlinks. It is possible to move from one document to another by using hyperlinked text found
within web pages.
History of Internet
The history of the Internet begins with the development of electronic computers in the
1950s. Initial concepts of wide area networking originated in several computer science laboratories
in the United States, United Kingdom, and France. The US Department of Defense awarded
contracts as early as the 1960s, including for the development of the ARPANET project, directed by
Robert Taylor and managed by Lawrence Roberts.
The first message was sent over the ARPANET in 1969 from computer science Professor
Leonard Kleinrock's laboratory at the University of California, Los Angeles (UCLA) to the second
network node at Stanford Research Institute (SRI).
Packet switching networks such as the NPL network, ARPANET, Tymnet, Merit Network,
CYCLADES, and Telnet, were developed in the late 1960s and early 1970s using a variety of
communications protocols. Donald Davies first demonstrated packet switching in 1967 at the
National Physics Laboratory (NPL) in the UK, which became a test-bed for UK research for almost
two decades.
The ARPANET project led to the development of protocols for internet-working, in which
multiple separate networks could be joined into a network of networks. The Internet protocol suite
(TCP/IP) was developed by Robert E. Kahn and Vint Cerf in the 1970s and became the standard
networking protocol on the ARPANET. The ARPANET was decommissioned in 1990. In the
1980s, research at CERN in Switzerland by British computer scientist Tim Berners-Lee resulted in
the World Wide Web, linking hypertext documents into an information system, accessible from any
node on the network.
Since the mid-1990s, the Internet has had a revolutionary impact on culture, commerce, and
technology, including the rise of near-instant communication by electronic mail, instant messaging,
voice over Internet Protocol (VoIP) telephone calls, two-way interactive video calls, and the World
Wide Web with its discussion forums, blogs, social networking, and online shopping sites.
The World Wide Web:
The World Wide Web (abbreviated WWW or the Web) is an information space where
documents and other web resources are identified by Uniform Resource Locators (URLs),
interlinked by hypertext links, and can be accessed via the Internet.The World Wide Web has been
central to the development of the Information Age and is the primary tool billions of people use to
interact on the Internet.[4][5][6]Web pages are primarily text documents formatted and annotated
with Hypertext Markup Language (HTML). In addition to formatted text, web pages may contain
images, video, audio, and software components that are rendered in the user's web browser as
coherent pages of multimedia content.
WEB BROWSER
Web Browser is an application software that allows us to view and explore information on
the web. User can request for any web page by just entering a URL into address bar. Web browser
can show text, audio, video, animation and more. It is the responsibility of a web browser to
interpret text and commands contained in the web page.
Earlier the web browsers were text-based while now a days graphical-based or voice-based
web browsers are also available. Following are the most common web browser available today:
Browser Vendor
Internet Explorer/Microsoft Edge Microsoft
Google Chrome Google
Mozilla Firefox Mozilla
Netscape Navigator Netscape Communications Corp.
Opera Opera Software
Safari Apple
On a network, a web browser can retrieve a web page from a remote web server. The web
server may restrict access to a private network such as a corporate intranet. The web browser uses
the Hypertext Transfer Protocol (HTTP) to make such requests.
The browser does not display the HTML tags but uses them to determine how to display the
document. Web browsers coordinate various web resource elements for the written web page, such
as style sheets, scripts, and images, to present the web page.
Architecture
There are a lot of web browser available in the market. All of them interpret and display
information on the screen however their capabilities and structure vary depending upon
implementation. But the most basic component that all web browser must exhibit are listed below:
Controller/Dispatcher
Interpreter
Client Programs
Controller works as a control unit in CPU. It takes input from the keyboard or mouse, interpret it
and make other services to work based on input it receives.
Interpreter receives the information from the controller and execute the instruction line by line.
Some interpreter are mandatory while some are optional For example, HTML interpreter program is
mandatory and java interpreter is optional.
Client Program describes the specific protocol that will be used to access a service. Following are
the client programs that are commonly used: HTTP, SMTP, FTP, NNTP, POP
WEB SERVERS
Web servers are computers that deliver (serves up) Web pages. Every Web server has an IP
address and possibly a domain name. For example, if you enter the URL
http://www.webopedia.com/index.html in your browser, this sends a request to the Web server
whose domain name is webopedia.com. The server then fetches the page named index.html and
sends it to your browser.
Any computer can be turned into a Web server by installing server software and connecting
the machine to the Internet. There are many Web server software applications, including public
domain software and commercial packages.
Web Server Working
Web server respond to the client request in either of the following two ways:
Sending the file to the client associated with the requested URL.
Generating response by invoking a script and communicating with database
Fig: Architecture
Architecture
Web Server Architecture follows the following two approaches:
Concurrent Approach
Single-Process-Event-Driven Approach.
Concurrent approach allows the web server to handle multiple client requests at the same time. It
can be achieved by following methods:
o Multi-process
o Multi-threaded
o Hybrid method.
o Multi-processing
In this a single process (parent process) initiates several single-threaded child processes and
distribute incoming requests to these child processes. Each of the child processes are responsible for
handling single request.
It is the responsibility of parent process to monitor the load and decide if processes should be killed
or forked.
Multi-threaded: Unlike Multi-process, it creates multiple single-threaded process.
Hybrid: It is combination of above two approaches. In this approach multiple process are created
and each process initiates multiple threads. Each of the threads handles one connection. Using
multiple threads in single process results in less load on system resources.
Examples
Following table describes the most leading web servers available today:
1. Apache HTTP Server
This is the most popular web server in the world developed by the Apache Software Foundation.
Apache web server is an open source software and can be installed on almost all operating systems
including Linux, UNIX, Windows, FreeBSD, Mac OS X and more. About 60% of the web server
machines run the Apache Web Server.
2. Internet Information Services (IIS)
The Internet Information Server (IIS) is a high-performance Web Server from Microsoft. This web
server runs on Windows NT/2000 and 2003 platforms (and may be on upcoming new Windows
version also). IIS comes bundled with Windows NT/2000 and 2003; Because IIS is tightly
integrated with the operating system, so it is relatively easy to administer it.
3.Lighttpd
The lighttpd, pronounced lighty is also a free web server that is distributed with the FreeBSD
operating system. This open source web server is fast, secure and consumes much less CPU power.
Lighttpd can also run on Windows, Mac OS X, Linux and Solaris operating systems.
4.Sun Java System Web Server
This web server from Sun Microsystems is suited for medium and large web sites. Though the
server is free it is not open source. It, however, runs on Windows, Linux and UNIX platforms. The
Sun Java System web server supports various languages, scripts and technologies required for Web
2.0 such as JSP, Java Servlets, PHP, Perl, Python, and Ruby on Rails, ASP and ColdFusion etc.
5.Jigsaw Server
Jigsaw (W3C's Server) comes from the World Wide Web Consortium. It is open source and free and
can run on various platforms like Linux, UNIX, Windows, and Mac OS X Free BSD etc. Jigsaw has
been written in Java and can run CGI scripts and PHP programs.
UNIFORM RESOURCE LOCATORS:
URL is the abbreviation of Uniform Resource Locator and is defined as the global address of
documents and other resources on the World Wide Web. The URL is an address that sends users to
a specific resource online, such as a webpage, video or other document or resource. When you
search Google, for example, the search results will display the URL of the resources that match your
search query. The title in search results is simply a hyperlink to the URL of the resource.
A URL is one type of Uniform Resource Identifier (URI); the generic term for all types of
names and addresses that refer to objects on the World Wide Web.
Parts of a URL:
A URL has two main components:
Protocol identifier: For the URL http://example.com, the protocol identifier is http.
Resource name: For the URL http://example.com, the resource name is example.com.
The protocol identifier indicates the name of the protocol to be used to fetch the resource.
The example uses the Hypertext Transfer Protocol (HTTP), which is typically used to serve up
hypertext documents. HTTP is just one of many different protocols used to access different types of
resources on the net. Other protocols include File Transfer Protocol (FTP), Gopher, File, and News.
The resource name is the complete address to the resource. The format of the resource name
depends entirely on the protocol used, but for many protocols, including HTTP, the resource name
contains one or more of the following components:
Host Name The name of the machine on which the resource lives.
Filename The pathname to the file on the machine.
Port Number The port number to which to connect (typically optional).
Reference A reference to a named anchor within a resource that usually identifies a specific
location within a file (typically optional).
For many protocols, the host name and the filename are required, while the port number and
reference are optional. For example, the resource name for an HTTP URL must specify a server on
the network (Host Name) and the path to the document on that machine (Filename); it also can
specify a port number and a reference.
Every HTTP URL conforms to the syntax of a generic URI. The URI generic syntax consists of a
hierarchical sequence of five components:
URI = scheme:[//authority]path[?query][#fragment]
where the authority component divides into three subcomponents:
authority = [userinfo@]host[:port]
MIME :
Multipurpose Internet Mail Extensions (MIME) is an Internet standard that extends the format
of email to support:
Text in character sets other than ASCII
Non-text attachments: audio, video, images, application programs etc.
Message bodies with multiple parts
Header information in non-ASCII character sets
MIME type names follow a given format:
media-type/subtype-identifier
o image/jpeg is an example of a MIME type where image is the media type, and
jpeg is the subtype identifier.
HTTP:
HTTP means Hyper Text Transfer Protocol. HTTP is the underlying protocol used by the
World Wide Web and this protocol defines how messages are formatted and transmitted, and what
actions Web servers and browsers should take in response to various commands. For example, when
you enter a URL in your browser, this sends an HTTP command to the Web server directing it to
fetch and transmit the requested Web page. The other main standard that controls how the World
Wide Web works is HTML, which covers how Web pages are formatted and displayed.
HTTP is based on the client-server architecture model and a stateless request/response protocol that
operates by exchanging messages across a reliable TCP/IP connection. Hypertext is structured text
that uses logical links (hyperlinks) between nodes containing text. HTTP is the protocol to exchange
or transfer hypertext.
An HTTP "client" is a program (Web browser or any other client) that establishes a
connection to a server for the purpose of sending one or more HTTP request messages. An HTTP
"server" is a program (generally a web server like Apache Web Server or Internet Information
Services IIS, etc. ) that accepts connections in order to serve HTTP requests by sending HTTP
response messages.
HTTP makes use of the Uniform Resource Identifier (URI) to identify a given resource and to
establish a connection. Once the connection is established, HTTP messages are passed in a format
similar to that used by the Internet mail and the Multipurpose Internet Mail Extensions (MIME).
HTML
HTML is the World Wide Web's core markup language. Originally, HTML was primarily
designed as a language for semantically describing scientific documents.
For its first five years (1990-1995), HTML went through several revisions and experienced a
number of extensions, primarily hosted first at CERN, and then at the IETF. With the creation of the
W3C, HTML's development changed venue again. A first abortive attempt at extending HTML in
1995 known as HTML 3.0 then made way to a more pragmatic approach known as HTML 3.2,
which was completed in 1997. HTML4 quickly followed later that same year.
In 2006, the W3C indicated an interest to participate in the development of HTML5 after all, and in
2007 formed a working group chartered to work with the WHATWG on the development of the
HTML5 specification.
New Features
HTML5 introduces a number of new elements and attributes that can help you in building modern
websites. Here is a set of some of the most prominent features introduced in HTML5.
New Semantic Elements − These are like <header>, <footer>, and <section>.
Forms 2.0 − Improvements to HTML web forms where new attributes have been introduced for
<input> tag.
Persistent Local Storage − To achieve without resorting to third-party plugins.
WebSocket − A next-generation bidirectional communication technology for web applications.
Server-Sent Events − HTML5 introduces events which flow from web server to the web browsers
and they are called Server-Sent Events (SSE).
Canvas − This supports a two-dimensional drawing surface that you can program with JavaScript.
Audio & Video − You can embed audio or video on your webpages without resorting to third-party
plugins.
Geolocation − Now visitors can choose to share their physical location with your web application.
Microdata − This lets you create your own vocabularies beyond HTML5 and extend your web
pages with custom semantics.
Drag and drop − Drag and drop the items from one location to another location on the same
webpage.
The HTML 5 language has a "custom" HTML syntax that is compatible with HTML 4 and
XHTML1 documents published on the Web, but is not compatible with the more esoteric SGML
features of HTML 4.HTML 5 does not have the same syntax rules as XHTML where we needed
lower case tag names, quoting our attributes, an attribute had to have a value and to close all empty
elements.
HTML5 comes with a lot of flexibility and it supports the following features −
Uppercase tag names.
Quotes are optional for attributes.
Attribute values are optional.
Closing empty elements are optional.
Code:
<html>
<head>
<title>Title of page</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>
BASIC SYNTAX :
HTML elements are represented by tags
HTML tags label pieces of content such as "heading", "paragraph", "table", and so on
Browsers do not display the HTML tags, but use them to render the content of the page
Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
DOCUMENT STRUCTURE
An HTML Document is mainly divided into two parts:
HEAD: This contains the information about the HTML document. For Example, Title of the page,
version of HTML, Meta Data etc.
BODY: This contains everything you want to display on the Web Page.
Example Explained
The first tag in your HTML document is <html>. This tag tells your browser that this is the
start of an HTML document. The last tag in the above code is </html>. This tag tells your browser
that this is the end of the HTML document.
The text between the <head> tag and the </head> tag is header information. Header
information is not displayed in the browser window. This section is used to provide meta data about
the page. The text between the <title> tags is the title of your document. The title is displayed in
your browser's caption.
The text between the <body> tags is the text that will be displayed in your browser. The text
between the <b> and </b> tags will be displayed in a bold font. When you save an HTML file,use
.html extension.
You can easily edit HTML files using a WYSIWYG (what you see is what you get) editor
like notepad plus, sublime text, FrontPage editors. But if you want to be a skillful Web developer,
we strongly recommend that you use a plain text editor like notepad to learn HTML in the earlier
days of learning.
HTML Elements
HTML documents are text files made up of HTML elements.
HTML elements are defined using HTML tags.
HTML Tags
HTML tags are used to mark-up HTML elements
HTML tags are surrounded by the two characters < and >
The surrounding characters are called angle brackets
HTML tags normally come in pairs like <b> and </b>
The first tag in a pair is the start tag, the second tag is the end tag
The text between the start and end tags is the element content
HTML tags are not case sensitive, <b> means the same as <B>
Remember the HTML example from the previous page:
<html>
<head><title>Title of page</title></head>
<body> This is my first homepage. <b>This text is bold</b></body>
</html>
Tag Attributes
Tags can have attributes. Attributes can provide additional information about the HTML elements
on your page.
This tag defines the body element of your HTML page: <body>. With an added bgcolor attribute,
you can tell the browser that the background color of your page should be red, like this:
<body bgcolor="red">.
This tag defines an HTML table: <table>. With an added border attribute, you can tell the browser
that the table should have no borders:
<table border="0">
Attributes always come in name/value pairs like this: name="value". Attributes are always added to
the start tag of an HTML element. Quote Styles, "red" or 'red'?
Attribute values should always be enclosed in quotes. Double style quotes are the most common, but
single style quotes are also allowed. In some rare situations, like when the attribute value itself
contains quotes, it is necessary to use single quotes:
name='John "ShotGun" Nelson'
Headings
Headings are defined with the <h1> to <h6> tags. <h1> defines the largest
heading. <h6> defines the smallest heading.
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
<h4>This is a heading</h4>
<h5>This is a heading</h5>
<h6>This is a heading</h6>
HTML automatically adds an extra blank line before and after a heading.
Paragraphs
Paragraphs are defined with the <p> tag.
<p>This is a paragraph</p>
<p>This is another paragraph</p>
HTML automatically adds an extra blank line before and after a paragraph.
Line Breaks
The <br> tag is used when you want to end a line, but don't want to start a new paragraph. The <br>
tag forces a line break wherever you place it.
<p>This <br> is a para<br>graph with line breaks</p>
The <br> tag is an empty tag. It has no closing tag.
Comments in HTML
The comment tag is used to insert a comment in the HTML source code. A comment will be ignored
by the browser. You can use comments to explain your code, which can help you when you edit the
source code at a later date.
<!-- This is a comment -->
Note that you need an exclamation point after the opening bracket, but not before the closing
bracket.
Character Entities
Some characters have a special meaning in HTML, like the less than sign (<) that defines the start of
an HTML tag. If we want the browser to actually display these characters we must insert character
entities in the HTML source.
A character entity has three parts: an ampersand (&), an entity name or a # and an entity number,
and finally a semicolon (;).
To display a less than sign in an HTML document we must write: < or <
The advantage of using a name instead of a number is that a name is easier to remember. The
disadvantage is that not all browsers support the newest entity names, while the support for entity
numbers is very good in almost all browsers. Note that the entities are case sensitive.
Non-breaking Space
The most common character entity in HTML is the non-breaking space.
Normally HTML will truncate spaces in your text. If you write 10 spaces in your text HTML will
remove 9 of them. To add spaces to your text, use the character entity.
LINKS:
HTML Anchor Tag
You might know that hyperlink which is a powerful means of browsing from web pages and
websites. It is developed for sending the readers or those who will perform surfing from one web
page to another without opening a new tab or window. This is in general term said to as link and is
given a reference to jump to another page, document, or from one part of the same page to another
using a hypertext.
Hypertext can be defined as a text shown on your PC screen, which holds the hyperlink data
(here data means from which document to which document, it will move) and hence take the readers
to different web pages by clicking it. In this chapter, you will be learning about how to create your
very own hyperlink and use them in creating your website and web pages.
What is Anchor Tag?
The Anchor tag in HTML can be defined as a means to create a hyperlink that can link your current
page on which the text is being converted to hypertext via <a> (anchor tag) to another page. This
anchoring from one page to another is made possible by the attribute "href", which can be
abbreviated as (hypertext reference).
HREF attribute
The attribute 'HREF' of the Anchor tag is implemented for defining the address or path to which this
hypertext will get linked. In other words, it can be said that it directs you out of your page to that
destination page, whose link you have mentioned within the double quotes of the href attribute as
value.
The syntax for an anchor tag with href attribute looks something like this:
<a href = "URL">Text Here</a>
IMAGES
HTML Images
With HTML you can display images in a document.
The Image Tag and the Src Attribute
In HTML, images are defined with the <img> tag. The <img> tag is empty, which means that it
contains attributes only and it has no closing tag.
To display an image on a page, you need to use the src attribute. Src stands for "source". The value
of the src attribute is the URL of the image you want to display on your page.
The syntax of defining an image:
<img src="url">
The URL points to the location where the image is stored. An image named "boat.gif" located in the
directory "images" on "www.w3schools.com" has the URL:
Example: http://www.w3schools.com/images/boat.gif.
The browser puts the image where the image tag occurs in the document. If you put an image tag
between two paragraphs, the browser shows the first paragraph, then the image, and then the second
paragraph.
The Alt Attribute
The alt attribute is used to define an "alternate text" for an image. The value of the alt attribute is an
author-defined text:
<img src="boat.gif" alt="Big Boat">
The "alt" attribute tells the reader what he or she is missing on a page if the browser can't load
images. The browser will then display the alternate text instead of the image. It is a good practice to
include the "alt" attribute for each image on a page, to improve the display and usefulness of your
document for people who have text-only browsers.
Image Tags
<img> Defines an image
<map> Defines an image map
<area> Defines an area inside an image map
MULTIMEDIA
What is Multimedia?
Multimedia is available in many different formats. It can be defined as almost anything which one
can hear or see.
Examples: Pictures, sound, music, videos, records, films, animations, and more.
Web pages consists of multimedia elements belonging to different types and formats.
In this chapter you will be learning about the different multimedia formats.
BROWSER SUPPORT
The first web browsers was having support for text only, which was also limited to a single font and
a single color.
Later browsers were developed to support for colors and fonts. They also supported for pictures!
The support for various multimedia like sounds, animations, and videos are handled in a different
manner by different browsers. Different types and formats are supported, and some formats require
extra helper programs (plug-ins) to work.
Hopefully, all the defects will become history. HTML5 multimedia is promising a bright future for
multimedia.
MULTIMEDIA FORMATS
Multimedia elements (like sounds or videos) are getting stored as media files.
The most easy and common way to find or discover the type of a file, is to have a look at the
extension of the file. When a browser locate the file extension .htm or .html, it will handle the file as
an HTML file. The .xml extension is used for indicating an XML file, and the .css extension is used
to indicate a style sheet file. Images are recognized using extensions like .gif, .png and .jpg.
Multimedia files also tend to have their own extensions, formats and like: .swf, .wav, .mp3, .mp4,
.mpg, .wmv, and .avi.
HTML LISTS
HTML supports ordered, unordered and definition lists.
Unordered Lists
An unordered list is a list of items. The list items are marked with bullets (typically small black
circles).
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>
Here is how it looks in a browser:
Coffee
Milk
Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.
Ordered Lists
An ordered list is also a list of items. The list items are marked with numbers.
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>
Here is how it looks in a browser:
1. Coffee
2. Milk
Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.
Definition Lists
A definition list is not a list of items. This is a list of terms and explanation of the terms.
A definition list starts with the <dl> tag. Each definition-list term starts with the <dt> tag. Each
definition-list definition starts with the <dd> tag.
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
Inside a definition-list definition (the <dd> tag) you can put paragraphs, line breaks, images, links,
other lists, etc.
List Tags
<ol> Defines an ordered list
<ul> Defines an unordered list
<li> Defines a list item
<dl> Defines a definition list
<dt> Defines a definition term
<dd> Defines a definition description
<dir> Deprecated. Use <ul> instead
<menu> Deprecated. Use <ul> instead
HTML TABLES
With HTML you can create tables.
Tables
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each
row is divided into data cells (with the <td> tag). The letters td stands for "table data," which is the
content of a data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules,
tables, etc.
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
How it looks in a browser:
If you do not specify a border attribute the table will be displayed without any borders. Sometimes
this can be useful, but most of the time, you want the borders to show.
To display a table with borders, you will have to use the border attribute:
<table border="1">
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>
Headings in a Table
Headings in a table are defined with the <th> tag.
<table border="1">
<tr>
<th>Heading</th>
<th>Another Heading</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
How it looks in a browser:
Note that the borders around the empty table cell are missing.
To avoid this, add a non-breaking space ( ) to empty data cells, to make the
borders visible:
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td> </td>
</tr>
</table>
How it looks in a browser:
row 1, cell 1 row 1, cell 2
row 2, cell 1
Table Tags
<table> Defines a table
<th> Defines a table header
<tr> Defines a table row
<td> Defines a table cell
<caption> Defines a table caption
<colgroup> Defines groups of table columns
<colspan> Defines the number of columns to be merged in a row
<rowspan> Defines the number of rows to be merged in a column
<col> Defines the attribute values for one or more columns in a table
<thead> Defines a table head
<tbody> Defines a table body
<tfoot> Defines a table footer
Checkbox
Checkboxes are used when you want the user to select one or more options of a limited number of
choices.
<form>
<input type="checkbox" name="bike">I have a bike
<br>
<input type="checkbox" name="car">I have a car
</form>
How it looks in a browser:
I have a bike
I have a car
If you type some characters in the text field above, and click the "Submit" button, you will send
your input to a page called "html_form_action.asp". That page will show you the received input.
Form Tags
<form> Defines a form for user input
<input> Defines an input field
<textarea> Defines a text-area (a multi-line text input control)
<label> Defines a label to a control
<fieldset> Defines a fieldset
<legend> Defines a caption for a fieldset
<select> Defines a selectable list (a drop-down box)
<optgroup> Defines an option group
<option> Defines an option in the drop-down box
<button> Defines a push button
<isindex> Deprecated. Use <input> instead
HTML Fonts
The <font> tag in HTML is deprecated. It is supposed to be removed in a future version of HTML.
Even if a lot of people are using it, you should try to avoid it, and use styles instead.
The HTML <font> Tag
With HTML code like this, you can specify both the size and the type of the browser output :
<p><font size="2" face="Verdana">This is a paragraph.</font></p>
<p><font size="3" face="Times">This is another paragraph.</font></p>
CSS was developed in 1997 for Web designers, as a way for Web designers to define the
attractive look and feel of their Web pages.
HTML is only Markup language, we can use some attributes and values in tags, but it's not
capable of creating attractive web page design.
The World Wide Web Consortium (W3C) has created CSS to solve this problem.
In HTML 4.0, all formatting could be removed from the HTML document and can be stored
in a separate CSS file.
CSS Example
<!DOCTYPE html>
<html>
<head><title>Sample CSS</title></head>
<body>
<style>
</style>
</body>
</html>
Introduction to CSS
Styling your web page to make it look appealing is also an essential element of web designing and
development. CSS helps in giving styles for describing the presentation of the markup based
documents.
CSS is abbreviated as Cascading Style Sheets and is used for describing how HTML elements need
to be displayed when they are represented in a web page format or other media. It also helps in
saving a lot of work because controlling the layout of multiple web pages can be done all at a time.
It helps in representing how markup based documents can be presented in conjunction with HTML.
The latest version of CSS released in CSS3.
CSS is said to as the cornerstone design tool of the World Wide Web along with HTML and
JavaScript. CSS is intended for enabling the separation of appearance with content, which includes
layout, coloring, and font styles. Such a smart approach can progress the accessibility of content,
offer more flexibility and organize in the order of presentation where it allows multiple web pages to
contribute to formatting by giving relevant CSS instructions in another file which has the file
extension .css. This separation of design implementation helps in reducing complexity as well as
repetition in the structural content.
Benifits of CSS
Compatible with Old Versions: This is the most beautiful feature of CSS3 as it gets compatible
with its older versions. This is advantageous as designers won't have to relinquish their previous
work because of the arrival of CSS3.
Simple yet Independent: Like that of CSS2, CSS3 is created using tiny modules that compose the
application more straightforward and more comfortable to exercise. Some of the most vital
components and features offered by CSS3 are selectors, box model, color, borders, backgrounds, 2D
and 3D transformations, Text Effects, and user interface.
View and Change-Friendly: As the various CSS concepts have been broken down into tiny chunks
or modules, it has become easier to alter the elements individually without particularly disturbing
the remaining components. Also, CSS has become compatible with all kinds of platform.
Rapid development: Since it is not dependent on JavaScript, CSS3 has become a lot swifter than its
older versions and is relatively more compatible with every browser available in the market.
Eye-catching backgrounds: CSS helps in making attractive backgrounds, especially using CSS3. It
permits web designers to prefer from a wide range of backgrounds that can be useful and catch the
eye with ease. Also, these backgrounds have the feature of gradient colors and resizing so that they
can fit for the project.
Images and Animations: CSS helps in ornamenting the appearance and feel of a website or web
pages immeasurably by making use of some simple styles. It permits straightforward incorporation
of a variety of images-including 3D images in your web development project. It also makes easy
insertion of videos or animations in your web pages along with flexibility for customization.
Testing its features: Because of the smaller modules (specifically in CSS3), testing of every entity
becomes smooth, which ultimately saves a lot of time and effort.
CSS Syntax
It is a standard set of rules which has three parts, a selector, a property, and a value. But, you do not
have to recall this every time to code your web designing thing using CSS. Selectors will be
discussed separately in the upcoming chapter. At the fundamental level of CSS, it has the two
building blocks that define how CSS code will perform:
Selector: selectors in CSS help in selecting the styles in elements you want to put for designing your
web pages.
Properties: These are understandable identifiers which point to different stylistic characteristics (such
as font, background color, width, etc.) you wish for change.
Values: Every particular property is set with a value that tells in what way you wish to alter those
stylistic characteristics within the web page (such as what font size you want, the width of any
particular CSS entity, or the background color).
The property and value together as a single pair are called as CSS declaration. These declarations
are placed inside CSS declaration Blocks.
1. Inline Style
2. Embedded Style Sheet
3. External Style Sheet
Inline Style
Styles sheets that are of type inline refer to information related to the style being functional to the
existing HTML element. The use of inline approach, rather than defining your style once, here, you
have to write the style in every HTML element that you use for designing your web page. It can be
more precisely called an inline style rather than the inline style sheet. It uses the style attribute
within that HTML element.
Syntax:
Example:
Using inline styles is not as powerful as other types of style sheets available in CSS. If you
define your styles for many HTML tags, which are in use to design a web page, then you will
not be able to use most of the power associated with CSS.
For example, you have to define the style over and over again whenever it is used, instead of
defining it only once.
Furthermore, if you want to change a specific style, you have to change it in many places in
your documents instead of changing it to one place.
Embedded Style Sheets is a style sheet where designers can embed information of the style sheet in
an HTML document by making use of the <style> element. This embedding of style sheet info
within <style> .... </style> tags are done within head section of HTML.
The syntax for embedded style sheets has no such exception. Simply you have to place the style
sheet code between the <head>.....</head> tags where <style> .... </style> is nested within head
element:
Example:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: #069;
font-size: 25px;
font-weight: normal;
line-height: 34px;
margin-bottom: 10px;
outline: 0 none;
padding-bottom: 3px;
padding-top: 0;
text-decoration: none;
</style></head>
```<body>
<h1>Welcome to w3schools.in</h1>
</body>
</html>
This type of style sheet gets a separate file in which designers can state every CSS styles which
seems relevant for your web site. Then this has to be linked with the external style sheet from your
HTML page. You have to follow some specific steps to make this conceptual style sheet
implementable.
Steps to create External Style Sheets:
1. Build the Style Sheet by typing the CSS code in a plain text file (using text editor, usually), and
then save the with as a .css extension.
2. Now, you have to link the Style Sheet with the HTML document by using an HTML link
element.
Example:
OVERVIEW
JavaScript is a dynamic computer programming language. It is lightweight and most commonly
used as a part of web pages, whose implementations allow client-side script to interact with the
user and make dynamic pages. It is an interpreted programming language with object-oriented
capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has
been embedded in Netscape, Internet Explorer, and other web browsers.
Java Script:
JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
Everyone can use JavaScript without purchasing a license
Note: Java and JavaScript are two completely different languages in both concept and design!
Advantages:
JavaScript can interact with events - A JavaScript can be set to execute when something
happens,
like when a page has finished loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data
before it is submitted to a server. This saves the server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed
for that browser
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer
Disadvantages
Security Issues: Javascript snippets, once appended onto web pages execute on client servers
immediately and therefore can also be used to exploit the user's system. While a certain
restriction is set by modern web standards on browsers, malicious code can still be executed
complying with the restrictions set.
Javascript rendering varies
The HTML <script> tag is used to insert a JavaScript into an HTML page.
<html>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use
the type attribute to define the scripting language.
So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and The
document.write command is a standard JavaScript command for writing output to a page. By
entering the document.write command between the <script> and </script> tags, the browser will
recognize it as a JavaScript command and execute the code line. In this case the browser will write
Hello World!.
JavaScript’s in a page will be executed immediately while the page loads into the browser. This is
not always what we want. Sometimes we want to execute a script when a page loads, other times
when a user triggers an event.
Object Orientation and JavaScript
There are certain features or mechanisms which makes a Language Object Oriented like:
Object
Classes
Encapsulation
Inheritance
Object– An Object is a unique entity which contains property and methods. For example “car” is
a real life Object, which have some characteristics like color, type, model, horsepower and
performs certain action like drive. The characteristics of an Object are called as Property, in Object
Oriented Programming and the actions are called methods. An Object is an instance of a class.
Objects are everywhere in JavaScript almost every element is an Object whether it is a
function,arrays and string.
Classes– Classes are blueprint of an Object. A class can have many Object, because class is
a template while Object are instances of the class or the concrete implementation.
Before we move further into implementation, we should know unlike other Object Oriented
Language there is no classes in JavaScript we have only Object. To be more precise, JavaScript
is a prototype based object oriented language, which means it doesn’t have classes rather it define
behaviors using constructor function and then reuse it using the prototype.
Encapsulation – The process of wrapping property and function within a single unit is known
as encapsulation.
Syntactic Characteristics
1.JavaScript are embedded either directly or indirectly in XHTML documents.
2.Scripts can appear directly as the content of a <script> tag.
3.The type attribute of <script> must be set to “text/JavaScript”.
4.The JavaScript can be indirectly embedded in an XHTML document using the srcattribute of a
<script> tag, whose value is name of a file that contains the script.
Eg. <script type=”text/JavaScript” src=”tst_number.js”>
</script>
Closing tag is required even if script element has src attribute included.The indirect method of
embedding JavaScript in XHTML has advantages of
1)Hiding the script from the browser user.
2)It also avoids the problem of hiding scripts from older browsers.
3)It is good to separate the computation provided by JavaScript from the layoutand presentation
provided by XHTML and CSS respectively.
But it is sometimes not convenient and cumbersome to place all JavaScriptcode in separate file
JavaScript identifiers or names are similar to programming languages.
1. Must begin with (-), or a letter. Subsequent characters may be letters, underscores or digits.
2. No length limitations for identifiers.
3. Case sensitive
4. No uppercase letters.
Example
var a_num = 1.234 // a_num holds the actual value
var an_obj = { type: 'cat' } // an_obj holds a reference to the obj
Boolean type
Allowed values: true,false.
Null type
Allowed values: null.
It is worth noting that the typeof operator returns object for null because the spec says so.
Undefined type
Allowed values: undefined.
The Undefined type has exactly one value, called undefined. Any variable that has not been assigned
a value has the value undefined.
Number type
Size: 8 bytes
Allowed values: 18437736874454810624 finite numbers (half positive half negative, including
positive and negative zero) and three symbolic values NaN, Positive Infinity & Negative Infinity
String type
Size: variable (string.length * 2 bytes)
Max size: 18014398509481982 bytes (~16gB)
Allowed values: 16-bit unsigned integer values (0 to 65535 inclusive)
JavaScript strings are immutable (unchangeable), once a string is created it is impossible to modify it.
However, it is still possible to create another string based on the original by using string functions
such as substr and concat.
Symbol type
Symbols are new to ES6 they are unique and immutable primitive values and may be used as the
key of an Object property.
Example:
var key = Symbol()
var an_obj = { [key]: 'cat'}
Symbol() === Symbol() /// false
OPERATORS in JavaScript
JavaScript has the following types of operators. This section describes the operators and contains
information about operator precedence.
Assignment operators
Comparison operators
Arithmetic operators
Bitwise operators
Logical operators
String operators
Conditional (ternary) operator
Comma operator
Unary operators
Relational operators
Expressions
Any unit of code that can be evaluated to a value is an expression. Since expressions produce
values, they can appear anywhere in a program where JavaScript expects a value such as the
arguments of a function invocation. As per the MDN documentation, JavaScript has the following
expression categories.
Arithmetic Expressions:
Arithmetic expressions evaluate to a numeric value. Examples include the following
10; // Here 10 is an expression that is evaluated to the numeric value 10 by the JS interpreter
10+13; // This is another expression that is evaluated to produce the numeric value 23
String Expressions:
String expressions are expressions that evaluate to a string. Examples include the following
'hello';
'hello' + 'world'; // evaluates to the string 'hello world'
Logical Expressions:
Expressions that evaluate to the boolean value true or false are considered to be logical expressions.
This set of expressions often involve the usage of logical operators && (AND), ||(OR) and !(NOT).
Examples include
10 > 9; // evaluates to boolean value true
10 < 20; // evaluates to boolean value false
true; //evaluates to boolean value true
a===20 && b===30; // evaluates to true or false based on the values of a and b
Primary Expressions:
Primary expressions refer to stand alone expressions such as literal values, certain keywords and
variable values. Examples include the following
'hello world'; // A string literal
23; // A numeric literal
true; // Boolean value true
sum; // Value of variable sum
this; // A keyword that evaluates to the current object
Left-hand-side Expressions:
Also known as lvalues, left-hand-side expressions are those that can appear on the left side of an
assignment expression. Examples of left-hand-side expressions include the following
// variables such as i and total
i = 10;
total = 0;
Working with any dynamic language requires the ability to read, process and output user data.
JavaScript is especially useful when you want to take user information and process it without
sending the data back to the server. JavaScript is much faster than sending everything to the server
to process, but you must be able to read user input and use the right syntax to work with that input.
This article will focus on retrieving user input and displaying it on the screen through HTML
elements or prompts.
Displaying Prompts and Retrieving User Responses
JavaScript has a few window object methods that you can use to interact with your users. The
prompt() method lets you open a client-side window and take input from a user. For instance, maybe
you want the user to enter a first and last name. Normally, you can use an HTML form for user
input, but you might need to get the information before sending the form back to your server for
processing. You can use the window.prompt() method for small amounts of information. It's not
meant for large blocks of text, but it's useful when you need information before the user continues to
another page.
if (customerName!= null) {
document.getElementById("welcome").innerHTML =
The first line of code uses the prompt method. Notice that we don't need the "window" object since
JavaScript inherits the main DOM methods and understands that this is an internal method. The first
parameter in the prompt is what you want to show the user. In this example, we want the user to
enter a name, so the prompt displays "Please enter your name." The second parameter is the default
text. This default text helps the user understand where to type the name, but if he clicks "OK"
without entering a name, the "<name goes here>" text will be used for the username. You can create
checks in your JavaScript code that detects when the user doesn't enter a name and just clicks OK,
but this code assumes any text entered is the user's name.
Notice the "if" statement that checks if the "customerName" variable is null. This logic checks to
make sure that the user entered something. It only checks that some character was entered, so the
user can type anything to bypass the "if" statement. The code within the "if" statement then displays
the message to the user in the "welcome" div. We've covered reading and writing text to a web page,
and this is another example of writing text to the inner HTML section of a div. Remember that the
innerHTML property writes any tags or text within the opening and closing div tag.
Use this method to get a short string response from your users before they access a page or before
they move on to another page in your site structure.
The JavaScript Confirmation Message Box
The window.prompt method is one way to read user input, but JavaScript also provides a way to get
confirmation from the user. For instance, you might want to confirm that the user has entered the
right information and wants to continue with payment. The confirmation window displays the
amount the user will be charged, and the user has the option to confirm or cancel. You could write a
complex JavaScript function to create a new window for confirmation or you can use the internal
window.confirm method. This method returns either a boolean true result if the user clicks "OK" or
the boolean false result if the user clicks "Cancel." This prompt is a quick way to get confirmation
without using any complex coding logic.
if (r == true) {
x = "Payment sent!";
} else {
x = "Payment cancelled!";
alert (x);
The main utility in the above code is the "confirm" function. This is an internal JavaScript function
from the window object. In other words, using "window.confirm()" and "confirm" results in the
same function. JavaScript handles the inheritance for you, so you don't need to remember to use the
window object. The confirmation window is also pre-built and shown to the user. In this example, a
prompt displays with the text "Are you sure you want to send a payment?" The only options for the
user are to click the Cancel button or the OK button. OK is the confirmation that returns "true." If
the user clicks "OK," the variable x contains the text "Payment sent!" Conversely, if the user clicks
the "Cancel" button, x contains the text "Payment cancelled!" The text is then displayed to the user
using the "alert" function. This is the first time we've seen the alert function, which is also a part of
the window object. Typing "alert" and "window.alert" results in the same method call. The alert
prompt is common during debugging and development of a web application, because it's a quick
way to check your logic and see the control flow of your code. The alert function in this example
checks that the confirm window is responding with the right result and the x variable contains the
right text.
The span and div tags are a way to just display the information you've read in JavaScript prompt
windows. You can also display data you've retrieved from a database.
Let's use the previous example where we prompted the user to enter a name. We then use the input
to display output in a div element. We've seen this before, but this is the first time we've used input
directly from the user.
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
</body>
</html>
We've included the HTML this time to show you how JavaScript prompts work with HTML
elements. The element we're using is the div HTML tag with the id of "welcome." The JavaScript
prompt asks the user for his name and then displays the result in the "welcome" div. You can also
use this same code to display the result in the span element using the same code except change the
div tag to a span opening and closing tag.
You've seen the innerHTML property several times, which controls the text within the opening and
closing div or span tags, but what if you want to use the input to pre-populate a form field? The
input text field lets users input string values, but you can use the methods we've seen to pre-populate
string values automatically. Using the same input example as we previously used, the following
code uses the input prompt to enter the user's name in the "username" text field.
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
</body>
</html>
The above code varies slightly from the previous div example. This code uses the same prompt
method to get a user's name, but then it displays the information in an "input" element with the type
set as "text." Again, you'll notice that the id tag property is used, which allows us to grab the DOM
element by id and change its properties. The form input element uses the "value" property and not
the innerHTML property. You'll get to know the DOM element properties by heart as you use them
more frequently. Also notice that the input HTML tag does not have a closing tag. The terminator
"/>" can be used when you don't need to contain text within an opening and closing tag. Using the
terminator is cleaner and follows HTML5 standards.
follows:
Iterative Statements (Loop): Until and unless the expression or the condition
Conditional Statements
IF
when you want to check for a specific condition. With the IF condition, the inner code
Syntax:
if (condition) {
IF-ELSE
an extended version of IF. When you want to check a specific condition and two
Syntax:
if (condition)
else {
SWITCH
A switch statement is similar to IF and is of use when you need to execute 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, code associated with that case executes.
Syntax:
switch (expression) {
case a:
Break;
case b:
Break;
case n:
Break;
default:
Iterative Statement
WHILE
one of the control flow statement, which executes a code block when the condition is satisfied. But
unlike IF, while keeps repeating itself until the condition is satisfied. Difference between IF and
while can be, IF executes code ‘if’ the condition is satisfied while the while keeps repeating itself
until the condition is satisfied.
Syntax:
while (condition)
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 then checks for the condition.
Syntax:
while
} (condition)
FOR
a for loop will execute a code block for 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:
JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct
create objects.
next →← prev
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 template based not class based. Here, we don't create class to get the object. But, we
direct 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)
Syntax:
object={property1:value1,property2:value2.....propertyN:valueN}
example:
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
Syntax:
var objectname=new Object();
example:
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
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.
Example:
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
Syntax:
var arrayname=[value1,value2.....valueN];
example:
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
Syntax:
var arrayname=new Array();
example:
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
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
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
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.
flatMap() It maps all array elements via mapping function, then flattens the result
into a new array.
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.
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.
Syntax:
Example:
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
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.
Example
<!DOCTYPE html>
<html>
<body>
<script>
class Employee {
constructor() {
this.id=101;
this.name = "Martin Roy";
}
}
var emp = new Employee();
document.writeln(emp.id+" "+emp.name);
</script>
</body>
</html>
1. By string literal
2. By string object (using new keyword)
Example:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to perfom a global, case-insensitive search for the letters "ain" in
a string, and display the matches.</p>
<p id="demo"></p>
<script>
function myFunction() {
var str = "The rain in SPAIN stays mainly in the plain";
var res = str.match(/ain/gi);
document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.
search() It searches a specified regular expression in a given string and returns its
position if a match occurs.
Example:
<html>
<head>
<script>
// run this function when the document is loaded
window.onload = function() {
Events are normally used in combination with functions, and the function will not be
executed before the event occurs, such as when a user clicks a button.
With the growth of Web applications, websites have been trying to make user interaction similar to
that found in
desktop applications. The largest push is towards making Web interfaces more dynamic: if data
changes, say a new email arrives in your inbox in GMAIL, the Web page should update and display
the new email without reloading the whole page. The page should always be available to the user
and always responsive to their input. While the DOM allows for such dynamic updates to occur,
AJAX is an important group of technologies that allows a Web page to request more information
from the server (such as an updated list of email in an inbox) without having to reload the whole
page. Together, AJAX and the DOM can be used to create dynamic Web pages.
AJAX stands for Asynchronous JavaScript and XML. It allows a Web page to make a request to a
Web server for information using standard HTTP, but without reloading the page, and without
automatically displaying the information returned from the server. These requests are all made
programmatically, using JavaScript, and data communication is often done using XML, as
JavaScript can easily parse this data. After receiving the data from the server, the JavaScript script
can use the returned data however it wishes. The requests can also be made in a such a way that the
JavaScript code does not have to wait for a reply from the server. Instead, the JavaScript code is
notified when the page has finished receiving the information. In this way, the script can continue to
perform useful actions while the data downloads from the server – this makes the communication
asynchronous to any action that the Web page is performing.
It is important to realise that AJAX itself refers to a group of related technologies, not all of which
are standardised, and not all of which need to be used at once. For instance, it can often be more
convenient to communicate with the server using plain text rather than XML, and these
communications need not occur asynchronously. Various other technologies are often employed in
addition to those making up the AJAX name itself. The original article that defined the term AJAX
lists the following technologies:
• XHTML and CSS, which defines what is being displayed and how it is displayed.
• The Document Object Model, which allows us to programmatically alter the content and how it is
displayed.
• XML and XSLT, which is used to transfer data between the server and Web browser (using XML),
and to manipulate that data (using XSLT).
• XMLHttpRequest, which is the object used to communicate with the Web server over HTTP. This
object provides the asynchronous communication abilities.
• JavaScript, which is the programming language implemented in most Web browsers, and is used to
bring together all the other technologies listed above.
Initialization
The first step to making an HTTP request using AJAX is to create an instance of one of the
XMLHttpFunction function objects. There are two different objects that can be used, depending on
the browser: Mozilla based browsers – such as Firefox – and Safari (used on OS X) both use
XMLHttpRequest() objects. Internet Explorer, on the other hand, uses ActiveXObject(). An object
can easily be created using the following code:
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, …
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
The methods and properties associated with both of these objects are identical: the major difference
between them is how they are initialised. During these notes we will speak of XMLHttpRequest to
mean both the Mozilla / Safari XMLHttpRequest objects
XML: Introduction to XML, Syntax, XML document structure, Document Type Definition, Name spaces,
XML Schemas, Display in raw XML documents, Displaying XML documents with CSS, XPath Basics,
XSLT, XML Processors.
J2EE: Exploring Enterprise architecture styles, Features of EE platform, Web servers and application
servers.Database programming with JDBC: JDBC Drivers, Exploring JDBC Processes with the java.sql
Package.
Introduction to XML
XML is a software- and hardware-independent tool for storing and transporting data.
What is XML?
XML stands for extensible Markup Language
XML is a markup language much like HTML
XML was designed to store and transport data
XML was designed to be self-descriptive
XML is a W3C Recommendation
XML Does Not DO Anything
Maybe it is a little hard to understand, but XML does not DO anything.
Example:
This note is a note to Tove from Jani, stored as XML:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The XML above is quite self-descriptive:
It has sender information.
It has receiver information.
It has a heading.
It has a message body.
But still, the XML above does not DO anything. XML is just information wrapped in tags.
The same XML data can be used in many different presentation scenarios.Because of this, with
XML, there is a full separation between data and presentation.
XML is Often a Complement to HTML: In many HTML applications, XML is used to store or
transport data, while HTML is usedto format and display the same data.
XML Separates Data from HTML: When displaying data in HTML, you should not have to edit the
HTML file when the datachanges.With XML, the data can be stored in separate XML files.With a
few lines of JavaScript code, you can read an XML file and update the datacontent of any HTML
page.
XML Syntax
Self-Describing Syntax
The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is written
in lower-case.
If document contains XML declaration, then it strictly needs to be the first statement of the
XML document.
The XML declaration strictly needs be the first statement in the XML document.
An HTTP protocol can override the value of encoding that you put in the XML declaration.
XML Documents Must Have a Root Element
XML documents must contain one root element that is the parent of all other elements:
In this example <note> is the root element:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The XML Prolog(Processing Instruction)
This line is called the XML prolog:
<?xml version="1.0" encoding="UTF-8"?>
The XML prolog is optional. If it exists, it must come first in the document.XML documents can
contain international characters, like Norwegian øæå or French êèé.To avoid errors, you should
specify the encoding used, or save your XML files as UTF-8.UTF-8 is the default character
encoding for XML documents.Character encoding can be studied in our Character Set Tutorial.
UTF-8 is also the default encoding for HTML5, CSS, JavaScript, PHP, and SQL.
All XML Elements Must Have a Closing Tag
In XML, it is illegal to omit the closing tag. All elements must have a closing tag:
Note: The XML prolog does not have a closing tag! This is not an error. The prolog is not
a part of the XML document.
XML Tags are Case Sensitive: XML tags are case sensitive. The tag <Letter> is different from the
tag <letter>.
Opening and closing tags must be written with the same case:<message>This is correct</message>
"Opening and closing tags" are often referred to as "Start and end tags". Use whateveryou prefer. It
is exactly the same thing.
XML Elements Must be Properly Nested
XML Attribute Values Must Always be Quoted
XML elements can have attributes in name/value pairs just like in HTML.
Entity References
Some characters have a special meaning in XML.
If you place a character like "<" inside an XML element, it will generate an error becausethe parser
interprets it as the start of a new element.
This will generate an XML error:<message>salary < 1000</message>
To avoid this error, replace the "<" character with an entity reference:
<message>salary < 1000</message>
Comments in XML
The syntax for writing comments in XML is similar to that of HTML:
<!-- This is a comment -->
Two dashes in the middle of a comment are not allowed:
<!-- This is an invalid -- comment -->
XML Elements
An XML document contains XML Elements.
What is an XML Element?
An XML element is everything from (including) the element's start tag to (including) theelement's
end tag.
<price>29.99</price>
An element can contain:
text
attributes
other elements
or a mix of the above
<bookstore>
<book category="children">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
In the example above:
<title>, <author>, <year>, and <price> have text content because they contain text(like 29.99).
<bookstore> and <book> have element contents, because they contain elements.
<book> has an attribute (category="children").
Empty XML Elements
An element with no content is said to be empty.In XML, you can indicate an empty element like
this:<element></element>
You can also use a so called self-closing tag:<element />
The two forms produce identical results in XML software (Readers, Parsers, Browsers).
Empty elements can have attributes.
Display Books.xml
XML DTD
The purpose of a DTD is to define the structure and the legal elements and attributes ofan 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 inthe
document:
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ENTITY nbsp " ">
<!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; ©right;</footer>
</note>
Tip: An entity has three parts: it starts with an ampersand (&), then comes the entity
name, and it ends with a semicolon (;).
Namespaces
XML Namespaces provide a method to avoid element name conflicts.
Name Conflicts: In XML, element names are defined by the developer. This often results in a
conflictwhen trying to mix XML documents from different XML applications.
This XML carries HTML table information:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This XML carries information about a table (a piece of furniture):
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
If these XML fragments were added together, there would be a name conflict. Bothcontain a <table>
element, but the elements have different content and meaning.
A user or an XML application will not know how to handle these differences.Solving the Name
Conflict Using a Prefix. Name conflicts in XML can easily be avoided using a name prefix.
This XML carries information about an HTML table, and a piece of furniture:
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
In the example above, there will be no conflict because the two <table> elements havedifferent
names.
When using prefixes in XML, a namespace for the prefix must be defined.The namespace can be
defined by an xmlns attribute in the start tag of an element.The namespace declaration has the
following syntax. xmlns:prefix="URI".
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="https://www.w3schools.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
In the example above:
The xmlns attribute in the first <table> element gives the h: prefix a qualifiednamespace.
The xmlns attribute in the second <table> element gives the f: prefix a qualifiednamespace.
When a namespace is defined for an element, all child elements with the same prefix areassociated
with the same namespace.Namespaces can also be declared in the XML root element:
<root xmlns:h="http://www.w3.org/TR/html4/"xmlns:f="https://www.w3schools.com/furniture">
Note: The namespace URI is not used by the parser to look up information.
The purpose of using an URI is to give the namespace a unique name.However, companies often use
the namespace as a pointer to a web page containingnamespace information.
XML Naming Rules
XML elements must follow these naming rules:
Element names are case-sensitive
Element names must start with a letter or underscore
Element names cannot start with the letters xml (or XML, or Xml, etc)
Element names can contain letters, digits, hyphens, underscores, and periods
Element names cannot contain spaces
Any name can be used, no words are reserved (except xml).
Best Naming Practices
Create descriptive names, like this: <person>, <firstname>, <lastname>.
Create short and simple names, like this: <book_title> not like this:
<the_title_of_the_book>.
Avoid "-". If you name something "first-name", some software may think you want tosubtract
"name" from "first".
Avoid ".". If you name something "first.name", some software may think that "name" isa property of
the object "first".
Avoid ":". Colons are reserved for namespaces (more later).
Non-English letters like éòá are perfectly legal in XML, but watch out for problems if yoursoftware
doesn't support them.
XML Attribute
XML elements can have attributes, just like HTML.Attributes are designed to contain data related to
a specific element.
XML Attributes Must be Quoted. Attribute values must always be quoted. Either single or double
quotes can be used.
For a person's gender, the <person> element can be written like this:
<person gender="female">
or like this:
<person gender='female'>
If the attribute value itself contains double quotes you can use single quotes, like in this
example:
<gangster name='George "Shotgun" Ziegler'>
or you can use character entities:
<gangster name="George "Shotgun" Ziegler">
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
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 forinterchanging data.With XML Schema,
you can verify data.
bookstore{
color: blue;
width: 100;
}
author{
display:block;
}
publisher{
display:block;
}
price{
display:block;
}
title {
font-size:25px;
font-weight:bold;
display:block; }
XPath
XPath is a major element in the XSLT standard.
XPath can be used to navigate through elements and attributes in an XML document.
XSLT Example(menu.xml)
We will use the following XML document:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="menu.xsl"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple
syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped
cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>Light Belgian waffles covered with an assortment of fresh berries
and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular hash
browns</description>
<calories>950</calories>
</food>
</breakfast_menu>
XML Processors
XMLHttpRequest Object
All modern browsers have a built-in XMLHttpRequest object to request data from aserver.
The XMLHttpRequest Object
The XMLHttpRequest object can be used to request data from a web server.The XMLHttpRequest
object is a developers dream, because you can:
Update a web page without reloading the page
Request data from a server - after the page has loaded
Receive data from a server - after the page has loaded
Send data to a server - in the background XMLHttpRequest Example
When you type a character in the input field below, an XMLHttpRequest is sent to theserver, and
some name suggestions are returned (from the server):
A common JavaScript syntax for using the XMLHttpRequest object looks much like this:
Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "filename", true);
xhttp.send();
Example Explained
The first line in the example above creates an XMLHttpRequest object:
var xhttp = new XMLHttpRequest();
The onreadystatechange property specifies a function to be executed every time the
status of the XMLHttpRequest object changes:
xhttp.onreadystatechange = function()
When readyState property is 4 and the status property is 200, the response is ready:
if (this.readyState == 4 && this.status == 200)
The responseText property returns the server response as a text string.
The text string can be used to update a web page:
document.getElementById("demo").innerHTML = xhttp.responseText;
XML Parser
All major browsers have a built-in XML parser to access and manipulate XML.
XML Parser
There are two types of parser available: 1) DOM Parser, 2) SAX Parser
The XML DOM (Document Object Model) defines the properties and methods for
accessing and editing XML.However, before an XML document can be accessed, it must be loaded
into an XML DOMobject.All modern browsers have a built-in XML parser that can convert text into
an XML DOMobject.
Parsing a Text String
This example parses a text string into an XML DOM object, and extracts the info from it with
JavaScript:
The XML DOM is a standard for how to get, change, add, and delete XML elements.
This example loads a text string into an XML DOM object, and extracts the info from it
with JavaScript:
Example
<html>
<body>
<p id="demo"></p>
<script>
var text, parser, xmlDoc;
text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
Example Explained
Example
Request the file cd_catalog.xml and use the response as an XML DOM object:
xmlDoc = xmlhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
Example
<html>
<body>
<p id="demo"></p>
<script>
var text, parser, xmlDoc;
text = "<bookstore><book>" +
"<title>Everyday Italian</title>" +
"<author>Giada De Laurentiis</author>" +
"<year>2005</year>" +
"</book></bookstore>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
Two-Tier Architecture
- The two-tier architecture is also known as the client/server architecture.
- It consists mainly of two tiers:
o data and
o client (GUI).
- The application logic can be located in either the client tier.
- Which results in a fat client or located in the data tier.
- which results in a fat server (see Figure).
Three-Tier Architecture
- To address the issues of the two-tier architecture, the application logic will be placed in its
own tier.
- Thus applications can be portioned into three tiers.
- The first tier is referred to as the presentation layer, and consists of the application GUI.
- The middle tier, or the business layer, consists of the business logic to retrieve data for the
user requests.
- The back-end tier, or data layer, consists of the data needed by the application.
- Figure illustrates the three-tier architecture.
- The decoupling of application logic from either presentation or data increases the flexibility
of the application design.
- Multiple views or a GUI can be added without changing the existing application logic.
- Similarly, multiple applications can be created using the same data model.
- Changing the components of one tier should not impact the other two tiers.
- For example, any change to the data or GUI will not affect the application logic.
Note :- 1
- The three-tier architecture is the basis for J2EE applications.
- In which EJBs provide a mechanism to build application logic.
- While JSPs and servlets abstract the presentation layer and allow interaction with the
business layer.
- One important feature of the three-tier architecture is sharing system resources by all clients.
- Which results in :
o highly efficient,
o scalable,
o secure, and
o reliable applications.
Note : - 2
- The J2EE platform is designed not only to support a multitier architecture to partition
applications.
- But also to provide infrastructure common services to reduce the complexity of developing
and deploying these applications.
- Other than multitier, the J2EE architecture provides the enterprise with common
infrastructure services.
- Which help in developing and deploying :
o portable,
o secure and
o transactional applications.
- The J2EE architecture partitions enterprise applications into three fundamental parts:
o components,
o containers, and
o connectors.
Note :- 3
- Multitier distributed applications follow the Model-View-Controller (MVC) paradigm,.
- This design pattern provides clean separation between tiers.
- Using this paradigm, the model (data tier) is separated from the view (client and presentation
tiers).
- Similarly, the controller (the application logic tier) is separated from both the view and the
model.
- Containers transparently provide common services :
o including transaction,
o security,
o persistence, and
o resource pooling, to both clients and components.
Features of EE platform
The Java EE stands for Java Enterprise Edition, which was earlier known as J2EE and is
currently known as Jakarta EE. It is a set of specifications wrapping around Java SE (Standard
Edition). The Java EE provides a platform for developers with enterprise features such as distributed
computing and web services. Java EE applications are usually run on reference run times such as
microservers or application servers. Examples of some contexts where Java EE is used are e-
commerce, accounting, banking information systems.
Specifications of Java EE
Java EE has several specifications which are useful in making web pages, reading and writing from
database in a transactional way, managing distributed queues. The Java EE contains several APIs
which have the functionalities of base Java SE APIs such as Enterprise JavaBeans, connectors,
Servlets, Java Server Pages and several web service technologies.
Fig: specifications of EE platform.
Web server is a computer where the web content is stored. Basically web server is used to host
the web sites but there exists other web servers also such as gaming, storage, FTP, email etc.
Architecture
Web Server Architecture follows the following two approaches:
1. Concurrent Approach
2. Single-Process-Event-Driven Approach.
Concurrent Approach
Concurrent approach allows the web server to handle multiple client requests at the same time. It
can be achieved by following methods:
Multi-process
Multi-threaded
Hybrid method.
Application Servers
An application server is a server specifically designed to run applications. The "server" includes
both the hardware and software that provide an environment for programs to run.
Application servers are used for many purposes. Several examples are listed below:
An application server provides the processing power and memory to run these
applications in real-time. It also provides the environment to run specific applications. For
example, a cloud service may need to process data on a Windows machine. A Linux-
based server may provide the web interface for the cloud service, but it cannot run
Windows applications. Therefore, it may send input data to a Windows-based application
server. The application server can process the data, then return the result to the web
server, which can output the result in a web browser.
JDBC DRIVERS
JDBC Driver is a software component that enables java application to interact with the database. There
are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC
bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC
drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
o easy to use.
o can be easily connected to any database.
Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.
Advantage:
Disadvantage:
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
ResultSet interface
4. Standard mappings for SQL types to classes and interfaces in the Java programming
language
5. Custom mapping an SQL user-defined type (UDT) to a class in the Java programming
language
6. Metadata
7. Exceptions
SQLException -- thrown by most methods when there is a problem accessing data and by
some methods for other reasons
SQLWarning -- thrown to indicate a warning
DataTruncation -- thrown to indicate that data may have been truncated
BatchUpdateException -- thrown to indicate that not all commands in a batch update
executed successfully
Servlets
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was common as a server-side programming language.
However, there were many disadvantages to this technology.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
1. Servlet is a technology which is used to create a web application.
2. Servlet is an API that provides many interfaces and classes including documentation.
3. Servlet is an interface that must be implemented for creating any Servlet.
4. Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
5. Servlet is a web component that is deployed on the server to create a dynamic web page.
Advantages of Servlet:
There are many advantages of Servlet over CGI. The web container creates threads for handling the
multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a
common memory area, lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
4. Secure: because it uses java language.
Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.
Servlets Tasks
Servlets perform the following major tasks −
Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
Servlets Packages
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http requests
only.
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet.
1. The servlet is initialized by calling the init() method.
2. The servlet calls service() method to process a client's request.
3. The servlet is terminated by calling the destroy() method.
4. Finally, servlet is garbage collected by the garbage collector of the JVM.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and
calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is the
signature of these two methods.
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the
implementation of all the methods of these interfaces except the service method. GenericServlet
class can handle any type of request so it is protocol-independent. You may create a generic servlet
by inheriting the GenericServlet class and providing the implementation of the service method.
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It
provides http specific methods such as doGet, doPost, doHead, doTrace etc. There are many
methods in HttpServlet class. They are as follows:
1) public void service(ServletRequest req,ServletResponse res) dispatches the request to the
protected service method by converting the request and response object into http type.
2) protected void service(HttpServletRequest req, HttpServletResponse res) receives the
request from the service method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3) protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the
GET request. It is invoked by the web container.
4) protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the
POST request. It is invoked by the web container.
5) protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the
HEAD request. It is invoked by the web container.
6) protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles
the OPTIONS request. It is invoked by the web container.
7) protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the
PUT request. It is invoked by the web container.
8) protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the
TRACE request. It is invoked by the web container.
9) protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the
DELETE request. It is invoked by the web container.
10) protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.
Method Description
public String getParameter(String name) is used to obtain the value of a parameter by name.
public int getContentLength() Returns the size of the request entity data, or -1 if not
known.
public String getCharacterEncoding() Returns the character set encoding for the input of
this request.
public String getContentType() Returns the Internet Media Type of the request entity
data, or null if not known.
public abstract String getServerName() Returns the host name of the server that received the
request.
public int getServerPort() Returns the port number on which this request was
received.
RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility of dispatching the request to another resource
it may be html, servlet or jsp. This interface can also be used to include the content of another
resource also. It is one of the way of servlet collaboration. There are two methods defined in the
RequestDispatcher interface.
As you see in the above figure, response of second servlet is sent to the client. Response of the first
servlet is not displayed to the user.
As you can see in the above figure, response of second servlet is included in the response of the first
servlet that is being sent to the client.
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to
another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL. It
works at client side because it uses the url bar of the browser to make another request. So, it can
work inside and outside the server.
It sends the same request and response It always sends a new request.
objects to another servlet.
It can work within the server only. It can be used within and outside the server.
URL Rewriting:
<a href="url ? name=value">display text </a>
In client-server communication, we will be writing lots of URLs to the client machine as part of the
response. In URL-Rewriting, we are going to change the way we write URL. While writing some
URL to client machine, we will append a query string(name=value) that contains client data.
Whenever the client submits this re-written URL to the server, server retrieves the client data form
the URL, and generates the response back to the intended client.
Cookies:
A Cookie is a small piece of data about the client, which will be stored on the client machine by the server
machine.
Cookies are used by server. To store a cookie, 1Kb of memory is required.
request
response+cookie
Client stores the cookies in the form a text file.
In cookies, just prior to writing some response to the client, we will create a cookie object and place
it in http headers, which will be delivered to the client. Once these http headers were received by the
client browser, it will retrieve the cookie from the header and stores them in a separate text file.
Whenever the client tries to send another request to the same server, browser will retrieve the cookie
associated with the server and places them as a part of http header, and send the request. Withe the
help of cookie, server remember the client.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
3. No limitation on number of cookies.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
3. They must be written to client prior to any response to client.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of
useful methods for cookies.
Constructor of Cookie class
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.
Method Description
HttpSession:
Purely handled by the server only.
A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object
is returned. This object can store a set of bindings that associate names with objects. The
setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of
HttpSession manage these bindings. It is important to note that session state is shared among all the
servlets that are associated with a particular client.
Advantages: Session tracking will available always
It can handle more than one value with single session object
The following servlet illustrates how to use session state. The getSession( ) method gets the current
session. A new session is created if one does not already exist. The getAttribute( ) method is called
to obtain the object that is bound to the name "date". That object is a Date object that encapsulates
the date and time when this page was last accessed. (Of course, there is no such binding when the
page is first accessed.) A Date object encapsulating the current date and time is then created. The
setAttribute( ) method is called to bind the name "date" to this object.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{ // Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}
When you first request this servlet, the browser displays one line with the current date and time
information. On subsequent invocations, two lines are displayed. The first line shows the date and
time when the servlet was last accessed. The second line shows the current date and time.
Syllabus: JSP Technology: Advantages of JSP over Java Servlet, Architecture of a JSP Page, Life
Cycle of a JSP Page, Working with JSP Basic Tags and Implicit Objects, Working with Action Tags in
JSP, Exploring EL, Exploring the Elements of Tag Extensions, Tag Extension API, Working with Simple
Tag Handlers Accessing Database from Servlet and JSP.
Introduction to JSP
Java Server Pages: It is a technology which is used to develop severside programs for generating
dynamic content. It is an extension to servlet technology.
Drawbacks in servlets:
1) To develop a serverside program using servlets, it requires two categories of people. One of them
is Web designers. Second are web developers.
2) For different display devices, different servlets are to be developed. i.e, because of writing
presentation logic inside business logic.
In servlets, html tags are embedded in between business logic. This increases the complexity of
development. And servlet programs are very lengthy.
In JSP, data presentation was separated from business logic. i.e, in JSP we can embed business logic
in between html tags. With respect to efficiency, JSP file will be served with the same efficiency as
that of a servlet, because, a JSP file will be internally converted into a servlet and then the request
will be processed.
Whenever a webserver receives a request for .jsp file, it will deligate the request to a virtual
component called JSPEngine. This engine will process the .jsp file in a 2 step process.
In this step JSPEngine translates a jsp file into a servlet based on the content of the jsp file. i.e, .java
file (servlet) will be created for .jsp file. Then the created .java file is compiled into .class file by
JSP engine.
2) Once the .class file is created, JSPEngine will forward it to ServletEngine to execute it. This
.class file is served to client by ServletEngine according to the life cycle of servlet.
JSP tags
JSP Directive tags: These tags are used to define how to translate a JSP page into the
corresponding servlet.
o page directive
o include directive
o taglib directive
page directive: This tag is used to define how exactly a servlet is created for the JSP
Example:
WEB-INF
example.jsp
Then, start the tomact server, open browser, type “localhost:8080” and press enter
Then click on Manager APP, enter username and password, then click signin, then select New
Folder, then type localhost:8080/New Folder/example.jsp
include directive:
It is used to include any external text based files(like .html, .txt). include directive will be executed
at the time of translation.
taglib directive:
It is used to include user defined tags. All the tags created by using custom tags are user defined tags
JSP Scripting Elements: these are used to place some valid java code or business logic in the JSP
program
It is used to declare user defined methods, and also used to override the methods
} %>
2) expression:The code placed within JSP expression tag is written to the output stream of the
response.
All the above expressions are evaluated at runtime and the output is written to the client
Syntax:
<%
-----
-----
%>
Example:
<html><body>
<% for(int i=0; i<=10;i++) { %>
<p> i = <%= i %></p>
<% } %>
</body></html>
JSP Action Tags:
JSP action tag is used to perform some specific tasks. They are used to control the flow between
pages and to use Java Bean.
1) Include action tag: It is used to include static dynamic content in the form of another JSP, html,
servlet file. It is evaluated at execution time.
The difference between include directive and include action tags is, first one ie evaluated at
execution time, so it is used to include dynamic content into JSP file. Second one is evaluated at
translation time, so it is used to include only static content.
2) Forward action tag: It is used to forward the request from one jsp to another jsp file.
It works like sendRedirect() of HttpServlet, the only difference is, sendRedirect() requires 2 pairs of
request and response objects, whereas jsp:forward requires only one pair of request and response
objects.
So jsp file allows to include java’s class file developed by java beans. It is used to achieve code
reusability.
A java bean is a simple java class which offers some properties with the help of getter and setter
methods.
Syntax:
We use jsp:setProterty action tag for calling the setter methods of java bean
We use jsp:getProperty action tag to call the getter methods of java bean
It is used to embed applet in the jsp file. The jsp:plugin action tag downloads plugin at client side to
execute an applet or bean.
Syntax: <jsp:plugin type= "applet | bean" code= "name of the class file"
codebase= "directory name that class file contains"
</jsp:plugin>
Attributes of jsp:plugin tag are
name, code, codebase, type, width, height, align, vspace, hspace, pluginurl, nspluginurl.
type, code and codebase are mandatory attributes, remaining are optional attributes.
These are used to separate business logic completely from jsp file.
In a normal jsp file, we can place any business logic, because of this jsp file looks like a java file. To
eliminate this we can use jsp:useBean action tag. Upto some extent it is capable of separating
business logic from jsp file. In case if you want to remove the business logic from jsp file, we have
to implement custom tags.
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>sample</short-name>
<uri>http://............</uri>
<tag>
<name>userdefined name</name>
<tag-class>class name</tag-class>
</tag>
</taglib>
Once we create a TLD file, it must be described in the web.xml file by using the element <taglib>.
while describing the TLD, we have to specify a unique URI and the location of corresponding TLD
file.
2) Tag handler class: It is used to implement the business logic that is associated with the custom
tag.
To create the Tag Handler, we are inheriting the TagSupport class and overriding
itsmethoddoStartTag().To write data for the jsp, we need to use the JspWriter class.
The PageContext class provides getOut() method that returns the instance of JspWriter class.
TagSupport class provides instance of pageContext bydefault.
There are 9 jsp implicit objects. These objects are created by the web container that are available to
all the jsp pages. These objects are references to interfaces and classes that are available in servlets.
Session Management:
In Java Sever Pages, the state information of a client is maintained by session object. In JSP, session
is an implicit object of type HttpSession.The Java developer can use this object to set,get or remove
attribute or to get session information.
Syntax to create session object: session.setAttribute("user",name); // user is the name of the session
object
Cookies
Cookies are text files stored on the client computer and they are kept for various information
tracking purposes. JSP transparently supports HTTP cookies using underlying servlet technology.
To delete cookies is very simple. If you want to delete a cookie, then you simply need to follow
these three steps −
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using the setMaxAge() method to delete an existing cookie.
Add this cookie back into the response header.
UNIT-2(JAVASCRIPT)
PART-A: SHORT ANSWER QUESTIONS
Blooms
Course
Taxonomy
Outcome
S.NO QUESTION Level
1 Write a JavaScript code for ONFOCUS event. L2
2 List out various Data types supported in python. L2
3 Write JavaScript function to validate email-id. L3
UNIT-5(JSP)
PART-A: SHORT ANSWER QUESTIONS
Blooms
Course
S.NO QUESTION Taxonomy
Outcome
Level
1 List out JSP implicit Objects. L1
2 Differentiate JSP include and JSP forward action tags L2
3 Explain the anatomy of JSP page? L2
4 What is deployment description? L1
5 Explain the concept of Cookie. L2
6 Interpret in your own words about session tracking L3
7 What is JSPEngine. What is the use of it. L2
11. a) What is HTTP and Explain Http Request and Response Formats? 5M
b)Write short noteonthe following tags. < img >, < table >, < frameset >, < pre > 5M
12.a) What is the use ofXML namespaces? Explain in detail with an example? 5M
b)Why XSLT is importantfor XML? 5M
13.a) Write ajava script code to find sum of n even numbers? Read the value of n from user? 6M
b)What is AJAX? List out various security issues with AJAX? 4M
FACULTY OF ENGINEERING
B.E. 3/4 (CSE) II – Semester (New) (Main) Examination, May / June 2017
Subject: Web Programming and Services
Time: 3 Hours Max.Marks: 75
Note: Answer all questions from Part A and any five questions from Part B.
PART – A (25 Marks)
1 Mention the MIME format for PDF documents. 2M
2 Write Javascript code to validate range from 10-100. 3M
3 Differentiate between Servlet and CGI? 3M
4 What is Session? 2M
5 What is the purpose of deployment descriptor? 2M
6 List the implicit objects in JSP. 2M
7 Write the syntax of UseBean tag. 3M
8 Why type 4 driver referred to as thin driver? 3M
9 Distinguish between Statement and PreparedStatement object. 3M
10Name the server on which ASP pages are deployed. 2M
12. a)Write a Servlet program to read the details from the form and store them indatabaseusing
JDBC. 6M
b)What is session tracking? How do we track user sessions with Cookies?Giveanexample. 4M
13. a)What is webserver? Explain different webservers and describe the sequenceof steps for
deploying a web application. 6M
b)Write a JSP page demonstrating the usage of JSP include and forward tag. 4M
16. a)Explain different types of hyperlinks. Design a webpage to display chapters andchapter
contents, apply hyperlink within a page to navigate to chapter contents. 6M
b)Describe enterprise architectural styles. 4M
17. Write short notes on:
a) Filter. 5M
b) Connection Pooling. 5M
****