SCSX1016
SCSX1016
SATHYABAMA UNIVERSITY
1
SCSX1016 Web Technology
Unit-1
Introduction
Web technology is the establishment and use of mechanisms that make it possible for different
computers to communicate and share resources.
2) Programming Languages and Technologies which help in creating applications for the web:
some of the languages are Perl, C#, Java and Visual Basic .Net.
3) Web servers and server technologies which facilitate request handling on a network where
different users have to share the same resources and communicate with one another.
4) Databases, which are crucial for data and information storage on a computer network.
Network Concepts
A network is a communication system that allows users to access resources on other computers
and exchange messages with one another. It allows users to share resources on their own system
or access shared resources on other systems.
Web technologies are infrastructural building blocks of any effective computer network: Local
Area Network (LAN), Metropolitan Area Network (MAN) or a Wide Area Network (WAN),
such as the Internet. Communication on a computer could never be as effective as they are
without the plethora of web technologies in existence.
Web technologies played an important part in redefining access to data, the sharing of data, and
the design of network applications. An intranet is an internal network built with Web
technologies while an extranet is a business-to-business network with links across the Internet.
Standard protocols:
TCP
handles conversion between messages and streams packets
IP
handles addressing of packets across networks
TCP/IP
enables packets to be sent across multiple networks using multiple
standards
Telnet
One of the earliest standards for exchanging transmission, directly
connect accounts on different systems.
SMTP
Specifies another way of direct connection
• MIME
Extension to the SMTP Protocol which supports the exchange
of richer data files such as audio-, video-, and images data.
• FTP
Supports file transfer between Internet sites and allows a system
to publish a set of files by hosting an FTP sever.
Web concepts:
What is the web?
The web is a whole bunch of interconnected computers talking to one another. The computers
(on the web) are typically connected by phone lines, digital satellite signals, cables, and other
types of data-transfer mechanisms. A ‘data-transfer mechanism’ is a way to move information
from point A to point B to point C and so on.
The computers that make up the web can be connected all the time, or they can be connected
only periodically. The computers that are connected all the time are typically called a ‘server’.
Servers are computers just like the one you’re using now to read this notes, with one major
difference, they have a special software installed called ‘server’ software.
What is Internet?
The Internet is essentially a global network of computing resources. We can think of the Internet
as a physical collection of routers and circuits as a set of shared resources.
Internet-Based Services
• Email − A fast, easy, and inexpensive way to communicate with other Internet users
around the world.
• Telnet − Allows a user to log into a remote computer as though it were a local system.
• FTP − Allows a user to transfer virtually every kind of file that can be stored on a
computer from one Internet-connected computer to another.
• UseNet news − A distributed bulletin board that offers a combination news and
discussion service on thousands of topics.
• World Wide Web (WWW) − A hypertext interface to Internet information resources.
What is WWW?
WWW stands for World Wide Web. A technical definition of the World Wide Web is − All the
resources and users on the Internet that are using the Hypertext Transfer Protocol (HTTP).
In simple terms, The World Wide Web is a way of exchanging information between computers
on the Internet, tying them together into a vast collection of interactive multimedia resources.
What is HTTP?
HTTP stands for Hypertext Transfer Protocol. This is the protocol being used to transfer
hypertext documents that makes the World Wide Web possible.
A standard web address such as Yahoo.com is called a URL and here the prefix http indicates its
protocol.
What is Website?
Website is a collection of various pages written in HTML markup language. This is a location on
the web where people can find tutorials on latest technologies. Similarly, there are millions of
websites available on the web.
Each page available on the website is called a web page and first page of any website is called
home page for that site.
Every Website sits on a computer known as a Web server. This server is always connected to the
internet. Every Web server that is connected to the Internet is given a unique address made up of
a series of four numbers between 0 and 256 separated by periods. For example, 68.178.157.132
or 68.122.35.127.
When you register a Web address, also known as a domain name, such as tutorialspoint.com you
have to specify the IP address of the Web server that will host the site.
Web Browsers are software installed on your PC. To access the Web you need a web browsers,
such as Netscape Navigator, Microsoft Internet Explorer or Mozilla Firefox.
On the Web, when you navigate through pages of information through web browser is
commonly known as browsing or surfing.
What is SMTP Server?
SMTP stands for Simple Mail Transfer Protocol Server. This server takes care of delivering
emails from one server to another server. When you send an email to an email address, it is
delivered to its recipient by a SMTP Server.
What is ISP?
ISP stands for Internet Service Provider. They are the companies who provide you service in
terms of internet connection to connect to the Internet.
You will buy space on a Web Server from any Internet Service Provider. This space will be used
to host your Website.
What is DNS?
DNS stands for Domain Name System. When someone types in your domain name,
www.example.com, your browser will ask the Domain Name System to find the IP that hosts
your site. When you register your domain name, your IP address should be put in a DNS along
with your domain name. Without doing it your domain name will not be functioning properly.
What is W3C?
W3C stands for World Wide Web Consortium which is an international consortium of
companies involved with the Internet and the Web.
The W3C was founded in 1994 by Tim Berners-Lee, the original architect of the World Wide
Web. The organization's purpose is to develop open standards so that the Web evolves in a single
direction rather than being splintered among competing factions. The W3C is the chief standards
body for HTTP and HTML.
What is Hyperlink?
What is URL?
URL stands for Uniform Resource Locator, and is used to specify addresses on the World Wide
Web. A URL is the fundamental network identification for any resource connected to the web
(e.g., hypertext pages, images, and sound files).
protocol://hostname/other_information
The protocol specifies how information is transferred from a link. The protocol used for web
resources is HyperText Transfer Protocol (HTTP). Other protocols compatible with most web
browsers include FTP, telnet, newsgroups, and Gopher.
The protocol is followed by a colon, two slashes, and then the domain name. The domain name
is the computer on which the resource is located.
Links to particular files or subdirectories may be further specified after the domain name. The
directory names are separated by single forward slashes.
Internet Addresses
There are two major types of addresses on the Internet. One is a person's e-mail address,
and the other is a web page or web site address, which is known as a URL. The proper
name for a website address is uniform resource locator (URL).
Example:
Email: [email protected]
URL: http://localhost:8080/Multifiel.html
URL
The Uniform Resource Locator was created in 1994 by Tim Berners-Lee.
It is used to address a document on the www.
The syntax is:-
scheme://host.domain:port/path/filename
Example:- http://localhost:8080/Multifiel.html
Types of URL
Relative URL:-
A String is reliable with the URL path syntax is known as relative URL.
Absolute URL:-
A complete URL(beginning with a scheme) is known as absolute URL.
Base URL:-
Base URL is a URL which is used to convert a relative URL to an absolute URL.
URIs, URNs, and IRIs
Uniform Resource Identifier (URI), Every URI is defined as consisting of four parts, as
follows:
<scheme name> : <hierarchical part> [ ? <query> ] [ # <fragment> ]
The scheme name consist of a sequence of characters beginning with a letter and
followed by any combination of letters, digits, plus ("+"), period ("."), or hyphen ("-").
("
The hierarchical part begins with a double forward slash ("//"), followed by an authority part
and an optional path.
The authority part holds an optional user
user-information
information part, terminated with "@" (e.g.
username:password@); a hostname (e.g., domain name or IP address); and an optional
port number, preceded by a colon ":".
The path part is a sequence of segments separated by a forward slash ("/").
The query is an optional part, separated by a question mark ("?").
The fragment is an optional part separated from the front parts by a hash ("#").
EXAMPLE:
http://en.wikipedia.org/wiki/URI#Examples_of_URI_references
"http" specifies the 'scheme' name,
"en.wikipedia.org" is the 'authority',
"/wiki/URI" the 'path' pointing to this article, and "#Examples_of_URI_
"#Examples_of_URI_references"
references" is a
'fragment' pointing to this section.
Markup Languages
o Notation for adding formal structure to text.
o Standard General Markup Language, SGML (1986)
o Markup languages do not directly instruct computers like procedural languages rather
indirectly instruct computer like logical languages.
o They do this by using tags:
elements
attributes
entities
text
PCDATA
Parsed Character Data (PCDATA) is a data definition that created in Standard General
Markup Language (SGML), and is used also in Extensible Markup Language (XML) .
Document Type Definition (DTD) to assign mixed content XML elements.
SGML: a Brief Introduction
Standard General Markup Language
In 1986, ISO approved an international standard for descriptive markup.
SGML is a metalanguage(a language that can be used to explain languages) for defining
markup languages.
HTML is one example of an SGML-defined language
What is the WWW?
A hypertext system that runs on top of the Internet, based on Three Main Standards
– URL
– HTTP
– HTML
The Origins of the WWW
WWW was invented by Tim Berners-Lee at CERN(European Organization for
Nuclear Research-1989)
1.OPTIONS
2.PUT
3.TRACE
4.DELETE
5.CONNECT
The GET Method is used to getting the data from server.
The POST Method is used for sending data to the server.
When a user wants to know about the headers like MIME(Multipurpose Internet Mail
Extensions) Types Like
1.Applications 2.Audio 3.Image
4.Message 4.Text 5.Video
What is HTML?
HTML stands for Hyper Text Markup Language. This is the language in which we write web
pages for any Website. Even the page you are reading right now is written in HTML.
This is a subset of Standard Generalized Mark-Up Language (SGML) for electronic publishing,
the specific standard used for the World Wide Web.
HTML Versions
Version Year
HTML 1991
HTML+ 1993
HTML 2.0 1995
HTML 3.2 1997
HTML 4.01 1999
XHTML 1.0 2000
HTML5 2012
Element examples
Header of the HTML document:<head>...</head>.
Usually the title should be included in the head, for example:
<head>
<title>The Title</title>
</head>
Changing Font Size
There are three different ways to change the size of the font. Method 1, Method 2, and
Method 3.
Method 1:
The first method is to use the "big" and "small" tags.
Method 2:
You can use + and - along with a number to shrink and grow the font.
Method 3:
Headers are abbreviated with the letter "h" and a number from 1 to 6.
Method 1:
For example, to increase the font by one degree surround the text with the following tags:
<big> chosen text </big>
If you want to make it even bigger, you surround it again:
<big> <big> chosen text </big> </big>
To make the font small, surround it with the small tag:
<small> chosen text </small>
If you want to make it even smaller, surround it with the tag again:
<small> <small> chosen text </small> </small>
Method 2:
You can use + and - along with a number to shrink and grow the font:
<font size=+2> chosen text </font>
<font size=+1> chosen text </font> ........(same as <big> )
<font size=+0> chosen text </font> .........(plain text)
<font size=-1> chosen text </font> .......(same as small> )
<font size=-2> chosen text </font>
Method3:
Headings: HTML headings are defined with the <h1> to <h6> tags:
<h1>Heading1</h1>
<h2>Heading2</h2>
<h3>Heading3</h3>
<h4>Heading4</h4>
<h5>Heading5</h5>
<h6>Heading6</h6>
Paragraph Tags
Tag: <p> </p> (Has a closing tag) </> means closed.
Attributes:
Align=left, right, center
Code Example:
<p align=left>This is a paragraph tag</p>
<p align=center >This is a paragraph tag</p>
What it looks like:
This is a paragraph tag.
This is a paragraph tag.
HTML Text Formatting
<html> <body>
<p> <b>This text is bold </b> </p>
<p> <strong>This text is strong </strong></p>
<p> <big>This text is big </big></p>
<p> <i>This text is italic </i></p>
<p>This is<sub> subscript</sub> and <sup>superscript</sup></p>
</body></html>
<b> (bold) tag and also a <strong> tag since both are displayed in bold type.
Output:
1. This text is bold
2. This text is strong
3. This text is big
4. This text is italic
This is subscript and superscript
Blinking Text:
To make text blink surround the chosen text with these tags.
<blink> chosen text </blink>
Html Link Tag:
HTML links are defined with the <a> tag.
The link address is specified in the href attribute:
Example
The "color name" can be one of two things. If you only want to use a common color,
you can simply put in the name of that color.
<font color="color name"> chosen text </font>
<font color="black"> Black </font>
<font color="white"> White (White) </font>
<font color="yellow"> Yellow (Yellow) </font>
<font color="orange"> Orange </font>
<font color="pink"> Pink (Pink) </font>
<font color="red"> Red </font>
<font color="green"> Green </font>
<font color="blue"> Blue </font>
The second thing you can use as a "color name" is a numeric code for the color.
Syntax:<font color="#rrggbb"> chosen text </font>
Here is a red color whose hex-code number is # f f 0 0 0 0 . (# f f 0 0 0 0)
Here is a green color whose hex-code number is-- # 0 0 f f 0 0 . (# 0 0 f f 0 0)
Here is a blue color whose hex-code number is-- # 0 0 0 0 f f . (# 0 0 0 0 f f)
Here is a light-blue color whose hex-code number is-- # 0 0 f f f f . (# 0 0 f f f f)
Here is another blue color whose hex-code number is-- # 1 f 8 1 a 6 . (# 1 f 8 1 a 6)
Document Structure
<html>
<head><title>My First Web Page</title>
</head>
<body bgcolor="white">
<p>A Paragraph of Text.</p>
</body>
</html>
Nesting Tags
o To make something both bold and italic use the following tags:
o <b> <i> chosen text </i> </b>
o For big and red:
o <font color="#ff0000"> <big>chosen text </big> </font>
o Both the color and the size of the font at the same time
o <font size=+2 color="#0000ff"> chosen text </font>
HTML Line Breaks:
Use the <br /> tag if you want a line break (a new line) without starting a new paragraph:
Example: <p>This is<br />a para<br />graph with line breaks</p>
Output
This is
a para
graph with line breaks
The <br /> element is an empty HTML element. It has no end tag.
How To Draw A Line Across The Screen
To draw a line across the page type:
<hr>
This stands for "horizontal rule"
Types:
<hr width=75%>
<hr size=10>
<hr size=10 noshade>
<hr noshade>
<hr width=50% align=left>
<hr width=50% align=center>
<hr width=50% align=right>
How To Center a Section Of Text
The center tag also automatically inserts a blank line above and below the chosen text.
<center>chosen text</center>
How To Indent a Section Of Text
The blockquote tag also automatically inserts a blank line above and below the chosen
text.
<blockquote>chosen text</blockquote>
<BLOCKQUOTE ...> indicates that you are quoting a large section of text.
<Blockquote> is used to indicate a large portion of referenced text.
HTML List Tags
Tag Description
How it looks:
Table Example
<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>
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</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>
Comments
<html><body>
<table border="1">
<caption>Monthly savings</caption>
<tr> <th>Month</th> <th>Savings</th> </tr>
<tr> <td>January</td> <td>$100</td> </tr>
<tr> <td>February</td> <td>$50</td> </tr>
</table> </body> </html>
The rowspan attribute specifies the number of rows a cell should span.
Syntax:<td rowspan="number"> .
Example:
<html><body><table width="100%" border="1">
<tr> <th>Month</th> <th>Savings</th>
<th>Savings for holiday!</th> </tr>
<tr> <td>January</td> <td>$100</td>
<td rowspan="2">$50</td> </tr> <tr>
<td>February</td> <td>$80</td> </tr>
</table> </body></html>
The colspan attribute defines the number of columns a cell should span.
Syntax:<td colspan="number"> .
Example:
<html><body><table border="1">
<tr> <th>Month</th> <th>Savings</th> </tr>
<tr> <td>January</td> <td>$100</td> </tr>
<tr> <td>February</td> <td>$100</td> </tr>
<tr> <td colspan="2">Sum: $180</td> </tr>
</table> </body> </html>
The <col> tag defines attribute values for one or more columns in a table.
The <col> tag is useful for applying styles to entire columns, instead of repeating the styles
for each cell, for each row.
The <col> tag can only be used inside a <table> or a <colgroup> element.
In HTML the <col> tag has no end tag.
In XHTML, the <col> tag must be properly closed.
<html><body><table border="1">
<colgroup>
<col span="2" style="background-color:red" />
<col style="background-color:yellow" />
</colgroup>
<tr> <th>ISBN</th><th>Title</th> <th>Price</th> </tr>
<tr><td>3476896</td> <td>My first HTML</td>
<td>$53</td> </tr>
<tr> <td>5869207</td> <td>My first CSS</td>
<td>$49</td> </tr></table></body></html>
< → <
> → >
& → &
→ space
© → Copyright symbol ©
® → Registered trademark
" → Quotation mark “
N/A → Trademark TM
Example:
<HTML><HEAD>
<TITLE>Character Entities Example</TITLE>
</HEAD><BODY>
<H1 ALIGN="center">Big Company Inc.'s Tagging Products</H1><HR>
<P>Character entities like &copy; allow users to insert special characters like
©.</P>
<P>One entity that is both useful and abused is the nonbreakingspace.</P><BR/><BR/>
Inserting spaces is easy with &nbsp;<BR/>
Look: S P A
C E S.<BR/>
<HR><ADDRESS>
Contents of this page © 1999 Big Company, Inc.<BR/>
The<B>Wonder Tag</B> <P> ™ is a registered trademark of Big Company,
Inc.
</ADDRESS></BODY></HTML>
Address Tag:
The <address> tag defines the contact information for the author or owner of a document.
This way, the reader is able to contact the document's owner.
The <address> element is usually added to the header or footer of a webpage.
<address>
Written by W3Schools.com<br />
<a href="mailto:[email protected]">Email us</a><br />
Address: Box 564, Disneyland<br />
Phone: +12 34 56 78
</address>
The <pre> tag defines preformatted text:
If you want the text to appear exactly as you type it, use these tag, and it preserves both
spaces and line breaks.
Syntax:<pre> text</pre>
<pre>Text in a pre element
is displayed in a fixed-width
font, and it preserves
both spaces and
line breaks</pre>
<pre>for i = 1 to 10
print i
next I </pre>
These attributes are divided into core attributes, internationalization attributes, and
scripting events.
HTML 4’s core attributes are
ID, CLASS, STYLE, and TITLE.
HTML 4’s internationalization attributes are
LANG,DIR
HTML 4’s scripting events are
ONCLICK, ONDBLCLICK, ONMOUSEDOWN,
ONMOUSEUP, ONMOUSEOVER,etc..
The ID attribute is used to set a unique name for a tag in a document.
No two elements can have the same ID value in a single document.
The attribute's value must begin with a letter in the range A-Z or a-z and may be followed
by letters (A-Za-z), digits (0-9), hyphens ("-"), underscores ("_"), colons (":"), and
periods (".").
The value is case-sensitive.
<P ID="First Paragraph">This is the first paragraph of text.</P>
<P ID=“Second Paragraph">This is the second paragraph of text.</P>
The CLASS attribute is used to indicate the class or classes that a tag may belong to.
The CLASS attribute specifies the element to be a member of one or more classes.
<P ID="FirstParagraph" CLASS="important">
This is the first paragraph of text. </P>.
STYLE attribute
The STYLE attribute is used to add style sheet information directly to a tag.
<P STYLE="font-size: 18pt“>First paragraph text.</P>
The TITLE is used to provide advisory text about a tag or its contents.
<P TITLE="Introductory paragraph">
This is the first paragraph of text.</P>
Output:
The HTML Lang attribute can be used to declare the language of a Web page or a portion
of a Web page.
<html lang="en“> …………. </html>.
The HTML DIR Specifies the text direction for the content in an element.
The values are LTR (left to right) or RTL (right to left).
<P DIR="RTL">This is a right-to-left paragraph.</P>
This is a right-to-left paragraph.
<P DIR=“LTR">This is a left-to-right paragraph.</P>
This is a left-to-right paragraph
HTML 4’s Common scripting events:
ONCLICK, when the mouse button is clicked on an element;
ONDBLCLICK, when the mouse button is double-clicked on an element;
ONMOUSEDOWN, when the mouse button is pressed over an element;
ONMOUSEUP, when the mouse button is released over an element;
ONMOUSEOVER, when the mouse is moved onto an element;
ONMOUSEMOVE, when the mouse is moved while over an element;
ONMOUSEOUT, when the mouse is moved away from an element;
ONKEYPRESS, when a key is pressed and released over an element;
ONKEYDOWN, when a key is pressed down over an element;
ONKEYUP, when a key is released over an element.
Example:
<html>
<head>
<P onclick="alert(‘cse department!')">Press this paragraph.</P>
</head>
</html>
HTML Block Elements & inline Elements
o Block level elements normally start (and end) with a new line when displayed in a
browser.
o HTML block level elements can appear in the body of an HTML page.
o Block level elements create larger structures .
o List of block level elements
o P,h1, h2, h3, h4, h5, h6,ol, ul,
o Blockquote,dl,div,form,hr,table
o Inline elements are normally displayed without starting a new line.
o HTML inline level elements can appear in the body of an HTML page.
o inline elements create shorter structures.
o List of inline elements
o i, b , a href, strong
o span, sub, sup
o a, br, img, map
The HTML <span> element is an inline element that can be used as a container for text.
When used together with CSS, the <span> element can be used to set style attributes to
parts of the text.
The <span> tag can be inside <p> tags or <div> tags.
<html><body>
<p>My mother has <span style="color:lightblue;font-weight:bold">light blue</span>
eyes and my father has <span style="color:darkolivegreen;font-weight:bold">dark green</span>
eyes.</p>
</body></html>
Buttons
o Authors may create three types of buttons:
Submit Buttons
Reset Buttons
Push Buttons
Checkboxes
Radio Buttons
Menus
Text input
HTML Forms
HTML Forms are used to select different kinds of user input.
HTML forms are used to pass data to a server.
A form can contain input elements like text fields, checkboxes, radio-buttons, submit
buttons and more.
A form can also contain select lists, textarea, fieldset, legend, and label elements.
The <form> tag is used to create an HTML form:
<form>
.
input elements
.
</form>
Attributes:
Type -This attribute specifies the type of control to create. The default type is text
Name - This attribute assigns the control name.
Value - This attribute specifies the initial value of the control.
Size - This attribute tells the initial width of the control.
Control Type created with INPUT
Text Fields
Syntax:<input type="text" /> defines a one-line input field that a user can enter text.
<form>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" />
</form>
Output: First name: Last name:
A text field:
<input type="text" name="textfield" value="with an initial value" />
Password Field
Syntax:<input type="password" /> defines a password field:
<form>Password: <input type="password" name="pwd" />
</form>
Password:
A password field:
<input type="password" name="textfield3" value="secret" />
Radio Buttons
Username:
Push Button:
The <button> tag defines a push button:
<button type="button">Click Me!</button>.
Field set & legend:
The label element is used to combine text with another element of the form.
Syntax: <label>Label name:-Any control type </label>
Example:- <form>
<label name="male">Male</label>
<input type="radio" name="sex" id="male" />
<br />
<label name="female">Female</label>
<input type="radio" name="sex" id="female" />
</form>
o Male
o Female
The Text area Element:
The Text area is allows the user to enter multiple lines of data.
Textarea Vs Input
Input is an empty tag.
Textarea is not empty – any character data placed between the start and end tags
of a textarea is displayed as default text in the textarea box.
A multi-line text field :
<textarea name="textarea" cols="24" rows="2">Hello</textarea>
Design a Form
<html><head><title>My First Web Page</title>
</head><form>
First name: <input type="text" name="firstname" /><br />
Last name: <input type="text" name="lastname" /> <br />
Password: <input type="password" name="pwd" /><br />
Sex:<input type="radio" name="sex" value="male" /> Male
<input type="radio" name="sex" value="female" /> Female<br />
Vehicle:<input type="checkbox
type="checkbox"" name="vehicle" value="Bike" /> I have a bike
<input type="checkbox" name="vehicle" value="Car" /> I have a car<br />
Select a Car:<select>
<option value="volvo">Volvo</option>
<option value=“i10">i10</option>
<option value=“i20">i20</option>
<option value=“santro">santro</option>
</select>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Image Maps
</HTML>
Planet Map
Sun.html
Merglobe.html
Venglobe.html
Multimedia Components
Definition of Multimedia
Multimedia is a combination of text, graphic, sound, animation, and video that is delivered
interactively to the user by electronic or digitally manipulated.
AVI .avi The AVI (Audio Video Interleave) format was developed by
Microsoft.
The AVI format is supported by all computers running
Windows, and by all the most popular web browsers.
It is a very common format on the Internet, but not always
possible to play on non-Windows computers.
WMV .wmv The Windows Media format is developed by Microsoft.
Windows Media is a common format on the Internet, but
Windows Media movies cannot be played on non-Windows
computer without an extra (free) component installed.
MPEG .mpg The MPEG (Moving Pictures Expert Group) format is the
.mpeg most popular format on the Internet.
It is cross-platform, and supported by all the most popular
web browsers.
Quick .mov The QuickTime format is developed by Apple.
Time QuickTime is a common format on the Internet, but
QuickTime movies cannot be played on a Windows
computer without an extra (free) component installed.
Real .rm The RealVideo format was developed for the Internet by
Video .ram Real Media.
The format allows streaming of video (on-line video,
Internet TV) with low bandwidths.
Flash .swf The Flash (Shockwave) format was developed by
.flv Macromedia
Mpeg-4 .mp4 Mpeg-4 (with H.264 video compression) is the new format
for the internet.
Sound Formats
Real .rm The RealAudio format was developed for the Internet by
Audio .ram Real Media.
The format also supports video.
Wave .wav The Wave (waveform) format is developed by IBM and
Microsoft.
It is supported by all computers running Windows, and by
all the most popular web browsers (except Google Chrome).
WMA .wma The WMA format (Windows Media Audio), compares in
quality to MP3.
It is compatible with most players, except the iPod.
MP3 .mp3 MP3 files are actually the sound part of MPEG files.
.mpga The MPEG format was originally developed for video by
the Moving Pictures Experts Group.
MP3 is one of the most popular sound formats for music.
MIDI .mid The MIDI (Musical Instrument Digital Interface) is a format
.midi for electronic music devices like PC sound card.
Multimedia Components
The easiest way to add video or sound to your web site is to include the special HTML
tag called <embed>.
This tag instruct the browser itself to include controls for the multimedia automatically.
You should use <no embed> tag along with this tag to handle browsers who do not
support embed tag.
Syntax:
<EMBED SRC="welcome.avi" HEIGHT="100" WIDTH="100">
<NOEMBED>
<IMG SRC="welcome.gif" ALT="Welcome to Big Company, Inc."> </NOEMBED>
Attributes: Following is the list of important attributes for <embed> element.
align - It takes either center, left or right.
auto start - Indicates if the media should start automatically. Netscape default is true,
Internet Explorer is false.
loop - Specifies if the sound should be played continuously (set loop to true), a certain
number of times (a positive value) or not at all (false). This is supported by Netscape
only.
play count - Specifies the number of times to play the sound. This is alternat option for
loop if you are usiong IE.
hidden - Defines if the object shows on the page. A false value means no and true means
yes.
height - Height of the object in pixels or en.
width - Width of the object in pixels or en.
pluginspage - Specifies the URL to get the plugin software.
name - A name used to reference the object.
src - URL of the object to be embedded. This can be any recognizable by the user's
browser. It could be .mid, .wav, .mp3, .avi and so on).
volume - Controls volume of the sound. Can be from 0 (off) to 100 (full volume). This
attribute is supported by Netscape only.
HTML - Video Media Types
Flash movies (.swf), AVI's (.avi), and MOV's (.mov) file types are supported by the embed tag.
.swf files - are the file types created by Macromedia's Flash program.
.wmv files - are Microsoft's Window's Media Video file types.
.mov files - are Apple's Quick Time Movie format.
.mpeg files - are movie files created by the Moving Pictures Expert Group.
Background Audio - The <bgsound> Element:
You can use the <bgsound> tag to play a soundtrack in the background.
This tag is for Internet Explorer documents only.
Sounds can either be samples (WAV or AU format) or MIDI format.
Syntax:<BGSOUND SRC="start.wav">
<bgsound src="/html/yourfile.mid" > <noembed><img src="yourimage.gif"
alt="yourimage.gif" /></noembed> </bgsound>
Frames
HTML Frames
Frames allow you to divide the page into several rectangular areas and to display a
separate document in each rectangle.
Each of those rectangles is called a "frame".
Example:
<html> <body>
<frameset cols="30%,*">
<frame src="menu.html">
<frame src="content.html">
</frameset> </body> </html>
Attributes:
frameset - The parent tag that defines the characteristics of this frames page. Individual
frames are defined inside it.
frameset cols="#%, *" - The width that each frame will have. In the above example, we
chose the menu (the 1st column) to be 30% of the total page and used a "*", which means
the content (the 2nd column) will use the remaining width for itself (70%).
frame src="" - The URL of the web page to load into the frame.
Add a row to the top for a title and graphics with the code as follows:
<html> <body>
<frameset rows="20%,*">
<frame src="title.html">
<frameset cols="30%,*">
<frame src="menu.html">
<frame src="content.html">
</frameset> </frameset> </body> </html>
Framespacing and border are the same attribute, but some browsers only recognize one
or the other, so use both, with the same value, to be safe.
frameborder="#" - Determines whether there will be a border.
border="#"- Modifies the border width.
framespacing="#" -Modifies the border width, used by Internet Explorer.
Example of the same frameset without the borders
<html> <body>
<frameset border="0" frameborder="0" framespacing="0" rows="20%,*">
<frame src="title.html">
<frameset border="0" frameborder="0" framespacing="0" cols="30%,*">
<frame src="menu.html">
<frame src="content.html">
</frameset> </frameset> </body> </html>
Two Column Frameset
DHTML
This example changes the text color of the <h1> element to blue:
Example:
<h1 style="color:blue;">This is a Blue Heading</h1>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
When you move the mouse over a link, two things will normally happen:
CSS Fonts
The CSS color property defines the text color to be used for the HTML element.
The CSS font-family property defines the font to be used for the HTML element.
The CSS font-size property defines the text size to be used for the HTML element.
Cascading Order
What style will be used when there is more than one style specified for an HTML element?
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet
by the following rules, where number one has the highest priority:
1. Inline style (inside an HTML element)
2. External and internal style sheets (in the head section)
3. Browser default
So, an inline style (inside a specific HTML element) has the highest priority, which means that it
will override a style defined inside the <head> tag, or in an external style sheet, or a browser
default value.
References:
1. Thomas A. Powell, “ HTML: The Complete Reference” , Osborne/Mc Graw Hill, Third
Edition , 2001.
2. http://www.w3schools.com
3. http://www.tutorialspoint.com/
SCSX1016 Web Technology
UNIT-II
XML
What is XML?
XML Example
<?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>
XML is a software- and hardware-independent tool for storing and transporting data.
HTML
JavaScript
• It is as easy as HTML.
• XML is fully compatible with applications like JAVA, and it can be combined with any
application which is capable of processing XML irrespective of the platform it is being
used on.
• XML is an extremely portable language to the extent that it can be used on large
networks with multiple platforms like the internet, and it can be used on handhelds or
palmtops or PDAs.
• XML is an extendable language, meaning that you can create your own tags, or use the
tags which have already been created.
If the application can work along with XML, then XML can work on any platform and has no
boundaries.
XML Applications
database interchange:
– example: home health care in the US (data interchange between hospitals and health agencies)
current: log into hospital, see records in browser, print them and key them into own database XML: log
into hospital, drag records onto own database
distributed processing:
web agents:
– intelligent searches over the web search criteria and searched documents have to be
expressed in standard format (e.g. XML); structural requirements beyond HTML;
Benefits of XML
• Simplicity
Information coded in XML is easy to read and understand, plus it can be processed easily
by computers.
• Openness
XML is a W3C standard, endorsed by software industry market leaders.
• Extensibility
There is no fixed set of tags.
New tags can be created as they are needed.
• Self-description
XML documents can be stored without [schemas] because they contain meta data; any
XML tag can possess an unlimited number of attributes such as author or version.
• Contains machine-readable context information
Tags, attributes and element structure provide context information ... opening up new
possibilities for highly efficient search engines, intelligent data mining, agents, etc.
• Separates content from presentation
XML tags describe meaning not presentation.
The look and feel of an XML document can be controlled by XSL stylesheets, allowing
the look of a document (or of a complete Web site) to be changed without touching the
content of the document.
Multiple views or presentations of the same content are easily rendered.
• Supports multilingual documents and Unicode
This is important for the internationalization of applications.
• Facilitates the comparison and aggregation of data
The tree structure of XML documents allows documents to be compared and aggregated
efficiently element by element.
• Can embed multiple data types
XML documents can contain any possible data type — from multimedia data (image,
sound, video) to active components (Java applets, ActiveX).
• Can embed existing data
Mapping existing data structures like file systems or relational databases to XML is
simple....
• Provides a “one-server view” for distributed data
XML documents can consist of nested elements that are distributed over multiple remote
servers. XML is currently the most sophisticated format for distributed data — the World
Wide Web can be seen as one huge XML database.
• Rapid adoption by industry
Software AG, IBM, Sun, Microsoft, Netscape, DataChannel, SAP ...
Advantages of XML over HTML
The root cause of the problem lies in HTML (Hyper Text Markup Language), the defacto
standard for web publication. The major problem with HTML is its ‘fixed tagset’. This tagset
is mainly for display of the content and HTML provides no tag to address the content precisely.
XML (extensible Markup Language) designed by W3C (World Wide Web Consortium)
promises a possible solution to this problem.
The major advantage of XML over HTML is its extensibility i.e., provision of user defined
tags and attributes to identify the structural elements of a document. XML also provides
structural complexity to define document structure that can be nested at any level of complexity.
XML also facilitates the transfer of structured data between servers. XML describes data, such
as city name, temperature and barometric pressure, while HTML defines tags that describe how
the data should be displayed, such as with a bulleted list or a table.
SAX is an event-driven interface. The programmer specifies an event that may happen and, if it
does, SAX gets control and handles the situation. SAX works directly with an XMLparser.
SAX was developed collaboratively by members of the XML-DEV mailing list. The original
version of SAX, which was specific to Java, was the first API for XML in Java to gain broad
industry support.
• SAX is lower-level than DOM – actually, DOM uses SAX – harder to use but more
flexible and efficient
SAX parser is the most commonly used xml parser in Java after DOM, unlike DOM Sax does
not loads the XML into memory before parsing it, nor it creates any type of object from XML.
SAX is a better choice to parse xml's with large size. SAX uses some callback methods to parse
and read the xml accordingly. It uses three callback methods listed below :
startElement() : Every time a SAX parser gets a opening tag '<', it calls startElement() and
process the xml according to the code written in startElement().
endElement(): Every time a SAX parser gets a closing tag '>', it calls endElement() and process
the xml according to the code written in endElement().
character(): Every time a SAX parser gets a simple character string, it calls character() method
and the xml according to the code written in startElement().
The three methods explained above are responsible to parse the xml in SAX parser, developer
use the methods as events and can write parsing and extraction code accordingly.
XSL
o It Started with XSL
o XSL stands for EXtensible Stylesheet Language.
o The World Wide Web Consortium (W3C) started to develop XSL because there was a
need for an XML-based Stylesheet Language.
CSS = Style Sheets for HTML
HTML uses predefined tags. The meaning of, and how to display each tag is well understood.
CSS is used to add styles to HTML elements.
A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules
of a DTD:
The DOCTYPE declaration, in the example above, is a reference to an external DTD file. The
content of the file is shown in the paragraph below.
XML DTD
The purpose of a DTD is to define the structure of an XML document. It defines the structure
with a list of legal elements:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
• !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"
A doctype declaration can also be used to define special characters and character strings, used in
the 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>
XML Schema
• An XML Schema describes the structure of an XML document, just like a DTD.
• An XML document with correct syntax is called "Well Formed".
• An XML document validated against an XML Schema is both "Well Formed" and
"Valid".
XML Schema
<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>
• With XML Schema, your XML files can carry a description of its own format.
• With XML Schema, independent groups of people can agree on a standard for
interchanging data.
• With XML Schema, you can verify data.
One of the greatest strength of XML Schemas is the support for data types:
Another great strength about XML Schemas is that they are written in XML:
XML Parsers
An XML parser converts an XML document into an XML DOM object - which can then be
manipulated with a JavaScrip.
The following code fragment parses an XML document into an XML DOM object:
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
The following code fragment parses an XML string into an XML DOM object:
txt="<bookstore><book>";
txt=txt+"<title>Everyday Italian</title>";
txt=txt+"<author>Giada De Laurentiis</author>";
txt=txt+"<year>2005</year>";
txt=txt+"</book></bookstore>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(txt);
}
XSLT (eXtensible Stylesheet Language Transformations) is far more sophisticated than CSS.
XSLT can be used to transform XML into HTML, before it is displayed by a browser:
XML CODE
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy -->
<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>
XSLT
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy -->
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
<xsl:for-each select="breakfast_menu/food">
<div style="background-color:teal;color:white;padding:4px">
<span style="font-weight:bold"><xsl:value-of select="name"/></span>
- <xsl:value-of select="price"/>
</div>
<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
<xsl:value-of select="description"/>
<span style="font-style:italic">
<xsl:value-of select="calories"/> (calories per serving)
</span>
</div>
</xsl:for-each>
</body>
</html>
DOM
The Document Object Model (DOM) is an application programming interface (API) for valid
HTML and well-formed XML documents. It defines the logical structure of documents and the
way a document is accessed and manipulated. In the DOM specification, the term "document" is
used in the broad sense - increasingly, XML is being used as a way of representing many
different kinds of information that may be stored in diverse systems, and much of this would
traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as
documents, and the DOM may be used to manage this data.
With the Document Object Model, programmers can build documents, navigate their structure,
and add, modify, or delete elements and content. Anything found in an HTML or XML
document can be accessed, changed, deleted, or added using the Document Object Model, with a
few exceptions - in particular, the DOM interfaces for the XML internal and external subsets
have not yet been specified.
• The XML DOM defines a standard way for accessing and manipulating XML
documents.
• The XML DOM views an XML document as a tree-structure.
All elements can be accessed through the DOM tree. Their content (text and attributes) can be
modified or deleted, and new elements can be created. The elements, their text, and their
attributes are all known as nodes.
<table>
<tbody>
<tr>
<td>Shady Grove</td>
<td>Aeolian</td>
</tr>
<tr>
<td>Over the River, Charlie</td>
<td>Dorian</td>
</tr>
</tbody>
</table>
A graphical representation of the DOM of the example table, with whitespaces in element
content (often abusively called "ignorable whitespace") removed, is:
Figure: graphical representation of the DOM of the example table
In the DOM, documents have a logical structure which is very much like a tree; to be more
precise, which is like a "forest" or "grove", which can contain more than one tree. Each
document contains zero or one doctype nodes, one document element node, and zero or more
comments or processing instructions; the document element serves as the root of the element tree
for the document. However, the DOM does not specify that documents must be implemented as a
tree or a grove, nor does it specify how the relationships among objects be implemented. The
DOM is a logical model that may be implemented in any convenient manner. In this
specification, we use the term structure model to describe the tree-like representation of a
document. We also use the term "tree" when referring to the arrangement of those information
items which can be reached by using "tree-walking" methods; (this does not include attributes).
One important property of DOM structure models is structural isomorphism: if any two
Document Object Model implementations are used to create a representation of the same
document, they will create the same structure model, in accordance with the XML Information
Set.
The name "Document Object Model" was chosen because it is an "object model" in the
traditional object oriented design sense: documents are modeled using objects, and the model
encompasses not only the structure of a document, but also the behavior of a document and the
objects of which it is composed. In other words, the nodes in the above diagram do not represent
a data structure, they represent objects, which have functions and identity. As an object model,
the DOM identifies:
The structure of SGML documents has traditionally been represented by an abstract data model,
not by an object model. In an abstract data model, the model is centered around the data. In
object oriented programming languages, the data itself is encapsulated in objects that hide the
data, protecting it from direct external manipulation. The functions associated with these objects
determine how the objects may be manipulated, and they are part of the object model.
The DOM originated as a specification to allow JavaScript scripts and Java programs to be
portable among Web browsers. "Dynamic HTML" was the immediate ancestor of the Document
Object Model, and it was originally thought of largely in terms of browsers. However, when the
DOM Working Group was formed at W3C, it was also joined by vendors in other domains,
including HTML or XML editors and document repositories. Several of these vendors had
worked with SGML before XML was developed; as a result, the DOM has been influenced by
SGML Groves and the HyTime standard. Some of these vendors had also developed their own
object models for documents in order to provide an API for SGML/XML editors or document
repositories, and these object models have also influenced the DOM.
In the fundamental DOM interfaces, there are no objects representing entities. Numeric character
references, and references to the pre-defined entities in HTML and XML, are replaced by the
single character that makes up the entity's replacement. For example, in:
the "&" will be replaced by the character "&", and the text in the P element will form a
single continuous sequence of characters. Since numeric character references and pre-defined
entities are not recognized as such in CDATA sections, or in the SCRIPT and STYLE elements
in HTML, they are not replaced by the single character they appear to refer to. If the example
above were enclosed in a CDATA section, the "&" would not be replaced by "&"; neither
would the <p> be recognized as a start tag. The representation of general entities, both internal
and external, are defined within the extended (XML) interfaces of Document Object Model
Core.
DOM Architecture
The DOM specifications provide a set of APIs that forms the DOM API. Each DOM
specification defines one or more modules and each module is associated with one feature name.
For example, the DOM Core specification (this specification) defines two modules:
The following representation contains all DOM modules, represented using their feature names,
defined along the DOM specifications:
A DOM implementation can then en implement one (i.e. only the Core module) or more modules
depending on the host application. A Web user agent is very likely to implement the
"MouseEvents" module, while a server
server-side
side application will have no use of this module and will
probably not implement it.
1. Attributes defined in the IDL do not imply concrete objects which must have specific data
members - in the language bindings, they are translated to a pair of get()/set() functions, not to a
data member. Read-only attributes have only a get() function in the language bindings.
2. DOM applications may provide additional interfaces and objects not found in this specification
and still be considered DOM conformant.
3. Because we specify interfaces and not the actual objects that are to be created, the DOM cannot
know what constructors to call for an implementation. In general, DOM users call the createX()
methods on the Document class to create document structures, and DOM implementations create
their own internal representations of these structures in their implementations of the createX()
functions.
XForms
What Is XForms?
The purpose of an HTML form is to collect data. XForms has the same purpose.
• The XForm model - defines what the form is, what it should do, what data it contains
• The XForm user interface - defines the input fields and how they should be displayed
<model>
<instance>
<person>
<fname/>
<lname/>
</person>
</instance>
<submission id="form1" action="submit.asp" method="get"/>
</model>
In the example above, the XForms model uses an instance element to define the XML-template
for the data to be collected, and a submission element to describe how to submit the data.
XForms Namespace
If you are missing the XForms namespace in these examples, or if you don't know what a
namespace is, it will be introduced in the next chapter.
XForms is always collecting data for an XML document. The instance element in the XForms
model defines the XML document.
In the example above the "data instance" (the XML document) the form is collecting data for
looks like this:
<person>
<fname/>
<lname/>
</person>
After collecting the data, the XML document might look like this:
<person>
<fname>John</fname>
<lname>Smith</lname>
</person>
In the example above, the id="form1" identifies a form, the action="submit.asp" defines the
URL to where the form should be submitted, and the method="get" attribute defines the method
to use when submitting the form data.
The XForms user interface defines the input fields and how they should be displayed.
The user interface elements are called controls (or input controls):
The <submit> element has a submission="form1" attribute which refers to the <submission>
element in the XForms model. A submit element is usually displayed as a button.
Notice the <label> elements in the example. With XForms every input control element has a
required <label> element.
A Container
XForms is not designed to work alone. There is no such thing as an XForms document.
XForms has to run inside another XML document. It could run inside XHTML 1.0, and it will
run inside XHTML 2.0.
<xforms>
<model>
<instance>
<person>
<fname/>
<lname/>
</person>
</instance>
<submission id="form1" action="submit.asp" method="get"/>
</model>
</xforms>
First Name
Last Name
The data can be submitted as XML and could look something like this:
<person>
<fname>Hege</fname>
<lname>Refsnes</lname>
</person>
XForms Functions
The XForms function library includes the entire XPath 1.0 core function library.
Function Description
boolean-from-string(string) Returns true if the parameter string is "true" or "1" and
false if the parameter string is "false" or "0"
if(booleantest, string1, string2) Evaluates the Booleantest parameter and returns string1 if
the test is true, and string2 if the test is false
avg(node-set) Returns the average of all the nodes in the specified node-
set. The value of each node is converted to a number. If
the node-set is empty it returns NaN
seconds("P1Y2M") returns 0
seconds("P3DT10H30M1.5S") returns 297001.5
seconds("3") returns NaN
months(string) If the string parameter represents a legal xs:duration, it
returns the number specified in the months component
plus 12 * the number specified in the years component,
otherwise it returns NaN
months("P1Y2M") returns 14
months("-P19M") returns -19
XHTML
What Is XHTML?
• XHTML stands for EXtensible HyperText Markup Language
• XHTML is almost identical to HTML
• XHTML is stricter than HTML
• XHTML is HTML defined as an XML application
• XHTML is supported by all major browsers
Why XHTML?
Many pages on the internet contain "bad" HTML.
This HTML code works fine in most browsers (even if it does not follow the HTML rules):
<html>
<head>
<title>This is bad HTML</title>
<body>
<h1>Bad HTML
<p>This is a paragraph
</body>
Today's market consists of different browser technologies. Some browsers run on computers, and
some browsers run on mobile phones or other small devices. Smaller devices often lack the
resources or power to interpret "bad" markup. XML is a markup language where documents
must be marked up correctly (be "well-formed"). By combining the strengths of HTML and
XML, XHTML was developed. XHTML is HTML redesigned as XML.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title of document</title>
</head>
<body>
some content
</body>
</html>
Transformations
XSLT
What is XSLT?
XSLT uses XPath to find information in an XML document. XPath is used to navigate
through elements and attributes in XML documents.
With XSLT you can transform an XML document into HTML
XSLT - Transformation
The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or
<xsl:transform>.
Note: <xsl:stylesheet> and <xsl:transform> are completely synonymous and either can be used!
The correct way to declare an XSL style sheet according to the W3C XSLT Recommendation is:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
or:
<xsl:transform version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
To get access to the XSLT elements, attributes and features we must declare the XSLT
namespace at the top of the document.
Viewing XML Files in IE, Chrome, Firefox, Safari, and Opera: Open the XML file (click on the
link below) - The XML document will be displayed with color-coded root and child elements
(except in Safari). Often, there is a plus (+) or minus sign (-) to the left of the elements that can
be clicked to expand or collapse the element structure. Tip: To view the raw XML source,
right-click in XML file and select "View Source"!
Then you create an XSL Style Sheet ("cdcatalog.xsl") with a transformation template:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Add the XSL style sheet reference to your XML document ("cdcatalog.xml"):
XSLT Example
XLINK
There is no browser support for XLink in XML documents. However, all major browsers support
XLinks in SVG.
XLink Syntax
In HTML, the <a> element defines a hyperlink. However, this is not how it works in XML. In
XML documents, you can use whatever element names you want - therefore it is impossible for
browsers to predict what link elements will be called in XML documents.
Below is a simple example of how to use XLink to create links in an XML document:
<homepages xmlns:xlink="http://www.w3.org/1999/xlink">
<homepage xlink:type="simple" xlink:href="http://www.w3schools.com">Visit
W3Schools</homepage>
<homepage xlink:type="simple" xlink:href="http://www.w3.org">Visit W3C</homepage>
</homepages>
• To get access to the XLink features we must declare the XLink namespace. The XLink
namespace is: "http://www.w3.org/1999/xlink".
• The xlink:type and the xlink:href attributes in the <homepage> elements come from the
XLink namespace.
• The xlink:type="simple" creates a simple "HTML-like" link (means "click here to go
there").
• The xlink:href attribute specifies the URL to link to.
XLink Example
<bookstore xmlns:xlink="http://www.w3.org/1999/xlink">
</bookstore>
Example explained:
In the example above we have demonstrated simple XLinks. XLink is getting more interesting
when accessing remote locations as resources, instead of standalone pages.
If we set the value of the xlink:show attribute to "embed", the linked resource should be
processed inline within the page. When you consider that this could be another XML document
you could, for example, build a hierarchy of XML documents.
You can also specify WHEN the resource should appear, with the xlink:actuate attribute.
XLink Attribute Reference
embed
new
xlink:show replace Specifies where to open the link. Default is "replace"
other
none
simple
extended
locator
xlink:type arc Specifies the type of link
resource
title
none
XPATH
XPath (the XML Path language) is a language for finding information in an XML document.
What is XPath?
XPath is a major element in the XSLT standard. Without XPath knowledge you will not be able
to create XSLT documents.
XPath Example
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
In the table below we have listed some XPath expressions and the result of the expressions:
XQuery
What is XQuery?
• XQuery is a language for finding and extracting elements and attributes from XML
documents.
• Here is an example of a question that XQuery could solve:
• "Select all CD records with a price less than $10 from the CD collection stored in the
XML document called cd_catalog.xml"
"books.xml":
</bookstore>
Functions
XQuery uses functions to extract data from XML documents.
The doc() function is used to open the "books.xml" file:
doc("books.xml")
Path Expressions
XQuery uses path expressions to navigate through elements in an XML document.
The following path expression is used to select all the title elements in the "books.xml" file:
doc("books.xml")/bookstore/book/title
(/bookstore selects the bookstore element, /book selects all the book elements under the
bookstore element, and /title selects all the title elements under each book element)
Predicates
XQuery uses predicates to limit the extracted data from XML documents.
The following predicate is used to select all the book elements under the bookstore element that
have a price element with a value that is less than 30:
doc("books.xml")/bookstore/book[price<30]
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
How to Select Nodes From "books.xml" With FLWOR
doc("books.xml")/bookstore/book[price>30]/title
The expression above will select all the title elements under the book elements that are under the
bookstore element that have a price element with a value that is higher than 30.
The following FLWOR expression will select exactly the same as the path expression above:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
return $x/title
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
• The for clause selects all book elements under the bookstore element into a variable
called $x.
• The where clause selects only book elements with a price element with a value greater
than 30.
• The order by clause defines the sort-order. Will be sort by the title element.
• The return clause specifies what should be returned. Here it returns the title elements.
• The result of the XQuery expression above will be:
1. Heather Williamson, “ The Complete Reference XML”, Tata Mc Graw Hill, 2001.
2. http://www.w3schools.com
3. http://www.tutorialspoint.com/
SUB-CODE: SCSX1016 SUB-NAME: WEB TECHNOLOGY
Unit-III
Client-Side Scripting
Introduction
JavaScript
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)
<html>
<head>
<script type="text/javascript">
document.writeln(“Helo World!);
------
</script>
</head>
<body>
----
----
</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
ends. It is possible to have script code inside the body tag also as shown below. If it is
placed inside the body tag, the script will be executed when the content of HTML
document is displayed.
<html>
<body>
<script type="text/javascript">
............
</script>
</body>
</html>
Scripts in <head>
Scripts to be executed when they are called, or when an event is triggered, are placed in
functions. It is a good practice to put all your functions in the head section, this way they
are all in one place and do not interfere with page content.
Example
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
JavaScripts 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, or at a later event, such as when a user clicks a button. When this is the case we put
the script inside a function
Example
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
JavaScript can also be placed in external files. External JavaScript files often contain
code to be used on several different web pages. External JavaScript files have the file
extension .js. External script cannot contain the <script></script> tags. To use an
external script, point to the .js file in the "src" attribute of the <script> tag:
Example
<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>
Advantages
Javascript is executed on the client side
Javascript is a relatively easy language
Javascript is relatively fast to the end user
Extended functionality to web pages
Disadvantages
Security Issues
Javascript rendering varies
Data Types
JavaScript variables can hold many data types: numbers, strings, arrays, objects and
more:
var length = 10; // Number
var lastName = "John"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = {firstName:"John", lastName:"Doe"}; // Object
Booleans:
var x = true;
var y = false;
Arrays: Example
Objects: Example
JavaScript Variables
JavaScript variables are used to hold values or expressions. A variable can have a short
name, like x, or a more descriptive name, like carname. Rules for JavaScript variable
names:
Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter or the underscore character
var x;
var carname;
After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will hold the value 5, and
carname will hold the value Volvo.
If you assign values to variables that have not yet been declared, the variables will
automatically be declared. These statements:
x=5;
carname="Volvo";
var x=5;
var carname="Volvo";
If you redeclare a JavaScript variable, it will not lose its original value.
var x=5;
var x;
After the execution of the statements above, the variable x will still have the value of 5.
The value of x is not reset (or cleared) when you redeclare it.
If you declare a variable within a function, the variable can only be accessed within that
function. When you exit the function, the variable is destroyed. These variables are called
local variables. You can have local variables with the same name in different functions,
because each is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it.
The lifetime of these variables starts when they are declared, and ends when the page is
closed.
Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Assignment operators are used to assign values to JavaScript variables. Given that x=10
and y=5, the table below explains the assignment operators:
Logical Operators
Logical operators are used to determine the logic between variables or values. Given that
x=6 and y=3, the table below explains the logical operators:
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on
some condition.
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";
Control Statements
Very often when you write code, you want to perform different actions for different
decisions. You can use conditional statements in your code to do this.
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a
JavaScript error!
Example
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>
If...else Statement
Use the if....else statement to execute some code if a condition is true and another code if
the condition is not true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();
var time = d.getHours();
Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}
Example
script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Alert Box
An alert box is often used if you want to make sure information comes through to the
user. When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
alert("sometext");
Example
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box" />
</body>
</html>
Confirm Box
A confirm box is often used if you want the user to verify or accept something. When a
confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If
the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Syntax
confirm("sometext");
Example
<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()" value="Show confirm box" />
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to
proceed after entering an input value. If the user clicks "OK" the box returns the input
value. If the user clicks "Cancel" the box returns null.
Syntax
prompt("sometext","defaultvalue");
Example
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
</body>
</html>
JavaScript Loops
Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal lines in a script we can use loops to
perform a task like this.
The for loop is used when you know in advance how many times the script should run.
Syntax
for (variable=startvalue;variable<=endvalue;variable=variable+increment)
{
code to be executed
}
Example
The example below defines a loop that starts with i=0. The loop will continue to run as
long as i is less than, or equal to 5. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any
comparing statement.
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
Loops execute a block of code a specified number of times, or while a specified condition
is true.
The while loop loops through a block of code while a specified condition is true.
Syntax
while (variable<=endvalue)
{
code to be executed
}
Example
The example below defines a loop that starts with i=0. The loop will continue to run as
long as i is less than, or equal to 5. i will increase by 1 each time the loop runs:
Example
<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>
The do...while loop is a variant of the while loop. This loop will execute the block of
code ONCE, and then it will repeat the loop as long as the specified condition is true.
Syntax
do
{
code to be executed
}
while (variable<=endvalue);
Example
The example below uses a do...while loop. The do...while loop will always be executed at
least once, even if the condition is false, because the statements are executed before the
condition is tested:
Example
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>
The break statement will break the loop and continue executing the code that follows
after the loop (if any).
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
The continue statement will break the current loop and continue with the next value.
Example
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>
The for...in statement loops through the elements of an array or through the properties of
an object.
Syntax
for (variable in object)
{
code to be executed
}
Note: The code in the body of the for...in loop is executed once for each
element/property.
Note: The variable argument can be a named variable, an array element, or a property of
an object.
Example
Example
<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>
The return statement is used to specify the value that is returned from the function. So,
functions that are going to return a value must use the return statement. The example
below returns the product of two numbers (a and b):
Example
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>
Functions
A function will be executed by an event or by a call to the function.
JavaScript Functions
To keep the browser from executing a script when the page loads, you can put your script
into a function. A function contains code that will be executed by an event or by a call to
the function. You may call a function from anywhere within a page (or even from other
pages if the function is embedded in an external .js file). Functions can be defined both in
the <head> and in the <body> section of a document. However, to assure that a function
is read/loaded by the browser before it is called, it could be wise to put functions in the
<head> section.
Syntax
function functionname(var1,var2,...,varX)
{
some code
}
The parameters var1, var2, etc. are variables or values passed into the function. The { and
the } defines the start and end of the function. The word function must be written in
lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a
function with the exact same capitals as in the function name
Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>
JavaScript Events
Events are actions that can be detected by JavaScript.
Event Association
Events are associated with HTML tags. The definitions of the events described below are
as follows:
Event handler Applies to: Triggered when:
onAbort Image The loading of the image is
cancelled.
onBlur Button, Checkbox, Password, The object in question loses
Radio, Reset, Select, Submit, focus (e.g. by clicking outside it
Text, TextArea, Window or pressing the TAB key).
onChange Select, Text, TextArea The data in the form element is
changed by the user.
onClick Button, Checkbox, Link, Radio, The object is clicked on.
Reset, Submit
onDblClick Document, Link The object is double-clicked on.
onError Image A JavaScript error occurs.
onFocus Button, Checkbox, Password, The object in question gains
Radio, Reset, Select, Submit, focus (e.g. by clicking on it or
Text, TextArea pressing the TAB key).
onKeyDown Image, Link, TextArea The user presses a key.
onKeyPress Image, Link, TextArea The user presses or holds down
a key.
onKeyUp Image, Link, TextArea The user releases a key.
onLoad Image, Window The whole page has finished
loading.
onMouseDown Button, Link The user presses a mouse
button.
onMouseMove None The user moves the mouse.
onMouseOut Image, Link The user moves the mouse away
from the object.
onMouseOver Image, Link The user moves the mouse over
the object.
onMouseUp Button, Link The user releases a mouse
button.
onMove Window The user moves the browser
window or frame.
onReset Form The user clicks the form's Reset
button.
onResize Window The user resizes the browser
window or frame.
onSelect Text, Textarea The user selects text within the
field.
onSubmit Form The user clicks the form's
Submit button.
onUnload Window The user leaves the page.
Events
By using JavaScript, we have the ability to create dynamic web pages. Events are actions
that can be detected by JavaScript. Every element on a web page has certain events which
can trigger a JavaScript. For example, we can use the onClick event of a button element
to indicate that a function will run when a user clicks on the button. We define the events
in the HTML tags.
Examples of events:
A mouse click
A web page or an image loading
Mousing over a hot spot on the web page
Selecting an input field in an HTML form
Submitting an HTML form
A keystroke
Events are normally used in combination with functions, and the function will not be
executed before the event occurs.
Date
Math
String, Number, Boolean
RegExp
window (Global Obejct)
Of the above objects, the most widely used one is the String object. Objects are nothing
but special kind of data. Each object has Properties and Methods associated with it.
property is the value that is tagged to the object. For example let us consider one of the
properties associated with the most popularly used String object - the length property.
Length property of the string object returns the length of the string that is in other words
the number of characters present in the string.
General syntax of using the length property of the string object is as below:
variablename.length
Here variablename is the name of the variable to which the string is assigned and length
is the keyword.
<html>
<body>
<script type="text/javascript">
var exf="Welcome"
document.write(exf.length)
</script>
</body>
</html>
Method of an Object:
Method of an object refers to the actions than can be performed on the object. For
example in String Object there are several methods available in JavaScript.
<html>
<body>
<script type="text/javascript">
var exf="Welcome"
document.write(exf.toUpperCase())
</script>
</body>
</html>
WELCOME
In the above script since the method toUpperCase is applied to the string object exf which
has value initialized as Welcome all letters get converted as upper case and hence the
output is as above.
The main purpose of String Object in JavaScript is for storing text. General method of
using String Object is to declare a variable and assign a string, in other words a text to the
variable.
var exf="Welcome"
Method Description
charAt() Returns the character at the specified index
charCodeAt() Returns the Unicode of the character at the specified index
concat() Joins two or more strings, and returns a copy of the joined strings
Returns the position of the first found occurrence of a specified value in
indexOf()
a string
Returns the position of the last found occurrence of a specified value in
lastIndexOf()
a string
Searches for a match between a regular expression and a string, and
match()
returns the matches
Searches for a match between a substring (or regular expression) and a
replace()
string, and replaces the matched substring with a new substring
Searches for a match between a regular expression and a string, and
search()
returns the position of the match
slice() Extracts a part of a string and returns a new string
split() Splits a string into an array of substrings
Extracts the characters from a string, beginning at a specified start
substr()
position, and through the specified number of character
substring() Extracts the characters from a string, between two specified indices
toLowerCase() Converts a string to lowercase letters
toUpperCase() Converts a string to uppercase letters
valueOf() Returns the primitive value of a String object
Date object of Java Script is used to work with date and times. General syntax for
defining Date object in Java Script is as follows:
var variablename=new Date( )
In the above new is a keyword which creates an instance of object and Date() defines
variablename as Date Object.
For example:
In the above example, variable exf is defined as Date object which has current date and
time as its initial value.
setSeconds()- Sets the seconds for a specified date according to local time.
setMinutes() - Sets the minutes for a specified date according to local time.
setHours() - Sets the hours for a specified date according to local time.
setDate() - Sets the day of the month for a specified date according to local time.
setMonth() - Sets the month for a specified date according to local time.
setYear() - Sets the year (deprecated) for a specified date according to local time.
setFullYear() - Sets the full year for a specified date according to local time.
toString() - Returns a string representing the specified Date object.
getSeconds() - Returns seconds in the specified date according to local time.
getMinutes() - Returns minutes in the specified date according to local time.
getHours() - Returns hour in the specified date according to local time.
getDay() - Returns day of the week for a specified date according to local time
getDate() - Returns day of the month for a specified date according to local time.
getMonth() - Returns month in the specified date according to local time.
getYear() - Returns year (deprecated) in the specified date according to local time.
getFullYear() - Returns year of the specified date according to local time.
exf.setFullYear(2020,0,20)
As we have seen setFullYear() is used for Setting the full year for a specified date
according to local time. In the above example the Date object exf is set to the specific
date and year 20th January 2020
</script>
</body>
</html>
11/15/2006
JavaScript Math object is used to perform mathematical tasks. But unlike the String and
the Date object which requires defining the object, Math object need not be defined.
Math object in JavaScript has two main attributes:
Properties
Methods
The JavaScript has eight mathematical values and this can be accessed by using the Math
Object. The eight mathematical values are:
E
PI
square root of 2 denoted as SQRT2
square root of 1/2 denoted as SQRT1_2
natural log of 2 denoted as LN2
natural log of 10 denoted as LN10
base-2 log of E denoted as LOG2E
base-10 log of E denoted as LOG10E
The way of accessing these values in JavaScript is by using the word Math before these
values namely as
Math.E
Math.LOG10E and so on
There are numerous methods available in JavaScript for Math Object. Some of them are
mentioned below namely:
<html>
<body>
<script type="text/javascript">
document.write(Math.round(5.8))
</script>
</body>
</html>
This is because the round() method rounds the number given in argument namely here
5.8 to the nearest integer. It rounds .5 up which gives 6.
Another example for using Math Object in JavaScript.
<html>
<body>
<script type="text/javascript">
document.write(Math.max(8,9) + "<br />")
document.write(Math.max(-5,3) + "<br />")
document.write(Math.max(-2,-7) + "<br />")
</script>
</body>
</html>
9
3
-2
The above example uses the max() method of the Math object which returns the largest of
the two numbers given in arguments of the max method.
The Boolean object is used to convert a non-Boolean value to a Boolean value (true or
false).
Method Description
toString() Converts a Boolean value to a string, and returns the result
valueOf() Returns the primitive value of a Boolean object
Number Object
Method Description
toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
toPrecision(x) Formats a number to x length
toString() Converts a Number object to a string
valueOf() Returns the primitive value of a Number object
String Object
or more simply:
Window Object
If a document contain frames (<frame> or <iframe> tags), the browser creates one
window object for the HTML document, and one additional window object for each
frame.
Method Description
alert() Displays an alert box with a message and an OK button
blur() Removes focus from the current window
clearInterval() Clears a timer set with setInterval()
clearTimeout() Clears a timer set with setTimeout()
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
createPopup() Creates a pop-up window
focus() Sets focus to the current window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window to the specified width and height
scroll()
scrollBy() Scrolls the content by the specified number of pixels
scrollTo() Scrolls the content to the specified coordinates
Calls a function or evaluates an expression at specified intervals (in
setInterval()
milliseconds)
Calls a function or evaluates an expression after a specified number of
setTimeout()
milliseconds
Regular expressions are used to do sophisticated pattern matching, which can often be
helpful in form validation. For example, a regular expression can be used to check
whether an email address entered into a form field is syntactically correct. JavaScript
supports Perl-compatible regular expressions.
Assuming you know the regular expression pattern you are going to use, there is no real
difference between the two; however, if you don't know the pattern ahead of time (e.g,
you're retrieving it from a form), it can be easier to use the RegExp() constructor.
The regular expression method in JavaScript has two main methods for testing strings:
test() and exec().
The exec() Method
The exec() method takes one argument, a string, and checks whether that string contains
one or more matches of the pattern specified by the regular expression. If one or more
matches are found, the method returns a result array with the starting points of the
matches. If no match is found, the method returns null.
The test() method also takes one argument, a string, and checks whether that string
contains a match of the pattern specified by the regular expression. It returns true if it
does contain a match and false if it does not. This method is very useful in form
validation scripts. The code sample below shows how it can be used for checking a social
security number. Don't worry about the syntax of the regular expression itself. We'll
cover that shortly.
function f1(ssn)
{
if (exp.test(ssn)) { alert("VALID SSN"); }
else { alert("INVALID SSN"); }
}
</script>
</head>
<body>
<form name=”f1”>
<input type="text" name="t1" />
<input type="button" value="Check" onclick="f1(this.f1.t1.value);" />
</form>
</body>
</html>
Code Explanation
1. First, a variable containing a regular expression object for a social security number
is declared.
2. Next, a function called f1() is created. This function takes one argument: ssn,
which is a string. The function then tests to see if the string matches the regular
expression pattern by passing it to the regular expression object's test() method. If it does
match, the function alerts "VALID SSN". Otherwise, it alerts "INVALID SSN".
function f1(ssn)
{
if (exp.test(ssn)) { alert("VALID SSN"); }
else { alert("INVALID SSN"); }
}
3. A form in the body of the page provides a text field for inserting a social security
number and a button that passes the user-entered social security number to the f1()
function.
<form >
<input type="text" name="t1" />
<input type="button" value="Check" onclick="checkSsn(this.form.ssn.value);"
/>
</form>
Flags
Flags appearing after the end slash modify how a regular expression works.
* The i flag makes a regular expression case insensitive. For example, /aeiou/i matches
all lowercase and uppercase vowels.
* The g flag specifies a global match, meaning that all matches of the specified pattern
should be returned.
A caret (^) at the beginning of a regular expression indicates that the string being
searched must start with this pattern.
A dollar sign ($) at the end of a regular expression indicates that the string being searched
must end with this pattern.
Number of Occurrences : ? + * {}
The following symbols affect the number of occurrences of the preceding character: ?, +,
*, and {}.
A questionmark (?) indicates that the preceding character should appear zero or one times
in the pattern.
* The pattern foo? can be found in "food" and "fod", but not "faod".
A plus sign (+) indicates that the preceding character should appear one or more times in
the pattern.
* The pattern fo+ can be found in "fod", "food" and "foood", but not "fd".
A asterisk (*) indicates that the preceding character should appear zero or more times in
the pattern.
Curly brackets with one parameter ( {n} ) indicate that the preceding character should
appear exactly n times in the pattern.
* The pattern fo{3}d can be found in "foood" , but not "food" or "fooood".
Curly brackets with two parameters ( {n1,n2} ) indicate that the preceding character
should appear between n1 and n2 times in the pattern.
* The pattern fo{2,4}d can be found in "food","foood" and "fooood", but not "fod" or
"foooood".
Curly brackets with one parameter and an empty second paramenter ( {n,} ) indicate that
the preceding character should appear at least n times in the pattern.
* The pattern fo{2,}d can be found in "food" and "foooood", but not "fod".
Common Characters: . \d \D \w \W \s \S
* The pattern fo.d can be found in "food", "foad", "fo9d", and "fo*d".
* The pattern fo\dd can be found in "fo1d", "fo4d" and "fo0d", but not in "food" or
"fodd".
* The pattern fo\Dd can be found in "food" and "foad", but not in "fo4d".
Backslash-w ( \w ) represents any word character (letters, digits, and the underscore (_) ).
* The pattern fo\wd can be found in "food", "fo_d" and "fo4d", but not in "fo*d".
Backslash-s ( \s) represents any whitespace character (e.g, space, tab, newline, etc.).
* The pattern fo\sd can be found in "fo d", but not in "food".
* The pattern fo\Sd can be found in "fo*d", "food" and "fo4d", but not in "fo d".
Grouping: []
* The pattern f[aeiou]d can be found in "fad" and "fed", but not in "food", "faed" or
"fd".
* The pattern f[aeiou]{2}d can be found in "faed" and "feod", but not in "fod", "fed" or
"fd".
Negation : ^
When used after the first character of the regular expression, the caret ( ^ ) is used for
negation.
* The pattern f[^aeiou]d can be found in "fqd" and "f4d", but not in "fad" or "fed".
Subpatterns: ()
* The pattern f(oo)?d can be found in "food" and "fd", but not in "fod".
Alternatives: |
* The pattern foo$|^bar can be found in "foo" and "bar", but not "foobar".
Escape Character : \
* The pattern fo\.d can be found in "fo.d", but not in "food" or "fo4d".
A more practical example has to do matching the delimiter in social security numbers.
Examine the following regular expression.
Within the caret (^) and dollar sign ($), which are used to specify the beginning and end
of the pattern, there are three sequences of digits, optionally separated by a hyphen or a
space. This pattern will be matched in all of following strings (and more).
* 123-45-6789
* 123 45 6789
* 123456789
* 123-45 6789
* 123 45-6789
* 123-456789
The last three strings are not ideal, but they do match the pattern. Back references can be
used to make sure that the second delimiter matches the first delimiter. The regular
expression would look like this.
^\d{3}([\- ]?)\d{2}\1\d{4}$
The \1 refers back to the first subpattern. Only the first three strings listed above match
this regular expression.
Regular expressions make it easy to create powerful form validation functions. Take a
look at the following example.
Code Sample: Login.html
<html>
<head>
<script type="text/javascript">
function validate()
{
var email = form.Email.value;
var password = form.Password.value;
var errors = [];
if (!RE_EMAIL.test(email)) { alert( "You must enter a valid email address."); }
if (!RE_PASSWORD.test(password)) { alert( "You must enter a valid password."); }
}
</script>
</head>
<body>
<form name=”form”>
Email: <input type="text" name="Email" />
Password: <input type="password" name="Password” />
*Password must be between 6 and 10 characters and can only contain letters and digits.
Code Explanation
This code starts by defining regular expressions for an email address and a password.
Let's break each one down.
1. The caret (^) says to start at the beginning. This prevents the user from entering
invalid characters at the beginning of the email address.
2. (\w+[\-\.])* allows for a sequence of word characters followed by a dot or a dash.
The * indicates that the pattern can be repeated zero or more times. Successful patterns
include "ndunn.", "ndunn-", "nat.s.", and "nat-s-".
3. \w+ allows for one or more word characters.
4. @ allows for a single @ symbol.
5. (\w+\.)+ allows for a sequence of word characters followed by a dot. The +
indicates that the pattern can be repeated one or more times. This is the domain name
without the last portion (e.g, without the "com" or "gov").
6. [A-Za-z]+ allows for one or more letters. This is the "com" or "gov" portion of the
email address.
7. The dollar sign ($) says to end here. This prevents the user from entering invalid
characters at the end of the email address.
1. The caret (^) says to start at the beginning. This prevents the user from entering
invalid characters at the beginning of the password.
2. [A-Za-z\d]{6,8} allows for a six- to eight-character sequence of letters and digits.
3. The dollar sign ($) says to end here. This prevents the user from entering invalid
characters at the end of the password.
Exercises:
1. Construct a reg exp to validate a text field which should be used to accept only a
string composed by 3 letters, one space, 6 numbers, a "-" and a number such as
MJHJ 123456-6
Ans: /^[A-Za-z]{4}\s\d{6}\-\d{1}$/
Document Object
Each HTML document loaded into a browser window becomes a Document object. The
Document object provides access to all HTML elements in a page, from within a script.
Method Description
Closes the output stream previously opened with
close()
document.open()
getElementById() Accesses the first element with the specified id
getElementsByName() Accesses all elements with a specified name
getElementsByTagName() Accesses all elements with a specified tagname
open() Opens an output stream to collect the output from
document.write() or document.writeln()
Writes HTML expressions or JavaScript code to a
write()
document
Same as write(), but adds a newline character after each
writeln()
statement
Arrays
It describes the JavaScript array object including parameters, properties, and methods.
Parameters
* arrayLength
* elementN - Array element list of values
Properties
* index
* input
* length - The quantity of elements in the object.
* prototype - For creating more properties.
Methods
* chop() - Used to truncate the last character of a all strings that are part of an array.
This method is not defined so it must be written and included in your code.
Look out
Duck
* concat()
* grep(searchstring) - Takes an array and returns those array element strings that
contain matching strings. This method is not defined so it must be written and included in
your code.
lines, finish
* join(delimiter) - Puts all elements in the array into a string, separating each element
with the specified delimiter.
limit;lines;finish;complete;In;Out
* pop() - Pops the last string off the array and returns it. This method is not defined so
it must be written and included in your code.
Out
* push(strings) - Strings are placed at the end of the array. This method is not defined
so it must be written and included in your code.
* shift() - Decreases array element size by one by shifting the first element off the
array and returning it. This method is not defined so it must be written and included in
your code.
Out
* sort() - Sorts the array elements in dictionary order or using a compare function
passed to the method.
In,Out,complete,finish,limit,lines
* splice() - It is used to take elements out of an array and replace them with those
specified. In the below example the element starting at element 3 is removed, two of
them are removed and replaced with the specified strings. The value returned are those
values that are replaced. This method is not defined so it must be written and included in
your code.
complete, In
An object is a set of variables, functions, etc., that are in some way related. They are
grouped together and given a name
Properties
Methods
Events
Window Object
Window is the fundamental object in the browser. It represents the browser window in
which the document appears
status The contents of the status bar (at the bottom of the browser
window). For example:
location The location and URL of the document currently loaded into the
window (as displayed in the location bar). For example:
alert(window.location);
will display an alert containing the location and URL of this
document.
Click here to see this line of code in operation.
length The number of frames (if any) into which the current window is
divided. For example:
alert(window.length);
will place a string representing the parent window into the variable
parentWindow, then use it to report the number of frames (if any)
in the parent window.
top The top-level window, of which all other windows are sub-
windows. For example:
alert() Displays an 'alert' dialog box, containing text entered by the page
designer, and an 'OK' button. For example:
alert("Hi, there!");
prompt() Displays a message, a box into which the user can type text, an
'OK' button, and a 'Cancel' button. Returns a text string. The
syntax is:
prompt(message_string, default_response_string)
For example:
open() Opens a new browser window and loads either an existing page or
a new document into it. The syntax is:
For example:
will open a new window 100 pixels high by 200 pixels wide. An
HTML document called '05_JS4nw.html' will be loaded into this
window.
Note that the variable newWindow is not preceded by the word var.
This is because newWindow is a global variable which was
declared at the start of the script. The reason for this is explained
below.
window_name.close()
For example:
newWindow.close()
onLoad() Message sent each time a document is loaded into a window. Can
be used to trigger actions (e.g., calling a function). Usually placed
within the <body> tag, for example:
<body onLoad="displayWelcome()">
<body onUnload="displayFarewell()">
The window history can be used to go back and forth on the list of visited pages. For
example,
history.back(); // reloads the previous page
history.forward(); // reloads the next page
history.go(-3); // goes back three pages
For a frames page, a page with a frameset element, each frame is also represented by its
own window object. These objects are kept on the frames array. Thus give the window
objects for the frames using their name or id attributes.
frames["top"]
frames["left"]
frames["right"]
Forms
Form validation
Form validation is the process of checking that a form has been filled in correctly before
it is processed. For example, if your form has a box for the user to type their email
address, you might want your form handler to check that they've filled in their address
before you deal with the rest of the form. Form validation is usually done with JavaScript
embedded in the Web page
The above program will accept the input in any one of the following valid form
[email protected] [email protected] [email protected]
The above program will accept the input only in any one of the following valid form
25 5 101
Validate a checkbox
Validate form selection
Host Objects
JavaScript supports three types of objects: native, host, and user-defined. Native objects
are objects supplied by the JavaScript language. String, Boolean, Math, and Number are
examples of native objects.
Host objects are JavaScript objects that provide special access to the host environment.
They are provided by the browser for the purpose of interaction with the loaded
document. In a browser environment,
1. window
2. document
objects are host objects. Several other browser host objects are informal, de facto
standards. They are: alert, prompt, confirm.
AJAX
What is AJAX?
AJAX Example
HTML page
<!DOCTYPE html>
<html>
<body>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
XMLHttpRequest (XHR)
Create Object
All modern browsers (Chrome, IE7+, Firefox, Safari, and Opera) have a built-in
XMLHttpRequest object.
Old versions of Internet Explorer (IE5 and IE6) use an ActiveX Object:
variable = new ActiveXObject("Microsoft.XMLHTTP");
To handle all browsers, including IE5 and IE6, check if the browser supports the
XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an
ActiveXObject:
Example
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
Request
To send a request to a server, we use the open() and send() methods of the
XMLHttpRequest object:
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
GET Requests
In the example above, you may get a cached result. To avoid this, add a unique ID to the
URL:
Example
xhttp.open("GET", "demo_get.asp?t=" + Math.random(), true);
xhttp.send();
POST Requests
Example
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
To POST data like an HTML form, add an HTTP header with setRequestHeader().
Specify the data you want to send in the send() method:
Example
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
Response
Server Response
To get the response from a server, use the responseText or responseXML property of the
XMLHttpRequest object.
Property Description
responseText get the response data as a string
responseXML get the response data as XML data
If the response from the server is not XML, use the responseText property.
The responseText property returns the response as a string, and you can use it
accordingly:
Example
document.getElementById("demo").innerHTML = xhttp.responseText;
If the response from the server is XML, and you want to parse it as an XML object, use
the responseXML property:
Example
xmlDoc = xhttp.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;
Ready State
jQuery
jQuery is a fast, small, and feature-rich JavaScript library.
It makes things like HTML document traversal and manipulation, event handling,
animation, and Ajax much simpler with an easy-to-use API that works across a
multitude of browsers.
With a combination of versatility and extensibility, jQuery has changed the way
that millions of people write JavaScript.
Features:
jQuery includes the following features:
DOM element selections using the multi-browser open source selector engine
Sizzle, a spin-off of the jQuery project.
DOM manipulation based on CSS selectors that uses elements' names and
attributes, such as id and class, as criteria to select nodes in the DOM
Events
Effects and animations
AJAX
Deferred and Promise objects to control asynchronous processing
Utilities, such as feature detection
Compatibility methods that are natively available in modern browsers, but need
fall backs for older ones, such as inArray() and each()
Multi-browser support
Example:
<html>
<head>
<title>The jQuery Example</title>
<script type="text/javascript" src="/jquery/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
document.write("Hello, World!");
});
</script>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
References:
Unit-IV
Server-Side Scripting
Introduction
Client-side Environment
The client-side environment used to run scripts is usually a browser. The processing takes place
on the end users computer. The source code is transferred from the web server to the users
computer over the internet and run directly in the browser.
The scripting language needs to be enabled on the client computer. Sometimes if a user is
conscious of security risks they may switch the scripting facility off. When this is the case a
message usually pops up to alert the user when script is attempting to run.
Server-side Environment
The server-side environment that runs a scripting language is a web server. A user's request is
fulfilled by running a script directly on the web server to generate dynamic HTML pages. This
HTML is then sent to the client browser. It is usually used to provide interactive web sites that
interface to databases or other data stores on the server.
This is different from client-side scripting where scripts are run by the viewing web browser,
usually in JavaScript. The primary advantage to server-side scripting is the ability to highly
customize the response based on the user's requirements, access rights, or queries into data
stores.
ASP
What is ASP?
• ASP stands for Active Server Pages
• ASP is a Microsoft Technology
• ASP is a program that runs inside Interet Information Services (IIS)
• IIS comes as a free component with Windows 2000
• IIS is also a part of the Windows NT 4.0 Option Pack
• The Option Pack can be downloaded from Microsoft
• Personal Web Server (PWS) is a smaller - but fully functional - version of IIS
• PWS can be found on your Windows 95/98 CD
• Active Server Page was developed by Microsoft and it is a popular technology for
developing dynamic web sites.
• Must run on an active server pages server
• IIS, PWS, …
• The latest version is ASP.NET
• Request Object
• Response Object
• Server Object
• Session Object
• Application Object
Request Object
Definition: The request object gets the information from client browser while HTTP request
Syntax: Request.[collection|property|method] (variable).
• Collections
– ClientCertificate
• To get certification fields from client side
– Cookies
• To get the values from cookies during HTTP request
– Form
• To get the values from form elements during HTTP request
– QueryString
• To get the values of variables during HTTP request
– Server Variables
• To get the values of predetermined environment variables
• Properties
– Read-only
• Size of the content being sent by client in terms of bytes.
• Methods
– Binary Read
• It reads the information sent by client while POST request
• In case collection/property/method is not mentioned, directly variable name is used to
fetch the data, ASP engine follows the below mentioned hierarchy to search the variable
1. QueryString
2. Form
3. Cookies
4. ClientCertificate
5. ServerVariables
Response Object
Definition: This object is used to send the information to client from server.
Syntax:
Response.[collection|method|property]
• Collections
– Cookies
• The response object supports only cookies as collection to set cookie
values.
• Properties
– Buffer
• to indicate whether page output is buffered
– CacheControl
• Determine whether proxy servers are able to cache the output generated by
ASP
– Charset
• Appends the name of the character set to content-type header
– ContentType
• Specifies the HTTP content type for the response
– ExpiresAbsolute
• specifies the date and time when page should expire on client side
– IsClientConnected
• Indicates whether the client is connected to server or not
– Pics
• Platform for Internet Content Selection
• It is used to rate the content in a website
• This property appends a value to PICS label response header
– Status
• Value of status line returned by the server
– Flush
• Sends buffered output immediately
– Redirect
• Sends a redirect message to browser
– Write
• Writes the content to HTTP output
Server Object
Definition: it provides access to methods and properties on the server
Syntax: Server.property|method
• Properties
– ScriptTimeout
• Amount of time that a script can run before it times out
• Methods
– Execute
• Used to run another asp file within asp file
– CreateObject
• Creates an instance of server component
– HTMLEncode
• Applies HTML encoding to string
– MapPath
• Maps the virtual path into physical path
– URLEncode
• Applies URL encoding rules to string
Session Object
Definition: it is used to store the temporary info for user. Data available in sessions remain
available within the website while visiting one page to another page. Sessions are
automatically created whenever user visits the website
Syntax:
Session.[collection|method|property]
• Collections
– Contents
• Contains the data which are added by script
– StaticObjects
• Contains the object created with <object> tag and given session scope
• Properties
– CodePage
• Codepage is used for symbol mapping
– LCID
• The locale identifer
– SessionID
• Returns the session identification of user
– Timeout
Timeout period for session
• Methods
– Abandon
• This method destroys a session object and releases its resources
Application Object
Definition: This object can store info regarding the application which remains constant
throughout the whole time server is running
Syntax: Application.method
• Collections
– Content
• Contains all the items that have been added by script
– StaticObjects
• Contains all the data for objects created by <OBJECT> tag
– Lock
• This method stops other clients from modifying application data
– Unlock
• This method allows the client for modification of application data
File Access
File Object
Methods
Copy Copies a specified file from one location to another
Delete Deletes a specified file
Move Moves a specified file from one location to another
OpenAsTextStream Opens a specified file and returns a TextStream object to access
the file
• The ASP AdRotator component creates an AdRotator object that displays a different
image each time a user enters or refreshes a page.
• A text file includes information about the images.
Syntax
<%
set
adrotator=server.createobject("MSWC.AdRotator")
adrotator.GetAdvertisement("textfile.txt")
%>
ASP AdRotator Properties
Border :
• Specifies the size of the borders around the advertisement
<%
set adrot=Server.CreateObject("MSWC.AdRotator")
adrot.Border="2"
Response.Write(adrot.GetAdvertisement("ads.txt"))
%>
Clickable:
• Specifies whether the advertisement is a hyperlink
<%
set adrot=Server.CreateObject("MSWC.AdRotator")
adrot.Clickable=false
Response.Write(adrot.GetAdvertisement("ads.txt"))
%>
Target:
• Frame Name of the frame to display the advertisement
<%
set adrot=Server.CreateObject("MSWC.AdRotator")
adrot.TargetFrame="target='_blank'"
Response.Write(adrot.GetAdvertisement("ads.txt"))
%>
GetAdvertisement
• Returns HTML that displays the advertisement in the page
• <%
set adrot=Server.CreateObject("MSWC.AdRotator")
Response.Write(adrot.GetAdvertisement("ads.txt"))
%>
• The ASP Content Linking component is used to create a quick and easy navigation
system!
• The Content Linking component returns a Nextlink object that is used to hold a list of
Web pages to be navigated.
Syntax
<%
Set nl=Server.CreateObject("MSWC.NextLink")
%>
Example
• First we create a text file - "links.txt":
• asp_intro.asp ASP Intro
asp_syntax.asp ASP Syntax
asp_variables.asp ASP Variables
asp_procedures.asp ASP Procedures
GetListCount
• Returns the number of items listed in the Content Linking List file
• <%
dim nl,c
Set nl=Server.CreateObject("MSWC.NextLink")
c=nl.GetListCount("links.txt")
Response.Write("There are ")
Response.Write(c)
Response.Write(" items in the list")
%>Output:
• There are 4 items in the list
GetListIndex
• Returns the index number of the current item in the Content Linking List file. The index
number of the first item is 1. 0 is returned if the current page is not in the Content Linking
List file
• <%
dim nl,c
Set nl=Server.CreateObject("MSWC.NextLink")
c=nl.GetListIndex("links.txt")
Response.Write("Item number ")
Response.Write(c)
%>
• Output:
• Item number 3
GetNextDescription
• Returns the text description of the next item listed in the Content Linking List file. If the
current page is not found in the list file it returns the text description of the last page on
the list
• <%
dim nl,c
Set nl=Server.CreateObject("MSWC.NextLink")
c=nl.GetNextDescription("links.txt")
Response.Write("Next ")
Response.Write("description is: ")
Response.Write(c)
%>
• Next description is: ASP Variables
GetNextURL
• Returns the URL of the next item listed in the Content Linking List file. If the current
page is not found in the list file it returns the URL of the last page on the list
• <%
dim nl,c
Set nl=Server.CreateObject("MSWC.NextLink")
c=nl.GetNextURL("links.txt")
Response.Write("Next ")
Response.Write("URL is: ")
Response.Write(c)
%>
• Next URL is: asp_variables.asp
GetNextURL
• Returns the URL of the next item listed in the Content Linking List file. If the current
page is not found in the list file it returns the URL of the last page on the list
• <%
dim nl,c
Set nl=Server.CreateObject("MSWC.NextLink")
c=nl.GetNextURL("links.txt")
Response.Write("Next ")
Response.Write("URL is: ")
Response.Write(c)
%>
• Next URL is: asp_variables.asp
GetNthURL
• Returns the URL of the Nth page listed in the Content Linking List file
• <%
dim nl,c
Set nl=Server.CreateObject("MSWC.NextLink")
c=nl.GetNthURL("links.txt",3)
Response.Write("Third ")
Response.Write("URL is: ")
Response.Write(c)
%>
• Third URL is: asp_variables.asp
GetPrevious
• Description Returns the text description of the previous item listed in the Content Linking
List file. If the current page is not found in the list file it returns the text description of the
first page on the list
• <%
dim nl,c
Set nl=Server.CreateObject("MSWC.NextLink")
c=nl.GetPreviousDescription("links.txt")
Response.Write("Previous ")
Response.Write("description is: ")
Response.Write(c)
%>
Previous description is: ASP Variables
GetPreviousURL
• Returns the URL of the previous item listed in the Content Linking List file. If the current
page is not found in the list file it returns the URL of the first page on the list
• <%
dim nl,c
Set nl=Server.CreateObject("MSWC.NextLink")
c=nl.GetPreviousURL("links.txt")
Response.Write("Previous ")
Response.Write("URL is: ")
Response.Write(c)
%>
• Previous URL is: asp_variables.asp
• The ASP Content Rotator component creates a ContentRotator object that displays a
different content string each time a visitor enters or refreshes a page.
• A text file, called the Content Schedule File, includes the information about the content
strings.
• The content strings can contain HTML tags so you can display any type of content that
HTML can represent: text, images, colors, or hyperlinks.
• Syntax
• <%
Set cr=Server.CreateObject("MSWC.ContentRotator")
Example:
• The following example displays a different content each time a visitor views the Web
page.
• First, create a text file named "textads.txt" and place it in a subfolder called "text".
• "textads.txt":
%% #3 <h2>This is a great day!!</h2>
%% #3 <img src="smiley.gif">
ChooseContent
• Gets and displays a content string
• <%
dim cr
Set cr=Server.CreateObject("MSWC.ContentRotator")
response.write(cr.ChooseContent("text/textads.txt"))
%>
Output:
GetAllContent
• Retrieves and displays all of the content strings in the text file
• <%
dim cr
Set cr=Server.CreateObject("MSWC.ContentRotator")
response.write(cr.GetAllContent("text/textads.txt"))
%>
• Output:
• This is a great day!!
<html><body>
<%
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
%>
<table border="0" width="100%“><tr>
<th>Client OS</th><th><%=MyBrow.platform%></th>
</tr><tr><td >Web Browser</td> <td><%=MyBrow.browser%></td> </tr><tr>
<td>Browser version</td><td><%=MyBrow.version%>
</td></tr><tr>
<td>Frame support?</td><td><%=MyBrow.frames%></td>
</tr><tr>
<td>Table support?</td><td><%=MyBrow.tables%></td>
</tr><tr>
<td>Sound support?</td><td><%=MyBrow.backgroundsounds%>
</td></tr><tr>
<td>Cookies support?</td><td><%=MyBrow.cookies%>
</td></tr><tr>
<td>VBScript support?</td><td><%=MyBrow.vbscript%>
</td></tr><tr>
<td>JavaScript support?</td><td><%=MyBrow.javascript%>
</td> </tr>
</table>
</body>
</html>
Output:
• Client OS WinNT
• Web Browser IE
• Browser version 5.0
• Frame support? True
• Table support? True
• Sound support? True
• Cookies support? True
• VBScript support? True
• JavaScript support? True
Accessing database
Server Side Scripting Model:
This model is characterized by the inclusion of labels or specific marks inside the documents
(HTML, XML or WML) located the server, inside those, orders required for the server to
execute are included, after that an HTML (or XML/WML) answer is generated which is
understandable for the client's browser.
The main advantages of this type of solutions include the independence in connection with the
client's browser; the use of SQL language to get the interaction with databases, and the easiness
and short time of test.
Disadvantages:
Its main disadvantages reside in the sacrifice in performance because the scripts are interpreted
(they require that the server carries out syntactic revision in each execution) and the necessity to
modify the code of the scripts when there are changes carried out in the interface. This model is
characteristic of solutions as ASP, Cold Fusion and PHP, and other solutions.
ASP: This is the solution of Microsoft which can be implemented in servers with Windows NT
with Internet Information Server of Microsoft, and inclusive for Windows 95/98 with Personal
Web Server installed.
Disadvantages:
- They have been broadly proven in servers IIS of Microsoft, and only until recently they have
been begun to develop products for other platforms (as iASP for Linux).
- When being interpreted, performance is sacrificed, because syntactic revision is made in each
execution (This restrictive one can be overcome using Web classes, which allow to create
compiled objects, but it will be required the acquisition of a programming language that supports
this technology additionally) Next a ASP script is presented, it visualizes data of a database
Access, that contains a chart friends with two fields: telephone and name, for which it has been
created a DSN (Data Source Name) previously in the control panel denominated aliasamigos.
PHP
PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Rasmus Lerdorf unleashed the first version of PHP way back in 1994.
PHP performs system functions, i.e. from files on a system it can create, open, read,
write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can
send data, return data to the user.
You add, delete, modify elements within your database thru PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Characteristics of PHP
Simplicity
Efficiency
Security
Flexibility
Familiarity
To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!" is an essential
example, first we will create a friendly little "Hello, World!" script.
As mentioned earlier, PHP is embedded in HTML. That means that in amongst your normal
HTML (or XHTML if you're cutting-edge) you'll have PHP statements like this :
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
Output:
Hello, World!
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the
URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>
</body>
</html>
* required field.
Name: *
E-mail: *
Website:
Comment:
Sending a mail
PHP must be configured correctly in the php.ini file with the details of how your system sends
email. Open php.ini file available in /etc/ directory and find the section headed [mail function].
Windows users should ensure that two directives are supplied. The first is called SMTP that
defines your email server address. The second is called sendmail_from which defines your own
email address.
[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net
Linux users simply need to let PHP know the location of their sendmail application. The path
and any desired switches should be specified to the sendmail_path directive.
[mail function]
; For Win32 only.
SMTP =
PHP makes use of mail() function to send an email. This function requires three mandatory
arguments that specify the recipient's email address, the subject of the the message and the actual
message additionally there are other two optional parameters.
As soon as the mail function is called PHP will attempt to send the email then it will return true
if successful or false if it is failed.
Multiple recipients can be specified as the first argument to the mail() function in a comma
separated list.
When you send a text message using PHP then all the content will be treated as simple text. Even
if you will include HTML tags in a text message, it will be displayed as simple text and HTML
tags will not be formatted according to HTML syntax. But PHP provides option to send an
HTML message as actual HTML message.
While sending an email message you can specify a Mime version, content type and character set
to send an HTML email.
Example
<html>
<head>
<title>Sending HTML email using PHP</title>
</head>
<body>
<?php
$to = "[email protected]";
$subject = "This is subject";
</body>
</html>
References:
Scot Johnson, Keith Ballinger, Davis Chapman, “Using Active Server Pages”, Prentice
Hall of India.
http://www.w3schools.com/
http://www.tutorialspoint.com
SUB-CODE: SCSX1016 SUB-NAME: WEB TECHNOLOGY
Unit-V
Web applications
A web application is any application that uses a web browser as a client. The application can be
as simple as a message board or a guest sign-in book on a website, or as complex as a word
processor or a spreadsheet.
What is a Client?
The 'client' is used in client-server environment to refer to the program the person uses to run the
application. A client-server environment is one in which multiple computers share information
such as entering information into a database.
The 'client' is the application used to enter the information, and the 'server' is the application used
to store the information.
A web application relieves the developer of the responsibility of building a client for a specific
type of computer or a specific operating system. Since the client runs in a web browser, the user
could be using an IBM-compatible or a Mac. They can be running Windows XP or Windows
Vista. They can even be using Internet Explorer or Firefox, though some applications require a
specific web browser.
Web applications commonly use a combination of server-side script (ASP, PHP, etc) and client-
side script (HTML, Javascript, etc.) to develop the application.
Web application security is a branch of Information Security that deals specifically with
security of websites, web applications and web services. At a high level, Web application
security draws on the principles of application security but applies them specifically
to Internet and Web systems.
Security threats
With the emergence of Web 2.0, increased information sharing through social networking and
increasing business adoption of the Web as a means of doing business and delivering service,
websites are often attacked directly. Hackers either seek to compromise the corporate network or
the end-users accessing the website by subjecting them to drive-by downloading.
Attacks
cross-site scripting (XSS)
SQL injection attacks
Phishing
Security Standards
OWASP : The Open Web Application Security Project (OWASP) is an online community
which creates freely-available articles, methodologies, documentation, tools, and technologies in
the field of web application security
Data that is shared between web components and is persistent between invocations of a web
application is usually maintained in a database. Web applications use the JDBC API to access
relational databases. In the JDBC API, databases are accessed via DataSource objects. A
DataSource has a set of properties that identify and describe the real world data source that it
represents. These properties include information such as the location of the database server, the
name of the database, the network protocol to use to communicate with the server, and so on.
Web applications access a data source using a connection, and a DataSource object can be
thought of as a factory for connections to the particular data source that the DataSource instance
represents. In a basic DataSource implementation, a call to the getConnection method returns a
connection object that is a physical connection to the data source. In the Application Server, a
data source is referred to as a JDBC resource.
If a DataSource object is registered with a JNDI naming service, an application can use the JNDI
API to access that DataSource object, which can then be used to connect to the data source it
represents.
Note: Application Server 8.2 includes a copy of the open source Derby database server.
Application Server 8.0/ 8.1 includes the PointBase database server. If you are using Application
Server 8.0/8.1, either follow the instructions in the J2EE Tutorial at
http://java.sun.com/j2ee/1.4/docs/tutorial-update6/doc/index.html that works with Application
Server 8.0/8.1 or upgrade to Application Server 8.2 (see
http://java.sun.com/j2ee/1.4/download.html#appserv to download).
To populate the database for the Duke's Bookstore examples, follow these steps:
...
[sql] Executing file:
<j2eetutorial.home>\examples\web\bookstore\books.sql
[sql] 8 of 8 SQL statements executed successfully
Data sources in the Application Server implement connection pooling. To define the Duke's
Bookstore data source, you use the installed Derby connection pool named DerbyPool.
You create the data source using the Application Server Admin Console, following this
procedure:
To access a database from a web application, you must declare a resource reference in the
application's web application deployment descriptor. The resource reference specifies a JNDI
name, the type of the data resource, and the kind of authentication used when the resource is
accessed. To specify a resource reference for a Duke's Bookstore example using deploytool,
follow these steps:
To create the connection to the database, the data access object database.BookDBAO looks up
the JNDI name of the bookstore data source object:
Both the web application resource reference and the data source defined in the Application
Server have JNDI names. To connect the resource reference to the data source, you must map the
JNDI name of the former to the latter. This mapping is stored in the web application runtime
deployment descriptor. To create this mapping using deploytool, follow these steps:
1. Select localhost:4848 in the Servers list to retrieve the data sources defined in the Application
Server.
2. Select the WAR in the Web WARs list.
3. Select the Resource Ref's tab.
4. Select the Resource Reference Name, jdbc/BookDB, defined in the previous section.
5. In the Sun-specific Settings frame, select jdbc/BookDB from the JNDI Name drop-down list.
Applications
Web templates can be used by any individual or organization to set up their website. Once a
template is purchased or downloaded, the user will replace all generic information included in
the web template with their own personal, organizational or product information.
Examples:
Web Services
Web services are open standard based Web applications that interact with other web applications
for the purpose of exchanging data.
XML is used to encode all communications to a web service. For example, a client invokes a
web service by sending an XML message, and then waits for a corresponding XML response.
Because all communication is in XML, web services are platform neutral and language neutral.
Java can talk with Perl; Windows applications can talk with UNIX applications. Web services
conceptually are just specialized web applications:
Body of web services request and response will be SOAP message which defines a protocol for
message exchange between applications.
1. Currency Converter
2. Temperature conversion
3. Weather Forecast system
4. Credit card validation system
SOAP
WDSL
UDDI
Service-Oriented Architecture
A service-oriented architecture is essentially a collection of services. These services
communicate with each other. The communication can involve either simple data passing
or it could involve two or more services coordinating some activity. Some means of
connecting services to each other is needed.
Service-oriented architectures are not a new thing. The first service-oriented architecture
for many people in the past was with the use DCOM or Object Request Brokers (ORBs)
based on the CORBA specification. For more on DCOM and CORBA.
The technology of Web Services is the most likely connection technology of service-
oriented architectures.
Elements of SOA
Application frontend
Service
Service repository
Service bus
Contract
Implementation
Interface
Business logic
Data
Every SOAP message has a mandatory Envelope element, an optional Header element,
and a mandatory Body element. Each of the elements has an associated set of rules.
Envelope:
Every SOAP message has a root Envelope element. SOAP does not define a versioning.
Rather, SOAP uses XML namespaces to differentiate versions.
SOAP Message
Envelope (required)
Header (optional)
Body (required)
Fault (optional)
Header:
The optional Header element offers a flexible framework for specifying additional
application level requirements.
For example, the Header element can be used to specify a digital signature for password-
protected services. The Header framework provides an open mechanism for authentication,
transaction management and payment authentications.
Header Attributes:
Actor – The SOAP protocol defines a message path as a list of SOAP service nodes.
Each of these intermediate nodes can perfume some processing and forward the
message to the next node in the chain.
By setting the actor attribute, the client can specify the recipient of the SOAP
header.
<SOAP-ENV: Header>
SOAP-ENV: mustUnderstand=”true”>
</ns: PaymentAccount>
</SOAP-ENV: Header>
Body:
Fault:
In the event of an error, the Body element will include a Fault element.
The Fault sub elements include the faultCode, faultString, faultActor, and detail
elements.
faultCode:
faultString:
faultActor:
A text string indicating who caused the fault. This is usable if the SOAP message travels
through several nodes in the SOAP message, and the clients to know which node caused the
error.
Detail:
<SOAP-ENV: Envelope
<SOAP-ENV: Body>
<SOAP-ENV: Fault>
SOAP-ENV: client
</faultCode>
</faultString>
</SOAP-ENV: Fault>
</SOAP-ENV: Body>
</SOAP-ENV: Envelope>
SOAP Encoding:
This enables the SOAP messages to indicate specific data types such as integers, floats,
doubles or arrays.
Most of the time, the encoding rules are implemented directly by the SOAP.
SOAP data types are divided into two broad categories scalar types and compound types.
Scalar types contain exactly one value, such as a last name, price, or product description.
The encoding style for a SOAP message is set via the SOAP-ENV: encoding style
attribute.
SOAP Request:
The client request must include the name of the method to invoke and any parameter.
Here is a simple client request sent to Xmethod.
First, the request includes a single mandatory Envelope element which in turn includes
mandatory Body elements.
Second, a total of four XML namespaces are defined. Namespaces are used to disambiguate
XML elements and attributes. The body element encapsulates the main”pay load” of the SOAP
message. The only element is getTemp, which is tied to the XMethods namespace and
corresponds to the remote method name.
Each parameter to the method appears as a sub element. Here we have a single zip code element
which is assigned to the XML schema xsd: string data typr and set to 10016.
<SOAP-ENV: Envelope
xmlns:SOAP-env=”http://schemas.xmlSOAP.org/SOAP/envelope/
xmlns:xsi=http://www.w3.org/2001/xmlschema-instance
xmlns:xsd=”http://www.w3.org/2001/xml””>
<SOAP-ENV: Body>
</nsl: getTemp>
</SOAP-ENV: Body>
</SOAP-ENV: Envelope>
SOAP Response:
<SOAP-ENV: Envelope
<SOAP-ENV: Body>
<ns1: getTempResponse
SOAP-ENV:encodingStyle=”http://schema.xmlSOAP.org/SOAP/encoding/”>
</ns1: getTempResponse>
</SOAP-ENV: body>
</SOAP-ENV: envelope>
Just like the request, the response includes envelope and body elements and same four xml
namespaces. The body element includes a single getTempResponse element, corresponding to
our initial request. The response element includes a single return element, indicating an xsd:
float.
SOAP TRANSPORT:
o SOAP does not care what transport protocol is uised to exchange the message.
o This makes SOAP extremely flexible in how and where it is used.
o To exchange SOAP message through HTTP, FTP, raw TCP, SMTP, POP3.
HTTP is by far the most common transport used to exchange SOAP messages.
HTTP is simple, stable and widely deployed.
Most Firewall allows HTTP Traffic.
The SOAP request message is posted to the HTTP server with the HTTP request, and the
Server returns the SOAP response message in the HTTP response.
POST/target HTTP/1.0
Content_Type: text/xml
Content_Length:
<SOAP_Env …………………………….
HTTP/1.1 200 ok
Content_Type: text/xml
Content_Length:
The SOAPAction HTTP header is defined by the SOAP specification and indicates
the intent of the SOAP HTTP request.
Its value is completing arbitrary but its intended to tell the HTTP server what the
SOAP message wants to do before the HTTP server decodes the XML.
WSDL
Helloservice.wsdl
Definitions:
The definitions element specifies that this document is the helloservice. It also specifies
many namespaces that will be used through-out the document. The use of namespaces is
important for differentiating elements. It enables the document preference multiple external
specification, including the wsdl specification, the SOAP specification and the xml schema
specification.
The definitions element also specifies a target namespace attribute that is a conversion of
xml schema that enables the wsdl document to refer itself.
<definitions name=”helloservice”
target namespace=”http://www.ecerami.com/wsdl/helloservice.wsdl”
xmlns=”http://schemas.xmlsoap.org/wsdl/”
xmlns:soap=”http://schemas.xmlsoap.org/wsdl/soap”
xmlns=”http://www.ecerami.com/wsdl/helloservice.wsdl
“xmlns:xsd=”http://www.w3.org/2001/xmlschema ”>
Methods:
Two messages elements are defined. The first represents a request message,
sayhellorequest and the second represents a response message sayhelloresponse.
<message name=”sayhellorequest”>
</message>
<message name=”sayhelloresponse”>
</message>
Each of these messages contains a single part element. For the request, the part specifies the
function parameters; we specify a single firstname parameter. For the response, the part specifies
the function return value. The part element‟s type attribute specifies an xml schema data type.
If the function expects multiple arguments or return multiple values, we can specify multiple part
element.
Port type:
The port type element defines a single operation called sayhello. The operation itself
consists of a single input message (sayhellorequest) and a single output message
(sayhelloresponse)
<port type name=”hello_port type”>
<operation name=”sayhello”>
</operation>
</port type>
Binding:
The binding element provides specific details on how a port type operation will actually
be transmitted over the wire. Bindings can be made available via multiple transports including
http get, http post, or SOAP. The binding elements itself specifies the name and type attributes.
The type attribute reference the port type defined in the document.
SOAP binding:
Wsdl 1.1 includes built-in extensions for SOAP 1.1. This enables yout o specifies SOAP-
specific details, including SOAP header, SOAP encoding styles, and the SOAP action http
header. The SOAP extension elements include,
SOAP: binding
This element indicates that the binding will be made available via SOAP. The style
attribute indicates the overall style of the SOAP message format. A style value of rpc specifies
an rpc format. This means that the body of the SOAP request will indicate a wrapper xml
element indicating the function name. A style value of document specifies an XML document
call format.
The transport attribute indicates the transport of the SOAP messages. The value
http://schemas.xmlsoap.org/soap/http indicates the SOAP http transport.
SOAP: Operation
This element enables you to specify the details of the input and output messages.
<service name=”Hello_Service”>
<documentation>WSDL file for Hello Service</documentation>
<port binding=”tns: Hello_Binding” name=”Hello_port”>
<SOAP: address location=”http://localhost:8080/soap/servlet/rpc router”/>
</port>
</service>
UDDI
UDDI is a directory service where business can register and search for web services.
UDDI was originally created by Microsoft, IBM and Ariba, represents a technical
specification for publishing and finding business and webservices.
UDDI consists of two parts. First, UDDI is a technical specification for building a
distributed directory of business and web service.
Data is stored within a specific XML format. The UDDI specification includes API
details for searching existing data and publishing new data. Second, the UDDI business
registry is a fully operational implementation of UDDI specification. The data captured
within UDDI divided into three main categories.
WHITE PAGES:
White pages provide very limited information such as name, telephone and contact
address.
YELLOW PAGES:
Yellow pages provide a categorization based on business and service type. For example,
the data may include industry, product
GREEN PAGE:
White and yellow pages directories were, earlier, available in the printed format.
In the present one, these directories are available online and are accessible globally.
Business entity data structure represents the top-level UDDI element. This element holds
descriptive information about business.
The business entity data structure contains information such as contact information,
categorization, identifiers, descriptions and business relations.
The business entity data structure defines an important attribute called business key,
which is a unique key.
Business entity
Discovery URL
Name
Description
Contacts
Business service
Category bag
Identifier bag
The <identifier bag> data structure contains a list of identifiers; the <category bag> data
structure contains a list of business categories that describe a specific business aspect.
Business Service:
Business service data structure provides information scout a single web service or group
related with web services.
The business service data structure contains descriptive information such as the name of
the service, description, classification.
Business service
name
description
bindingTemplate
categoryBag
The data structure defines two important attributes, business key and service key.
<businessService
servicekey=” “
businessKey=” “>
<name> </name>
<description> </description>
<bindingTemplates> </bindingTemplates>
<categoryBag> </categoryBag>
</businessService>
Binding Template:
bindingTemplate
description
accesspoint
tmodelInstanceDetails
categoryBag
<bindingTemplates>
<bindingTemplate
serviceKey=” “
bindingKey=” “>
<description> </description>
<accessPoint URLType= > </accessPoint>
<tmodelInstanceDetails>
<tmodelInstanceInfo tmodelKey=” “/>
</tmodelInstanceDetails>
</bindingTemplate>
</bindingTemplates>
tModel:
UDDI REGISTRIES:
There is the API that is used for inter-UDDI communication implementation. The
purpose is to manipulate the data stored in different UDDI implementations.
The node API sets are available for implementing a variety of tasks such as UDDI
inquiry, UDDI publications, UDDI subscription and UDDI security.
UDDI NODE:
A system that hosts an application to support at least one of the node API sets is called a
UDDI node. A UDDI node must ensure the following.
One or more UDDI nodes may be combined to form a UDDI registry. These UDDI nodes are
designed to collectively manage the business data in the registry. The UDDI registry architecture
is shown in the figure.
u2
u1
u3
u5 u4
Client Client
UDDI registry architecture
Service publication:
The task of service publication is an administration activity. Normal users are not
authorized for doing this activity and access to such activity will be granted through
authentication and authorization mechanism.
They are save Business, save Service, save Binding and save tmodel.
save Business:
This operation is represented using the <save_business> element. This stores or updates
the information contained within the <businessEntity> element.
save Service:
This operation inserts or modifies the information provided inside the <businessService>
data structures. This operation will affect the <bindingTemplate> and the <tmodel> data
strucutre.
save Binding:
This operation will insert or modify the information provided in the <bindingTemplate>
data structure. The save Binding also takes care of tmodel data structure.
save tmodel:
Service Deletion:
Similarly, we have delete messages for each of the four data structures. These delete
operations are authenticated operations. They are Delete Business, Delete Service, Delete
Binding and Delete tmodel.
Delete Business:
Deletion corresponds to the deletion of existing information requires UUID. UUID stands
for Universal Unique Identifier. UUID‟s are assigned when data structures are first created and
inserted into the UDDI business registry.
UUID are hexadecimal strings, and they are in accordance with the algorithm defined by
ISO. It is an authentication operation. <delete_business> element is used to provide the
information deletion.
Delete Service:
The element <delete_Service> is used to encode the service data for deletion purpose. It
requires valid UUID for deleting the business service data.
Delete Binding and Delete tmodel are authenticated operations, which accept valid UUID‟s
corresponding to binding and tmodel informations.
Service Discovery:
Service discovery will enable clients to search and find out the details of the company,
services and other related informations from the UDDI business registry.
For searching we use the inquiry interface. Searching can be carried out at two different
levels
Browse
Drill down
The service discovery needs to be brought about using service_searching or service
querying applications. These applications communicate with the registries using soap.
Service_querying applications, use appropriate API‟s that help in generating appropriate
soap based queries based on UDDI specifications.
Information Browsing:
Browsing refers to a superficial search of the UDDI Business registry. Within browsing,
we have four different categories. Find Business, Find Service, Find Binding and Find tmodel.
All the find and drill down operations are non-authenticated operations.
Find Business:
Find Service:
Web service policy provides a flexible and extensible grammar for expressing the
capabilities, requirements and general characteristics of entities in a XML webservices- based
system.
Eg:
1.<wsp:Policy xmlns:sp=”http://schemas.xmlsoap.org/ws/2005/07/securitypolicy “
xmlns:wsp=”http://schemas.xmlsoap.org/ws/2004/09/policy”>
2. <wsp:ExactlyOne>
3. <sp:Basic256 Rsa 15/>
4. <sp:TripleDes Rsa 15/>
5. </wsp:ExactlyOne>
6. </wsp:Policy>
Line (1-6) represents a policy for the algorithm.
Line (2-5) illustrates the exactly one policy operator.
Policy operators group policy assertions into policy alternatives.
In order to understand how UDDI uses WSDL as a description language, you must be clear on
how WSDL documents are mapped to the UDDI structure. The implementation document s
maps to the UDDI business service element whereas the service interface. The first step is
publishing a WSDL description in UDDI registry is publishing the service interface as a tModel.
businessEntity
Service Implementation
Import
businessService
Service
port
bindingTemplate
port
bindingTemplate
Service Interface
types
message
tModel
portType
Set the name field of the tmodel to the target Namespace attribute of the definitions
binding document. This filed is used to locate the appropriate tmodel.
element in the interface
The description field of the tmodel corresponds to the documentation element of the
interface document. This field can have a maximum of 256 characters.
Set the overviewURL field of the tmodel to the URL and binding specification in the
interface document.
Set the categoryBag field of the tmodel so that it‟s keyed reference in uddi-org: types and
its keyValue in wsdlSpec. This defines the UDDI entry as a WSDL service interface
definition.
<keyedReference tModelkey=”UUID:DB77450D-9FA8-45D4-A7BC-9C8C7D998F8D”
keyName=”Sample Web Service” keyValue=”12345678”/>
</categoryBag>
</tModel>
Next, we must create the businessService and bindingTemplate elements that correspond to the
WSDL service implementation document.
The name field of the businessService is set to the name attribute of the service element
in the implementation document.
The description field of the businessService comes from the documentation element in
the implementation document.
The description field of the bindingTemplate comes from the first 256 characters of the
documentation element of the port element, if it exists.
The accesspoint field is set to the value of the location attribute of the extension element
that is associated with the port element, in the case of a SOAP or HTTP binding.
Putting these instructions together, we can build the UDDI businessService that corresponds to
the WSDL interface document. The businessService appears as follows
</instanceDetails>
</tModelInstanceInfo>
</tModelInstanceDetails>
</bindingTemplate>
</bindingTemplates>
<categoryBag>
<keyedReference tModelKey=”UUID:DB77450D-9FA8-45D4-A7BC-3663DA8D8CFB”
keyName=”Sample Web Service” keyValue=”84121801”/>
</categoryBag>
</businessService>
Inquiry API:
find_business: locates information about one or more business and returns a businessList
message. Searches can be performed on name elements (or partial name elements),
identifierBag elements, categoryBag elements, tModelBag elements, or discoveryURL
elements. tModelBag elements are collection of tModel elements that allow searches for
compatible bindings. If there are no matches, an empty businessList is returned. Errors
are handled as they are with the find_binding query.
find_tModel: locates one or more tModel information structures and returns a tModelList
structure, which is a list of abbreviated information about tModel elements that match the
search criteria. Search parameters, no match conditions, and error conditions are handled
the same as the preceding queries.
Publication API:
The publication queries are as follows
References:
Leon Shklar, Rich Rosen, “Web Application Architecture: Principles, Protocols, and
Practices”, John Wiley & Sons, Second Edition.
http://www.w3schools.com/