Ip Notes Converted in Word
Ip Notes Converted in Word
You can program for the Web, using your skills as a Visual Basic programmer, no matter what your level of
experience with Internet technology. If you are new to the Internet or unfamiliar with its technology, Visual
Basic allows you to quickly and easily produce functional applications. If you are more experienced with
Internet technology, you can work at a more advanced level.
From one perspective, Internet technology simply provides another area for your development efforts. When
you deploy Internet applications on the Web, you may go about it differently — incorporating HTML pages
with your Visual Basic code, providing security features, and so on — but you're still calling methods, setting
properties, and handling events. In this way, all of your knowledge as a Visual Basic developer can be carried
into the Internet arena.
From another perspective, applying Internet technology enables you to extend your development skills in
exciting new ways. For example, writing Visual Basic code that manipulates HTML pages allows you to
decrease deployment costs, reduce client maintenance probl ms, and reach the broad audience of the Internet.
A common way to think about Internet development is in terms of client/server relationships. In this case, the
client is the browser, and the server is the Web server. Most interactions on the Internet or an intranet can be
thought of in terms of requests and responses. The browser makes a request to the Web server (usually to
display a page the user wants to see) and the W b server returns a response (usually an HTML page, an
element, or an image) to the browser.
The Internet encompasses two cat gori s: the Internet and the intranet. The Internet is a global, distributed
network of computers operating on a protocol called TCP/IP. An intranet is also a network of computers
operating on the TCP/IP protocol, but it is not global. Generally, intranets are restricted to a particular set of
users and are not accessible by the outside world. For example, many corporations use a corporate intranet to
provide information to their employees, and run another Internet site for external users. Users within the
company can access both the intranet sites and the Internet, but users outside the company can access only the
company's Internet sites.
HTML Pages
HTML (HyperText Markup Language) is a language that allows you to display documents in a Web browser.
You use HTML to create .htm files that are displayed in a browser. When you create an Internet application in
Visual Basic, your user interface is usually made up of HTML pages rather than forms. In many ways, an .htm
file (which allows you to display HTML pages) is similar to a Visual Basic .frm file (which allows you to
display a Visual Basic form).
Note While the user interface is generally made up of HTML pages, it can also contain a mix of Visual Basic
forms and HTML pages.
An .htm file is a text document that contains a series of tags that tell the browser how to display the file. These
HTML tags supply information about the page's structure, appearance, and content. The following figure shows
the relationship between page in the browser and its HTML tags:
HTML Page and Source HTML
In addition to describing the structural relationships among page elements, some HTML tags also contain
attributes. Attributes provide details about a particular tag. For example, the tag that inserts an image onto a
page contains an attribute that specifies the name of the file to insert. The tag is shown below.
You use the concepts of object-oriented programming in your Visual Basic Internet applications just as you do
in forms-based Visual Basic applications. In Visual Basic Internet applications, you use Internet-related object
models to access and manipulate information and controls on your HTML pages.
There are two types of Visual Basic Internet applications: IIS applications and DHTML applications. In IIS
applications, you make use of the Active Server Pages (ASP) object model to retrieve information from the
user, send information to the browser, and maintain information about the current session. In DHTML
applications, you use the Dynamic HTML (DHTML) object model to manipulate the elements on an HTML
page.
The important point to remember is that you access the information on your HTML pages through objects,
regardless of whether the objects themselves are ASP or DHTML. The object models are explained in much
greater detail in the chapters describing each type of application.
For More Information See "A History of Development on the Internet" for more information on the
differences between IIS and DHTML applications. See the "Developi g DHTML Applications" chapter for
more information on using Dynamic HTML objects. See the "Develop ng IIS Applications with Webclasses"
chapter for more information on using ASP objects. See the MSDN™ Web site at http://msdn.microsoft.com/
for details on using HTML and Internet technologies.
Web page
Web site
A collection of webpages
Web Server
A computer that hosts a website
Search Engine
A website that helps you find web pages
HTML Basics
Welcome to HTML Basics. This workshop leads you through the basics of Hyper Text Markup Language
(HTML). HTML is the building block for web pages. You will learn to use HTML to author an HTML page
to display in a web browser.
Objectives:
Prerequisites:
You will need a text editor, such as Notepad and an Internet browser, such as Internet Explorer or Netscape.
Q: What is Notepad and where do I get it?
A: Notepad is the default Windows text editor. On most Windows systems, click your Start button and
choose Programs then Acc ssories. It should be a little blue notebook.
Mac Users: SimpleText is the default text editor on the Mac. In OSX use TextEdit and change the
following preferences: Select (in the preferences window) Plain text instead of Rich text and then
select Ignore rich text commands in HTML files. This is very important because if you don't do this
HTML codes probably won't work.
One thing you should avoid using is a word processor (like Microsoft Word) for authoring your HTML
documents.
HTML is a format that tells a computer how to display a web page. The documents themselves are plain text
files with special "tags" or codes that a web browser uses to interpret and display information on your
computer screen.
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>
Save the file as mypage.html. Start your Internet browser. Select Open (or Open Page) in the File menu of
your browser. A dialog box will appear. Select Browse (or Choose File) and locate the html file you just
created - mypage.html - select it and click Open.
HTM or HTML Extension?
When you save an HTML file, you can use either the .htm or the .html extension. The .htm extension comes
from the past when some of the commonly used software only allowed three letter extensions. It is perfectly
safe to use either .html or .htm, but be consistent. mypage.htm and mypage.html are treated as different files
by the browser.
A good way to learn HTML is to look at how other people have coded their html pages. To find out, simply
click on the View option in your browsers toolbar and select Source or Page Source. This will open a
window that sho s you the actual HTML of the page. Go ahead and view the source html for this page.
HTML Tags
▪ HTML tags are not case sensitive, <b> means the same as <B>
In HTML there are both logical tags and physical tags. Logical tags are designed to describe (to the browser)
the enclosed text's meaning. An example of a logical tag is the <strong> </strong> tag. By placing text in
between these tags you are telling the browser that the text has some greater importance. By default all
browsers make the text appear bold when in between the <strong> and
</strong> tags.
Physical tags on the other hand provide specific instructions on how to display the text they enclose. Examples
of physical tags include:
HTML Elements
The purpose of the <b> tag is to define an HTML element that should be displayed as bold. This is
<body>
This is my first homepage. <b>This text is bold</b>
</body>
This HTML element starts with the start tag <body>, and ends with the end tag </body>. The purpose of
the <body> tag is to define the HTML element that contains the body of the HTML document.
Nested Tags
You may have noticed in the example above, the <body> tag also contains other tags, like the <b> tab. When
you enclose an element in with multiple tags, the last tag opened should be the first tag closed. For example:
Note: It doesn't matter which tag is first, but they must be closed in the proper order.
You may notice we've used lowercase tags even though I said that HTML tags are not case sensitive.
<B> means the same as <b>. The World Wide Web Co sortium (W3C), the group responsible for
developing web standards, recommends lowercase tags in their HTML 4 recommendation, and
XHTML (the next generation HTML) requires lowercase ta s.
Tag Attributes
Tags can have attributes. Attributes can p ovide additional information about the HTML elements on your
page. The <tag> tells the browser to do something, while the attribute tells the browser how to do it. For
instance, if we add the bgcolor attribute, we can tell the browser that the background color of your page
should be blue, like this: <body bgcolor="blue">
This tag defines an HTML table: <table>. With an added border attribute, you can tell the browser that the
table should have no borders: <table border="0">. Attributes always come in name/value pairs like this:
name="value". Attributes are always added to the start tag of an HTML element and the value is
surrounded by quotes.
Basic HTML Tags
The most important tags in HTML are tags that define headings, paragraphs and line breaks.
Tag Description
<html> Defines an HTML document
Headings
Headings are defined with the <h1> to <h6> tags. <h1> defines the largest headi g while <h6> defines
the smallest.
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
<h4>This is a heading</h4>
<h5>This is a heading</h5>
<h6> This is a heading</h6>
HTML automatically adds an extra blank line before and aft r a h ading. A useful heading attribute is align.
<h5 align="left">I can align headings </h5>
<h5 align="center">This is a ce tered heading </h5>
<h5 align="right">Th s s a heading aligned to the right </h5>
Paragraphs
Paragraphs are defined with the <p> tag. Think of a paragraph as a block of text. You can use the
align attribute with a paragraph tag as well.
<p align="left">This is a paragraph</p>
<p align="center">this is another p r gr ph</p>
Important: You must indicate paragraphs with <p> elements. A browser ignores any
indentations or blank lines in the source text. Without <p> elements, the document becomes
one large paragraph HTML automatically adds an extra blank line before and after a paragraph.
Line Breaks
The <br> tag is used hen you want to start a new line, but don't want to start a new paragraph. The
<br> tag forces a line break wherever you place it. It is similar to single spacing in a document.
Horizontal Rule
The <hr> element is used for horizontal rules that act as dividers between sections, like this:
The horizontal rule does not have a closing tag. It takes attributes such as align and width. For instance:
Comments in HTML
The comment tag is used to insert a comment in the HTML source code. A comment can be placed anywhere
in the document and the browser will g ore everything inside the brackets. You can use comments to write
notes to yourself, or write a helpful message to someone looking at your source code.
Notice you don't see the text b tw n the tags <!-- and -->. If you look at the source code, you would see the
comment. To view the source code for this page, in your browser window, select View and then select
Source.
Note: You need an exclamation point after the opening bracket <!-- but not before the closing
bracket -->.
HTML automatically adds an extra blank line before and after some elements, like before and after a
paragraph, and before and after a heading. If you want to insert blank lines into your document, use the
<br> tag.
Tag Description
<abbr> Defines an abbreviation Tag Description
<acronym> Defines an acronym <b> Defines bold text
<address> Defines an address element <big> Defines big text
<cite> Defines a citation <i> Defines italic text
<code> Defines computer codetext <small> Defines small text
<blockquote> Defines a long quotation <sup> Defines superscripted text
<del> Defines text <sub> Defines subscripted text
<dfn> Defines a definition term <tt> Defi es teletype text
<em> Defines emphasized text <u> Deprecated. Use styles instead
<ins> Defines inserted text
<kbd> Defines keyboard text
<pre> Defines preformatted text
<q> Defines a short quotation
<samp> Defines sample computer code
<strong> Defines strong text
<var> Defines a variable
Character tags like <strong> and <em> produce the same physical display as <b> and <i> but are
more uniformly supported across different browsers.
Some characters have a special m aning in HTML, like the less than sign (<) that defines the start of an
HTML tag. If we want the browser to actually display these characters we must insert character entities
in place of the actual characters themselves.
semicolon (;). The & means we are beginning a special character, the ; means ending a special character
and the letters in between are sort of an abbreviation for what it's for. To display a less than sign in an
HTML document we must write: < or < The advantage of using a name instead of a number is
that a name is easier to remember. The disadvantage is that not all browsers support the newest entity
names, while the support for entity numbers is very good in almost all browsers.
Non-breaking Space
The most common character entity in HTML is the non-breaking space . Normally HTML will
truncate spaces in your text. If you add 10 spaces in your text, HTML will remove 9 of them. To add
spaces to your text, use the character entity.
HTML Fonts
The <font> tag in HTML is deprecated. The World Wide Web Consortium (W3C) has removed the
<font> tag from its recommendations. In future versions of HTML, style sheets (CSS) will be used to
define the layout and display properties of HTML elements. The <font> Tag Should NOT be used.
HTML Backgrounds
Backgrounds
The <body> tag has t o attributes where you can specify backgrounds. The background can be a color or
an image.
Bgcolor
The bgcolor attribute specifies a background-color for an HTML page. The value of this attribute can be
a hexadecimal number, an RGB value, or a color name: <body bgcolor="#000000">
<body bgcolor="rgb(0,0,0)">
<body bgcolor="black">
Background
The background attribute can also specify a background-image for an HTML page. The value of this
attribute is the URL of the image you want to use. If the image is smaller than the browser window,
the image will repeat itself until it fills the entire browser window.
<body background="clouds.gif">
<body background="http://profdevtrain.austincc.edu/html/graphics/clouds.gif">
The URL can be relative (as in the first line above) or absolute (as in the second line above).
If you want to use a background image, you should keep in mind:
▪ Will the background image increase the loading time too much?
▪ Will the background image look good with other imag s on the page?
▪ Will the background image look good with the text colors on the page?
▪ Will the background image look good when it is r p at d on the page?
▪ Will the background image take away the focus from the text?
<html>
<head>
<title>My First Webpage</title>
</head>
<body background="http://profdevtrain.austincc.edu/html/graphics/clouds.gif"
bgcolor="#EDDD9E"> <h1 align="center">My First Webpage</h1>
<p>Welcome to my <strong>first</strong> webpage. I am writing this page using a text editor and
plain old html.</p>
<p>By learning html, I'll be able to create webpages like a <del>beginner</del> pro....<br>
which I am of course.</p>
</body>
</html>
Save your page as mypage3.html and view it in your browser. To view how the page should look,
visit this web page: http://profdevtrain.austincc.edu/html/mypage3.html
Notice we gave our page a background color as well as a backg ound mage. If for some reason the web
page is unable to find the picture, it will display our background color.
HTML Colors
Color Values
Colors are defined using a hexadecimal notation for the combination of red, green, and blue color values
(RGB). The lowest value that can be given to o e light source is 0 (hex #00). The highest value is 255
(hex #FF). This table shows the result of combining r d, green, and blue:
Color Names
A collection of color names is supported by most browsers. To view a table of color names that are
supported by most browsers visit this web page: http://profdevtrain.austincc.edu/html/color_names.htm
Note: Only 16 color names are supported by the W3C HTML 4.0 standard (aqua, black, blue,
fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow).
For all other colors you should use the Color HEX value.
A few years ago, when most computers supported only 256 different colors, a list of 216 Web Safe Colors
was suggested as a Web standard. The reason for this was that the Microsoft and Mac operating system
used 40 different "reserved" fixed system colors (about 20 each). This 216 cross platform web safe color
palette was originally created to ensure that all computers would display all colors correctly when running a
256 color palette. To view the 216 Cross Platform Colors visit this web page:
http://profdevtrain.austincc.edu/html/216.html
The combination of Red, Green and Blue values from 0 to 255 gives a total of more than 16 million
different colors to play with (256 x 256 x 256). Most modern monitors are capable of displaying at least
16,384 different colors. To assist you in using color schemes, check out
http://wellstyled.com/tools/colorscheme2/index-en.html. This site lets you test different color schemes
for page backgrounds, text and links.
HTML Lists
HTML provides a simple way to show unordered lists (bullet lists) or ordered lists (numbered lists).
Unordered Lists
An unordered list is a list of items marked with bullets (typically small black circles). An unordered list
starts with the <ul> tag. Each list item starts with the <li> tag.
Ordered Lists
An ordered list is also a list of items. The list items are marked with numbers. An ordered list starts with
the <ol> tag. Each list item starts with the <li> tag.
Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.
Definition Lists
Definition lists consist of two parts: a term and a description. To mark up a definition list, you need
three HTML elements; a container <dl>, a definition term <dt>, and a definition description <dd>.
HTML Links
HTML uses the <a> anchor tag to create a link to another document or web page
An anchor can point to any resource on the Web: an HTML page, an mage, a sound file, a movie, etc. The
syntax of creating an anchor:
<a href="url">Text to be displayed</a>
The <a> tag is used to create an anchor to link from, the hr f attribute is used to tell the address of the
document or page we are linking to, and the words betwe n the open and close of the anchor tag will be
displayed as a hyperlink.
With the target attribute, you can define where the linked document will be opened. By default, the link
will open in the current window. The code below will open the document in a new browser window:
Email Links
To create an email link, you will use mailto: plus your email address. Here is a link to ACC's Help Desk:
<a href="mailto:[email protected]">Email Help Desk</a>
To add a subject for the email message, you would add ?subject= after the email address. For example:
<a href="mailto:[email protected]?subject=Email Assistance">Email Help Desk</a>
The name attribute is used to create a named anchor. When using named anchors we can create links that
can jump directly to a specific section on a page, instead of letting the user scroll around to find what he/she
is looking for. Unlike an anchor that uses href, a named anchor doesn't change the appearance of the text
(unless you set styles for that anchor) or indicate in any way that there is anything special about the text.
Below is the syntax of a named anchor:
<a name="top">Text to be displayed</a>
To link directly to the top section, add a # sign and the name of the anchor to the end of a URL, like this:
This Code Would Display
<a href="http://profdevtrain.austincc.edu/html
/10links.html#top">Back to top of page </a> Back to top of page
Named anchors are often used to create "table of co tents" at the beginning of a large document. Each
chapter within the document is given a nam d anchor, and links to each of these anchors are put at the top
of the document. If a browser cannot find a amed anchor that has been specified, it goes to the top of the
document. No error occurs.
HTML Images
The <img> tag is empty, which means that it contains attributes only and it has no closing tag. To display an
image on a page, you need to use the src attribute. Src stands for "source". The value of the src attribute
is the URL of the image you ant to display on your page. The syntax of defining an image:
<img src="graphics/chef.gif">
Not only does the source attribute specify what image to use, but where the image is located. The
above image, graphics/chef.gif, means that the browser will look for the image name chef.gif in a
graphics folder in the same folder as the html document itself.
src="chef.gif" means that the image is in the same folder as the html document calling for it.
src="images/chef.gif" means that the image is one folder down from the html document that called for it.
This can go on down as many layers as necessary.
src="../chef.gif" mea s that the image is in one folder up from the html document that called for it.
src="../../chef.gif" means that the image is two folders up from the html document that called for it.
src="../images/chef.gif" means that the image is one folder up and then another folder down in the images
directory.
The alt attribute is used to define an alternate text for an image. The value of the alt attribute
is author-defined text:
The alt attribute tells the reader what he or she is missing on a page if the browser can't load images. The
browser will then display the alternate text instead of the image. It is a good practice to include the alt
attribute for each image on a page, to improve the display and usefulness of your document for people
who have text-only browsers or use screen readers.
Image Dimensions
When you have an image, the browser usually figures out how big the image is all by itself. If you put in
the image dimensions in pixels however, the browser simply reserves a space for the image, then loads
the rest of the page. Once the entire page is loads it can go back and fill in the images. Without
dimensions, when it runs into an image, the browser has to pause loading the pag , load the image, then
continue loading the page. The chef image would then be:
<img src="graphics/chef.gif" width="130" height="101" alt="Smiling Happy Chef">
Open the file mypage2.html in your text editor and add code highlighted in bold:
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
<h1 align="center">My First Web page</h1>
<p>Welcome to my first webpage. I am w iting this page using a text editor and plain old
html.</p> <p>By learning html, I'll be able to cre te web pages like a pro....<br> which I am of
course.</p>
<!-- Who would have guessed how easy this would be :) -->
<p><img src="graphics/chef.gif" width="130" height="101" alt="Smiling Happy Chef"
align="center"></p>
<p align="center">This is my Chef</p>
</body>
</html>
Tables
Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag), and each row is
divided into data cells (with the <td> tag). The letters td stands for table data, which is the content of a
data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc.
This Code Would Display
<table>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr> row 1, cell 1 row 1, cell 2
<tr> row 2, cell 1 row 2, cell 2
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
To display a table with borders, you will use the border attribute.
Open up your text editor. Type in your <html>, <head> and <body> tags. From here on I will only be
writing what goes between the <body> tags. Type in the following:
<table border="1">
<tr>
<td>Tables can be used to layout information</td>
<td> <img src="http://profdevtrain.austincc.edu/html/graphics/chef.gif">
</td>
</tr>
</table>
Headings in a Table
The <table> tag has two attributes known as cellspacing and c llpadding. Here is a table example
without these properties. These properties may be used separately or tog ther.
This Code Would Display
<table border="1">
<tr>
<td>some text</td>
<td>some text</td>
</tr> some text some text
<tr>
<td>some text</td> some text some text
<td>some text</td>
</tr>
Cellspacing is the pixel width between the individual data cells in the table (The thickness of the lines
making the table grid). The default is z ro. If the border is set at 0, the cellspacing lines will be invisible.
This Code Would Display
<table border="1" cellspacing="5">
<tr>
<td>some text</td>
<td>some text</td> some text some text
</tr><tr>
some text some
<td>some text</td> text
<td>some text</td>
</tr>
Cellpadding is the pixel space between the cell contents and the cell border. The default for this property is
also zero. This feature is not used often, but sometimes comes in handy when you have your borders
turned on and you want the contents to be away from the border a bit for easy viewing. Cellpadding is
invisible, even with the border property turned on. Cellpadding can be handled in a style sheet.
Table Tags
Tag Description
<table> Defines a table
<th> Defines a table header
<tr> Defines a table row
<td> Defines a table cell
<caption> Defines a table caption
<colgroup> Defines groups of table columns
<col> Defines the attribute values for one or more columns in a table
Table Size
Table Width
The width attribute can be used to define the width of your table. It can be defined as a fixed width or a
relative width. A fixed table width is one where the width of the table is specified in pixels. For
example, this code, <table width="550">, will produce a table that is 550 pixels wide. A relative table
width is specified as a percentage of the width of the visitor's viewing window. Hence this code, <table
width="80%">, will produce a table that occupies 80 percent of the screen.
This table width is 250 pixels
There are arguments in favor of giving your tables a relative width because such table widths yield pages
that work regardless of the visitor's screen resolution. For example, a table width of 100% will always
span the entire width of the browser window whether the visitor has a 800x600 display or a 1024x768
display (etc). Your visitor never needs to scroll horizontally to read your page, something that is regarded
by most people as being very annoying.
<html>
<head>
<title>My First Web Page </title>
</head>
<body>
<table width="90%" cellpadding="5" cellspacing="0" >
<tr bgcolor="#EDDD9E">
<td width="200" valign="top"><img src="graphics/contact.gif" width="100"
height="100"></td> <td valign="top"><h1 align="right">Janet Doeson</h1>
<h3 align="right">Technical Specialist</h3></td>
</tr>
<tr>
<td width="200">
<h3>Menu</h3>
<ul>
<li><a href="home.html">Home</a></li>
<li> <a href="faq.html">FAQ</a></li>
<li> <a href="contact.html">Contact</a></li>
<li> <a
href="http://www.austincc.edu">Links</a>
</li> </ul></td>
<td valign="top"><h2 align="center">W lcome!</h2>
<p>Welcome to my first webpage. I created this webpage without the assistance of a
webpage editor. Just my little text editor and a keen unde standing of html.</p>
<p>Look around. Notice I'm ble to use paragraphs, lists and headings. You may not be
able to tell, but the layout is done with a table. I'm very clever. </p>
<blockquote>
<p>I always wanted to be somebody, but now I realize I should have been more
specific.</p>
<cite>Lily Tomlin </cite> </blockquote>
</td> </tr>
</table>
<hr width="90%" align="left">
<address>
Janet Doeson<br> Technical
Specialist<br> 512.555.5555
</address>
<p>Contact me at <a href="mailto:[email protected]">[email protected]</a> </p>
</body>
</html>
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the
text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what
background images or colors are used, as well as a variety of other effects.
CSS is easy to learn and understand but it provides powerful control over the presentation of an
HTML document. Most commonly, CSS is combined with the markup la guages HTML or
XHTML.
Advantages of CSS:
n write CSS once and then reuse same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages as you
want.
If you are using CSS, you do not need to write HTML tag attr butes every time. Just write one
CSS rule of a tag and apply to all the occurrences of that tag. So less code means faster download
times.
Easy maintenance
To make a global change, simply change the style, a d all elements in all the web pages will be
updated automatically.
Superior styles to HTML
CSS has a much wider array of attributes than HTML so you can give far better look to your
HTML page in comparison of HTML attributes.
Multiple Device Compatibility
Style sheets allow content to be optimized for more than one type of device. By using the same
HTML document, different versio s of a website can be presented for handheld devices such as
PDAs and cell phones or for printing.
Global web standards
Now HTML attributes are b ing deprecated and it is being recommended to use CSS. So its a
good idea to start using CSS in all the HTML pages to make them compatible to future browsers.
Introduction to JavaScript
JavaScript is a programming language that can be included on web pages to make them more
interactive. You can use it to check or modify the contents of forms, change images, open new
windows and write dynamic page content. You can even use it with CSS to make DHTML
(Dynamic HyperText Markup Language). This allows you to make parts of your web pages
appear or disappear or move around on the page. JavaScripts only execute on the page(s) that are
on your browser window at any set time. When the user stops viewing that page, any scripts that
were running on it are immediately stopped. The only exceptions are cookies or various client
side storage APIs, which can be used by many pages to store and pass information between
them, even after the pages have been closed.
Before we go any further, let me say; JavaScript has nothing to do with Java. If we are honest,
JavaScript, originally nicknamed LiveWire and then LiveScript when it was created by Netscape,
should in fact be called ECMAscript as it was renamed when Netscape passed it to the ECMA for
standardisation.
JavaScript is a client side, interpreted, object oriented, high l v l scripting language, while Java
is a client side, compiled, object oriented high level language. Now after that mouthful, here's
what it means.
Client side
Programs are passed to the computer that the browser is on, and that computer runs them.
The alternative is server side, where the pro ram is run on the server and only the results
are passed to the computer that the browser is on. Examples of this would be PHP, Perl,
ASP, JSP etc.
Interpreted
The program is passed as source code with all the programming language visible. It is
then converted into machine code as it is being used. Compiled languages are converted
into machine code first then passed around, so you never get to see the original
programming language. Java is actually dual half compiled, meaning it is half compiled
(to 'byte code') before it is passed, then executed in a virtual machine which converts it to
fully compiled code just before use, in order to execute it on the computer's processor.
Interpreted languages are generally less fussy about syntax and if you have made
mistakes in a part they never use, the mistake usually will not cause you any problems.
Scripting
This is a little harder to define. Scripting languages are often used for performing
repetitive tasks. Although they may be complete programming languages, they do not
usually go into the depths of complex programs, such as thread and memory
management. They may use another program to do the work and simply tell it what to do.
They often do not create their own user interfaces, and instead will rely on the other
programs to create an interface for them. This is quite accurate for JavaScript. We do not
have to tell the browser exactly what to put on the screen for every pixel (though there is
a relatively new API known as canvas that makes this possible if needed), we just tell it
that we want it to change the document, and it does it. The browser will also take care of
the memory management and thread management, leaving JavaScript free to get on with
the things it wants to do.
High level
Written in words that are as close to english as possible. The contrast would be with
assembly code, where each command can be directly translated into machine code.
Object oriented
The basic part of a script is a variable, literal or object. A variable is a word that represents a
piece of text, a number, a boolean true or false value or an object. A literal s the actual number
or piece of text or boolean value that the variable represents. An object s a collection of
variables held together by a parent variable, or a document component.
The next most important part of a script is an operator. Operators assign literal values to
variables or say what type of tests to perform.
The next most important part of a script is a control structure. Control structures say what scripts
should be run if a test is satisfied.
Functions collect control structures, actions and assig ments together and can be told to run
those pieces of script as and when necessary.
The most obvious parts of a script are the actions it performs. Some of these are done with
operators but most are done using methods. Methods are a special kind of function and may do
things like submitting forms, writing pag s or displaying messages.
Events can be used to detect actio s, usually created by the user, such as moving or clicking the
mouse, pressing a key or resetting a fo m. When triggered, events can be used to run functions.
Lastly and not quite so obvious is referencing. This is about working out what to write to access
the contents of objects or v n the objects themselves.
As an example, think of the following situation. A person clicks a submit button on a form.
When they click the button, we want to check if they have filled out their name in a text box and
if they have, we ant to submit the form. So, we tell the form to detect the submit event. When
the event is triggered, we tell it to run the function that holds together the tests and actions. The
function contains a control structure that uses a comparison operator to test the text box to see
that it is not empty. Of course we have to work out how to reference the text box first. The text
box is an object. One of the variables it holds is the text that is written in the text box. The text
written in it is a literal. If the text box is not empty, a method is used that submits the form.
With the object model, JavaScript gets all the power t eeds to create dynamic HTML:
Regular Expression
Regular expressions are patterns used to match character combinations in strings. In JavaScript,
regular expressions are also objects. These patterns are used with the exec and test methods of
RegExp, and with the match, replace, search, and split methods of String. This chapter describes
JavaScript regular expressions.
var re = /ab+c/;
Regular expression literals provide compilation of the regular expression when the script is
loaded. When the regular expression will remain constant, use this for better performance.
Using the constructor function provides runtime compilation of the regular expression. Use the
constructor function when you know the regular expression pattern will be changing, or you
don't know the pattern and are getting it from a other source, such as user input.
Simple patterns are constructed of characters for which you want to find a direct match. For
example, the pattern /abc/ matches character combinations in strings only when exactly the
characters 'abc' occur together and in that order. Such a match would succeed in the strings "Hi,
do you know your abc's?" and "The latest airplane designs evolved from slabcraft." In both cases
the match is ith the substring 'abc'. There is no match in the string 'Grab crab' because while it
contains the substring 'ab c', it does not contain the exact substring 'abc'.
The following table provides a complete list and description of the special characters that can
be used in regular expressions.
Character Meaning
A backslash that precedes a non-special charact r indicates that the next character is
special and is not to be interpreted literally. For example, a 'b' without a preceding '\'
generally matches lowercase 'b's wherever they occur. But a '\b' by itself doesn't
match any character; it forms the spec al word boundary character.
\
A backslash that precedes a special character indicates that the next character is not
special and should be interpreted literally. For example, the pattern /a*/ relies on the
special character '*' to match 0 or more a's. By contrast, the pattern /a\*/ removes
the specialness of the '*' to e able matches with strings like 'a*'.
Do not forget to esc pe \ itself while using the RegExp("pattern") notation because \
is also an escape ch r cter in strings.
Matches beginning of input. If the multiline flag is set to true, also
matches immediately after a line break character.
^ For example, /^A/ does not match the 'A' in "an A", but does match the 'A' in "An E".
The has a different meaning when it appears as the first character in a character set
'^' pattern. See complemented character sets for details and an example.
Matches end of input. If the multiline flag is set to true, also matches
$ immediately before a line break character.
For example, /t$/ does not match the 't' in "eater", but does match it in "eat".
*
Matches the preceding character 0 or more times. Equivalent to {0,}.
Special characters in regular expressions.
Character Meaning
For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A
bird warbled", but nothing in "A goat grunted".
Matches the preceding character 1 or more times. Equivalent to {1,}.
+
For example, /a+/ matches the 'a' in "candy" and all the a's in "caaaaaaandy",
but nothing in "cndy".
Matches the preceding character 0 or 1 time. Equivalent to {0,1}.
For example, /e?le?/ matches the 'el' in "angel" and the 'le' in "angle" and also the
'l' in "oslo".
If used immediately after any of the quantifi rs *, +, ?, or {}, makes the quantifier
non-greedy (matching the fewest possible charact rs), as opposed to the default,
?
which is greedy (matching as many charact rs as possible). For example, applying
/\d+/ to "123abc" matches "123". But applyi g /\d+?/ to that same string matches
only the "1".
Also used in lookahead assertio s, as described in the x(?=y) and x(?!y) entries of
this table.
(The decimal point) matches any single character except the newline character.
.
For example, /.n/ matches 'an' and 'on' in "nay, an apple is on the tree", but not 'nay'.
Matches 'x' and remembers the match, as the following example shows.
The parentheses are called capturing parentheses.
(x) The '(foo)' and '(bar)' in the pattern /(foo) (bar) \1 \2/ match and remember the first
two ords in the string "foo bar foo bar". The \1 and \2 in the pattern match the
string's last two words. Note that \1, \2, \n are used in the matching part of the
regex. In the replacement part of a regex the syntax $1, $2, $n must be used, e.g.:
'bar foo'.replace( /(...) (...)/, '$2 $1' ).
Matches 'x' but does not remember the match. The parentheses are called non-
capturing parentheses, and let you define subexpressions for regular expression
(?:x) operators to work with. Consider the sample expression /(?:foo){1,2}/. If the
expression was /foo{1,2}/, the {1,2} characters would apply only to the last 'o' in
'foo'. With the non-capturing parentheses, the {1,2} applies to the entire word 'foo'.
Special characters in regular expressions.
Character Meaning
Where n and m are positive i tegers and n <= m. Matches at least n and at most m
occurrences of the preceding character. When m is omitted, it's treated as ∞.
{n,m}
For example, /a{1,3}/ matches nothing in "cndy", the 'a' in "candy," the first two a's
in "caandy," and the fi st th ee a's in "caaaaaaandy". Notice that when matching
"caaaaaaandy", the m tch is "aaa", even though the original string had more a's in it.
Character set. This pattern type matches any one of the characters in the brackets,
including escape sequences. Special characters like the dot(.) and asterisk (*) are
not special inside a character set, so they don't need to be escaped. You can specify
a range of characters by using a hyphen, as the following examples illustrate.
[xyz]
The pattern [a-d], which performs the same match as [abcd], matches the 'b' in
"brisket" and the 'c' in "city". The patterns /[a-z.]+/ and /[\w.]+/ match the entire
string "test.i.ng".
A negated or complemented character set. That is, it matches anything that is not
enclosed in the brackets. You can specify a range of characters by using a
[^xyz] hyphen. Everything that works in the normal character set also works here.
For example, [^abc] is the same as [^a-c]. They initially match 'r' in "brisket" and
'h' in "chop."
Special characters in regular expressions.
Character Meaning
Matches a backspace (U+0008). You need to use square brackets if you want
[\b]
to match a literal backspace character. (Not to be confused with \b.)
Matches a word boundary. A word boundary matches the position where a word
character is not followed or preceeded by another word-character. Note that a
matched word boundary is not included in the match. In other words, the length of
a matched word boundary is zero. (Not to be confused with [\b] )
Examples:
/\bm/ matches the 'm' in "moon" ;
/oo\b/ does not match the 'oo' in "moon", because 'oo' s followed by 'n' which is a
word character;
\b /oon\b/ matches the 'oon' in "moon", because 'oon' is the end of the string, thus
not followed by a word character;
/\w\b\w/ will never match anything, because a word character can never be
followed by both a non-word and a word character.
For example, /\B../ matches 'oo' in "noonday", and /y\B./ matches 'ye' in "possibly
yesterday."
Where X is a character ranging from A to Z. Matches a control character in a string.
\cX
For example, /\cM/ matches control-M (U+000D) in a string.
Matches a digit character. Equivalent to [0-9].
\d
For example, /\d/ or /[0-9]/ matches '2' in "B2 is the suite number."
Matches any non-digit character. Equivalent to [^0-9].
\D
For example, /\D/ or /[^0-9]/ matches 'B' in "B2 is the suite number."
\f Matches a form feed (U+000C).
Special characters in regular expressions.
Character Meaning
Matches a single white space character, including space, tab, form feed, line feed.
Equivalent to [ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a
\s
\u2028\u2029\u202f\u205f\u3000].
For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."
Where n is a positive integer, a back reference to the last substring matching the n
parenthetical in the regular expression (counting left parentheses).
\n
For example, /apple(,)\sorange\1/ matches 'apple, orange,' in "apple, orange, cherry,
peach."
Matches a NULL (U+0000) character. Do not follow this with another digit, because
\0
\0<digits> is an octal escape sequence.
\xhh Matches the character with the code hh (two hexadecimal digits)
\uhhhh Matches the character with the code hhhh (four hexadecimal digits).
Escaping user input to be treated as a literal string within a regular expression can be
accomplished by simple replacement:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
Using parentheses
Parentheses around any part of the regular expression pattern cause that part of the matched
substring to be remembered. Once remembered, the substring can be recalled for other use,
as described in Using Parenthesized Substring Matches.
For example, the pattern /Chapter (\d+)\.\d*/ illustrates additional escaped and special characters
and indicates that part of the pattern should be remembered. It matches precisely the characters
'Chapter ' followed by one or more numeric characters (\d mea s a y umeric character and +
means 1 or more times), followed by a decimal point (which in itself is a special character;
preceding the decimal point with \ means the pattern must look for the literal character '.'),
followed by any numeric character 0 or more times (\d m ans numeric character, * means 0 or
more times). In addition, parentheses are used to rem mb r the first matched numeric characters.
This pattern is found in "Open Chapter 4.3, paragraph 6" and '4' is remembered. The pattern
is not found in "Chapter 3 and 4", because that string does not have a period after the '3'.
To match a substring without causing the matched part to be remembered, within the
parentheses preface the pattern with ?:. For exampl , (?:\d+) matches one or more numeric
characters but does not remember the matched charact rs.
Regular expressions are us d with the RegExp methods test and exec and with the String methods
match, replace, s arch, and split. These methods are explained in detail in the JavaScript
reference.
Method Description
A RegExp method that executes a search for a match in a string. It returns an array of
exec
information.
test A RegExp method that tests for a match in a string. It returns true or false.
match A String method that executes a search for a match in a string. It returns an array of
Method Description
A String method that tests for a match in a string. It returns the index of the match, or -1
search
if the search fails.
A String method that executes a search for a match in a string, a d replaces the matched
replace substring with a replacement substring.
A String method that uses a regular expression or a fixed string to break a string into an
split
array of substrings.
When you want to know whether a pattern is found in a string, use the test or search method; for
more information (but slower execution) use the exec or match methods. If you use exec or
match and if the match succeeds, these methods return an array and update properties of the
associated regular expression object and also of the predefined regular expression object,
RegExp. If the match fails, the exec method returns null (which coerces to false).
In the following example, the script uses the exec method to find a match in a string.
If you do not need to access the properties of the regular expression, an alternative way
of creating myArray is with this script:
If you want to construct the regular expression from a string, yet another alternative is this script:
/ "The value of
lastIndex is 5"
However, if you
The following script uses the replace() method to switch the words in the string. For the
replacement text, the script uses the $1 and $2 in the replacement to denote the first and second
parenthesized substring matches.
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
console.log(newstr);
Flag Description
g Global search.
i Case-insensitive search.
m Multi-line search.
y Perform a "sticky" search that matches starting at the current position in the target string.
var re = /pattern/flags;
or
Note that the flags are an integral part of a regular expression. They cannot be added or removed
later.
For example, re = /\w+\s/g creates a regular expression that looks for one or more characters
followed by a space, and it looks for this combination throughout the string.
var re = /\w+\s/g;
This displays ["fee ", "fi ", "fo "]. In this example, you could replace the line:
var re = /\w+\s/g;
with:
The m flag is used to specify that a multiline input string should be treated as multiple lines. If
the m flag is used, ^ and $ match at the start or end of any line within the input string instead of
the start or end of the entire string.
Date Object
Both the Date(string) constructor and parse() method work on exactly the the same date formats.
The difference is that the constructor creates a Date obj ct, while the static Date.parse() method
returns a number - more precisely, the number of milliseconds since Jan 1, 1970:?
Either of the above will also work for numeric date formats, assuming that you're dealing with a
supported format, such as yyyy/MM/dd, yyyy/M/d, yyyy/MM/dd hh:mm, or yyyy/mm/dd
hh:mm:ss. Aside from that short list, most other date formats - with the notable exception of long
date formats like Mon, January 1, 2000, which make excellent candidates for string parsing - will
result in unpredictable results at best. Oddly, according to Wikipedia, the standard Calendar date
representation allo s both the YYYY-MM-DD and YYYYMMDD formats, as well as the year-
month-only YYYY-MM format.
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c)
Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a closing parenthesis.
<script type="text/javascript">
<!--
window.print(;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as the
syntax error is affected and the rest of the code in other threads gets executed assuming nothing
in them depends on the code containing the error.
Runtime Errors
Runtime errors, also called exceptions, occur during x cution (after compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct, but at
runtime, it is trying to call a method that does not exist.
<script type="text/javascript">
<!--
window.printme();
//-->
</script>
Exceptions also affect the thr ad in which they occur, allowing other JavaScript threads to
continue normal execution.
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the result
of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives
your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of
logic you ant to put in your program.
The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript
syntax errors.
<script type="text/javascript">
<!--
try {
/ Code to run
[break;]
}
catch ( e ) {
/ Code to run if an exception occurs
[break;]
}
[ finally {
/ Code that is always executed regardless of
/ an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or one finally block (or one of
both). When an exception occurs in the try block, the exception is placed in e and the catch
block is executed. The optional finally block executes unconditionally after try/catch.
Examples
Here is an example where we are trying to call a non-existing function which in turn is raising an
exception. Let us see how it b haves without try...catch−
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
Event Handler
An event handler executes a segment of a code based on certa eve ts occurring within the
application, such as onLoad, onClick. JavaScript event hande s can be divided into two parts:
interactive event handlers and non-interactive event handl rs. An interactive event handler is the
one that depends on the user interactivity with the form or the document. For example,
onMouseOver is an interactive event handler because it d p nds on the users action with the
mouse. On the other hand non-interactive event ha dler would be onLoad, because this event
handler would automatically execute JavaScript code without the user's interactivity. Here are all
the event handlers available in JavaScript:
onAbort:
An onAbort event handler executes JavaScript code when the user aborts loading an image.
<HTML>
<TITLE>Example of onAbort Event Handler</TITLE>
<HEAD>
</HEAD>
<BODY>
<H3>Example of onAbort Event Handler</H3>
<b>Stop the loading of this image and see what happens:</b><p>
<IMG SRC="reaz.gif" onAbort="alert('You stopped the loading the image!')">
</BODY>
</HTML>
Here, an alert() method is called using the onAbort event handler when the user aborts loading
the image.
onBlur:
An onBlur event handler executes JavaScript code when input focus leaves the field of a text,
textarea, or a select option. For windows, frames and framesets the event handler executes
JavaScript code when the window loses focus. In windows you need to specify the event handler
in the <BODY> attribute. For example:
<BODY BGCOLOR='#ffffff' onBlur="document.bgcolor='#000000'">
Note: On a Windows platform, the onBlur event do s not work with <FRAMESET>.
See Example:
<HTML>
<TITLE>Example of onBlur Event Handler</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function valid(form){
var input=0;
input=document.myform.d ta.v lue;
if (input<0){
alert("Please input a value that is less than 0");
}
}
</SCRIPT>
</HEAD>
<BODY>
<H3> Example of onBlur Event Handler</H3>
Try inputting a value less than zero:<br>
<form name="myform">
<input type="text" name="data" value="" size=10 onBlur="valid(this.form)">
</form>
</BODY>
</HTML>
In this example, 'data' is a text field. When a user attempts to leave the field, the onBlur event
handler calls the valid() function to confirm that 'data' has a legal value. Note that the keyword
this is used to refer to the current object.
onChange:
The onChange event handler executes JavaScript code when input focus exits the field after the
user modifies its text.
See Example:
<HTML>
<TITLE>Example of onChange Event Handler</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function valid(form){
var input=0;
input=document.myform.data.value;
alert("You have changed the value from 10 to " + input );
}
</SCRIPT>
</HEAD>
<BODY>
<H3>Example of onChange Event Handler</H3>
Try changing the value from 10 to som thing else:<br>
<form name="myform">
<input type="text" name="data" value="10" size=10 onChange="valid(this.form)">
</form>
</BODY>
</HTML>
This is how a servlet execution takes place when client (browser) makes a request to the
webserver.
a) Servlet Interface
To write a servlet we need to implement Servlet interface. Servlet interface can be implemented
directly or indirectly by extending GenericServlet or HttpServlet class.
The first time a servlet is invoked, the init method is called. It is called only once during the
lifetime of a servlet. So, we can put all your initialization code here.
The Service method is used for handling the client request. As the client request reaches to the
container it creates a thread of the servlet object, and request and response object are also
created. These request and response object are then passed as parameter to the service method,
which then process the client request. The service method in turn calls the doGet or doPost
methods (if the user has extended the class from HttpServlet ).
c) Number of instances
A servlet life cycle can be defined s the entire process from its creation till the destruction. The
following are the paths follow d by a servlet
The init method is designed to be called only once. It is called when the servlet is first created,
and not called again for each user request. So, it is used for one-time initializations, just as with
the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but
you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used throughout the life of the servlet.
The service() method is the main method to perform the actual task. The servlet container (i.e.
web server) calls the service() method to handle requests coming from the client( browsers) and
to write the formatted response back to the client.
Each time the server receives a request for a servlet, the s rver spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
The service () method is call d by the container and service method invokes doGe, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method
but you override either doGet() or doPost() depending on what type of request you receive from
the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is
the signature of these two methods.
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
// Servlet code
}
A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write cookie
lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this:
Architecture Digram:
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
session
A session is a conversation between the server and a client. A conversation consists series of
continuous request and response.
When there is a series of continuous request and response from a same client to a server, the
server cannot identify from which client it is getting requests. Because HTTP is a stateless
protocol.
When there is a need to maintain the conversational state, session tracking is needed. For
example, in a shopping cart application a client keeps on adding items into his cart using
multiple requests. When every request is made, the s rv r should identify in which client’s cart
the item is to be added. So in this scenario, there is a c rtain need for session tracking.
Solution is, when a client makes a request it should ntroduce itself by providing unique
identifier every time. There are five different methods to achieve this.
1. User authorization
2. Hidden fields
3. URL rewriting
4. Cookies
5. Session tracking API
The first four methods are traditionally used for session tracking in all the server-side
technologies. The session tracking API method is provided by the underlying technology (java
servlet or PHP or like ise). Session tracking API is built on top of the first four methods.
1. User Authorization
Users can be authorized to use the web application in different ways. Basic concept is that the
user will provide username and password to login to the application. Based on that the user can
be identified and the session can be maintained.
2. Hidden Fields
<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>
Hidden fields like the above can be inserted in the webpages and information can be sent to the
server for session tracking. These fields are not visible directly to the user, but can be viewed
using view source option from the browsers. This type doesn’t need any special configuration
from the browser of server and by default available to use for session tracking. This cannot be
used for session tracking when the conversation included static resources lik html pages.
3. URL Rewriting
4. Cookies
Cookies are the mostly used technology for session tracking. Cookie is a key value pair of
information, sent by the server to the browser. This should be saved by the browser in its space
in the client computer. Whenever the browser se ds a request to that server it sends the cookie
along with it. Then the server can identify the cl ent using the cookie. In java, following is the
source code snippet to create a cookie:
Session tracking is easy to impleme t a d maintain using the cookies. Disadvantage is that, the
users can opt to disable cookies using their browser preferences. In such case, the browser will
not save the cookie at client computer and session tracking fails.
Session tracking API is built on top of the first four methods. This is inorder to help the
developer to minimize the overhead of session tracking. This type of session tracking is provided
by the underlying technology. Lets take the java servlet example. Then, the servlet container
manages the session tracking task and the user need not do it explicitly using the java servlets.
This is the best of all methods, because all the management and errors related to session tracking
will be taken care of by the container itself.
Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java
servlets can use the session object to store and retrieve java objects across the session. Session
tracking is at the best when it is implemented using session tracking api.
package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet
{ private static final long serialVersionUID =
1L; private final String userID = "Pankaj";
private final String password = "journaldev";
JSP
JSP technology is used to create web application just like Servlet technology. It can be thought
of as an extension to servlet because it provides more functionality than servlet such as
expression language, jstl etc.
A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than
servlet because we can separate designing and development. It provides some additional features
such as Expression Language, Custom Tag etc.
Advantage of JSP over Servlet
There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of servlet in
JSP. In addition to, we can use implicit objects, predefin d tags, expression language and
Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation
logic. In servlet technology, we mix our busi ess logic with the presentation logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
Moreover, we can use EL, implicit objects etc.
To create the first jsp pag , write some html code as given below, and save it by .jsp extension.
We have save this file as index.jsp. Put it in a folder and paste the folder in the web-apps
directory in apache tomcat to run the jsp page.
index.jsp
Let's see the simple example of JSP, here we are using the scriptlet tag to put java code in the
JSP page. We ill learn scriptlet tag later.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
No, there is no need of directory structure if you don't have class files or tld files. For example,
put jsp files in a folder directly and deploy that folder.It will be ru i g fine.But if you are using
bean class, Servlet or tld file then directory structure is required.
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags
which encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags
for manipulating XML documents, internationalization tags, and SQL tags. It also
provides a framework for integrating existing custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into followi g JSTL tag
library groups that can be used when creating a JSP page:
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions
If you are using Apache Tomcat container then follow the following two simple steps:
Download the binary distribution from Apache Standard Taglib and unpack
the compressed file.
To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the
JAR files in the distribution's 'lib' dir ctory to your application's
webapps\ROOT\WEB-INF\lib directory.
To use any of the libraries, you must include a <taglib> directive at the top of each JSP that
uses the library.
Core Tags:
The core group of tags are the most frequently used JSTL tags. Following is the syntax to
include
JSTL Core library in your JSP:
Tag Description
<c:out > Like <%= ... >, but for expressions.
<c:set > Sets the result of an expression evaluation in a 'scope'
<c:remove > Removes a scoped variable (from a particular scope, if specified).
<c:when> Subtag of <choose> that includes its body if its condition evalutes
to 'true'.
Subtag of <choose> that follows <when> tags and runs only if all
<c:otherwise >
of the prior conditions evaluated to 'false'
Retrieves an absolute or relative URL and exposes its contents to
<c:import>
either the page, a String in 'var', or a Reader in 'varReader'.
The basic iteration tag, accepting ma y different collection types
<c:forEach >
and supporting subsetting and other functionality .
<c:forTokens> Iterates over tokens, separat d by the supplied delimeters.
<c:param> Adds a parameter to a containing 'import' tag's URL.
<c:redirect > Redirects to a new URL.
<c:url> Creates a URL w th opt onal query parameters
Formatting tags:
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Web sites. Followi g is the syntax to include Formatting library in your JSP:
<%@ taglib prefix="fmt"
uri="http://java.sun.com/jsp/jstl/fmt" %>
Tag Description
<fmt:formatNumber> To render numerical value with specific precision or format.
Parses the string representation of a number, currency, or
<fmt:parseNumber>
percentage.
<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern
<fmt:parseDate> Parses the string representation of a date and/or time
<fmt:bundle> Loads a resource bundle to be used by its tag body.
<fmt:setLocale> Stores the given locale in the locale configuration variable.
Loads a resource bundle and stores it in the named scoped variable
<fmt:setBundle>
or the bundle configuration variable.
Specifies the time zone for any time formatting or parsing actions
<fmt:timeZone>
nested in its body.
<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable
<fmt:message> To display an internationalized message.
<fmt:requestEncoding> Sets the request character encoding
SQL tags:
The JSTL SQL tag library provides tags for interacting with relational databases
(RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
Tag Description
<sql:setDataSource> Creates a simple DataSource suitable only for prototyping
Executes the SQL query defined in its body or through the sql
<sql:query>
attribute.
Executes the SQL update defined in its body or through the
<sql:update>
sql attribute.
<sql:param> Sets a parameter in an SQL statement to the specified value.
Sets a pa ameter in an SQL statement to the specified java.util.Date
<sql:dateParam>
v lue.
Provides nested database action elements with a shared
<sql:transaction >
Connection, set up to execute all statements as one transaction.
XML tags:
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.
Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML data. This includes
parsing XML, transforming XML data, and flow control based on XPath expressions.
Before you proceed with the examples, you would need to copy following two XML and
XPath related libraries into your <Tomcat Installation Directory>\lib:
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.
Use to parse XML data specified either via an attribute or in the
<x:parse>
tag body.
<x:set > Sets a variable to the value of an XPath express on.
Evaluates a test XPath expression and if it is true, it processes its
<x:if >
body. If the test condition is false, the body is ignored.
<x:forEach> To loop over nodes in an XML docume t.
Simple conditional tag that establ shes a context for mutually
<x:choose> exclusive conditional operations, marked by <when> and
<otherwise>
Subtag of <choose> that includes its body if its expression evalutes
<x:when >
to 'true'
Subtag of <choose> that follows <when> tags and runs only if all
<x:otherwise > of the prior condit ons evaluated to 'false'
<x:transform > Applies an XSL transformation on a XML document
Use along with the transform tag to set a parameter in the XSLT
<x:param > styleshe t
JSTL Functions:
JSTL includes a number of st nd rd functions, most of which are common string manipulation
functions. Following is the syntax to include JSTL Functions library in your JSP:
To start off the exploration of HTML forms, it's best to start with a small form and expand from
there. Also, it's better to start with a JSP rather than a servlet, because it is easier to write out the
HTML. Most of the form handling for JSPs a d servlets is identical, so after you know how to
retrieve form information from a JSP, you know how to do it from a servlet. Listing 3.1 shows an
HTML file containing a simple input form that calls a JSP to handle the form.
<html>
<body>
The SimpleFormHandler JSP does little more than retrieve the form var ables and print out their
values. Listing 3.2 shows the contents of SimpleFormHandler.jsp, which you can see is pretty
short.
<html>
<body>
<%
</body>
</html>
Unit – IV
PHP
When working with data values in PHP, we need some convenient way to store these values so that we
can easily access them and make reference to them whenever necessary. This is where PHP variables
come in. It is often useful to think of variables as computer memory locations where data is to be stored.
When declaring a variable in PHP it is assigned a name that can be used to reference it in other
locations in the PHP script. The value of the variable can be accessed, the value can be changed, and the
type of variable can be altered all by referencing the name assigned at variable creation time.
Before learning how to declare a variable in PHP it is first important to understand some rules about
variable names (also known as variable naming conventions). All PHP variable names must be pre-fixed
with a $. It is this prefix which informs the PHP pre-processor that t s dealing with a variable. The first
character of the name must be either a letter or an underscore ( ). The remaining characters must
comprise only of letters, numbers or underscores. All other charact rs are deemed to be invalid for use in
a variable name. Let's look at some valid and invalid PHP variable names:
$_myName // valid
$myName // valid
$__myvar // valid
$myVar21 // valid
$_1Big // invalid - underscore must be follow d by a letter
$1Big // invalid - must begin with a letter or underscore
$_er-t // invalid contains non alpha umeric character (-)
Variable names in PHP are case-s nsitive. This means that PHP considers $_myVariable to be a
completely different variable to one that is named ''$ myvariable.
Values are assigned to variables using the PHP assignment operator. The assignment operator is
represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the
left of the expression, followed by the assignment operator. The value to be assigned is then placed to
the right of the assignment operator. Finally the line, as with all PHP code statements, is terminated
with a semi-colon (;).
$myShape = "Circle";
We have now declared a variable with the name myShape and assigned a string value to it of "Circe".
We can similarly declare a variable to contain an integer value:
$numberOfShapes = 6;
The above assignment creates a variable named numberOfShapes and assigns it a numeric value of 6.
Once a variable has been created, the value assigned to that variable can be changed at any time
using the same assignment operator approach:
<?php
$numberOfShapes = 6; // Set initial values
$myShape = "Circle";
$numberOfShapes = 7; // Change the initial values to new values
$myShape = "Square";
?>
Now that we have learned how to create a variable a d assign an initial value to it we now need to look
at how to access the value currently assigned to a var able. In practice, accessing a variable is as
simple as referencing the name it was given when it was created.
For example, if we want to display the value which we assigned to our numberOfShapes variable we can
simply reference it in our echo command:
<?php
echo "The number of shapes is $numbe OfShapes.";
?>
<?php
echo "$myShape is the value of the current shape.";
?>
The examples we have used for accessing variable values are straightforward because we have always
had a space character after the variable name. The question arises as to what should be done if we
need to put other characters immediately after the variable name. For example:
<?php
Unfortunately PHP will see the th on the end of the $numberOfShapes variable name as being part of the
name. It will then try to output the value of a variable called $numberOfShapesth, which does not exist.
This results in nothing being displayed for this variable:
Fortunately we can get around this issue by placing braces ({ and }) around the variable name
to distinguish the name from any other trailing characters:
<?php
echo "The Circle is the ${numberOfShapes}th
shape"; ?>
To give us the desired output:
PHP comes standard with many functio s a d constructs. There are also functions that require specific
PHP extensions compiled in, othe wise fatal "undefined function" errors will appear. For example, to use
image functions such as imagecre tetruecolor(), PHP must be compiled with GD support. Or, to use
mysql_connect(), PHP must be compiled with MySQL support. There are many core functions that are
included in every version of PHP, such as the string and variable functions. A call to phpinfo() or
get_loaded_extensions() will show which extensions are loaded into PHP. Also note that many
extensions are enabled by default and that the PHP manual is split up by extension. See the
configuration, installation, and individual extension chapters, for information on how to set up PHP.
Reading and understanding a function's prototype is explained within the manual section titled how to
read a function definition. It's important to realize what a function returns or if a function works directly
on a passed in value. For example, str_replace() will return the modified string while usort() works on
the actual passed in variable itself. Each manual page also has specific information for each function
like information on function parameters, behavior changes, return values for both success and failure,
and availability information. Knowing these important (yet often subtle) differences is crucial for
writing correct PHP code.
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
Syntax
function functionName() {
code to be executed;
}
In the example below, we create a function named "writ Msg()". The opening curly brace ( { ) indicates
the beginning of the function code and the closing curly brace ( } ) indicates the end of the function.
The function outputs "Hello world!". To call the function, just write its name:
Example
<?php
function writeMsg() {
echo "Hello world!";
}
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you ant, just seperate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function
is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs
several different first names, but an equal last name:
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
Connecting to a Database
PDO will work on 12 different database systems, where as MySQLi will only work with
MySQL databases.
So, if you have to s itch your project to use another database, PDO makes the process easy. You only
have to change the connection string and a few queries. With MySQLi, you will need to rewrite the
entire code - queries included.
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are
very important for web application security.
In this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:
MySQLi (object-oriented)
MySQLi (procedural)
PDO
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when
php5 mysql package is installed.
PDO Installation
Before we can access data in the MySQL database, we need to be able to connect to the server:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect error);
}
echo "Connected successfully";
?>
<?php
$servername = "localhost";
$username = "username";
$pass ord = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $user ame, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR ERRMODE, PDO::ERRMODE EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
The connection will be closed automatically when the script ends. To close the connection before,
use the following:
$conn->close();
mysqli_close($conn);
Example (PDO)
$conn = null;
Using Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.
Syntax
Only the name parameter is required. All other parameters are optional.
The following example creates a cookie named "user" w th the value "John Doe". The cookie will expire
after 30 days (86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select
the directory you prefer).
We then retrieve the value of the cookie "us r" (using the global variable $ COOKIE). We also use the
isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($ COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not
set!"; } else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Modify a Cookie Value
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie name])) {
echo "Cookie named '" . $cookie name . "' is not set!";
} else {
echo "Cookie '" . $cookie name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
/ set the expiration date to one hour
ago setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
The following example creates a small script that checks whether cookies are enabled. First, try to
create a test cookie with the setcookie() function, then count the $_COOKIE array var able:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Regular Expressions
Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the
foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another string, you can replace one
string by another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each corresponding to a
certain type of regular expression. You can use any of them based on your comfort.
The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression:
various elements (operators) are combined to form more complex expressions.
The simplest regular expression is one that matches a single character, such as g, inside
strings such as g, haggle, or bag.
Lets give explaination for few concepts being used in POSIX regular express on. After
that we will introduce you wih regular expression related functions. Brackets
Brackets ([]) have a special meaning when used in the context of egular expressions.
They are used to find a range of characters.
Expression Description
The ranges shown above are gener l; you could also use the range [0-3] to match any
decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase
character ranging from b through v. Quantifiers
The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each pecial character having a specific connotation. The
+, *, ?, {int. range}, and $ flags all follow a character sequence.
Expression Description
p? It matches any string containing zero or more p's. This is just an alternative way to use p*.
Examples
Following examples will clear your concepts about matching chracters.
Expression Description
[^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A
through Z.
p.p It matches any string containing p, followed by any character, in turn followed by another p.
p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp.
Expression Description
[[:alnum:]] It matches any string containing alphanumeric characters aA through zZ and 0 through 9.
Function Description
ereg() The ereg() function searches a string specified by string for a string specified by pattern,
returning true if the pattern is found, and false otherwise.
ereg_replace() The ereg_replace() function searches for string specified by pattern and replaces pattern
with replacement if found.
eregi() The eregi() function searches throughout a string specified by pattern for a string specified
by string. The search is not case sensitive.
eregi_replace() The eregi replace() function operates exactly like ereg_replace(), except that the search
for pattern in string is not case sensitive.
split() The split() function will divide a string nto various elements, the boundaries of each
element based on the occurrence of patte n in string.
spliti() The spliti() function operates xactly in the same manner as its sibling split(), except that
it is not case sensitive.
sql_regcase() The sql regcase() funct on can be thought of as a utility function, converting each
character in the input parameter string into a bracketed expression containing two
characters.
Character Description
a single
. character
Modifiers
Several modifiers are available that can make your work with regexps much easier, like
case sensitivity, searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive
m Specifies that if the string has newline or carr age
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
o Evaluates the expression only once
s Allows use of . to match a ewli e character
x Allows you to use white space in the expression for clarity
g Globally finds all matches
cg Allows a search to continue even after a global match fails
preg match() The preg_match() function searches string for pattern, returning true if pattern exists,
and false otherwise.
preg match all() The preg_match_all() function matches all occurrences of pattern in string.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular
expressions can be used in the pattern and replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that regular expressions
are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements
matching the regexp pattern.
XML
XML is a markup language that looks a lot like HTML. An XML document s plain text
and contains tags delimited by < and >.There are two big differences between XML and
HTML:
XML doesn't define a specific set of tags you must use.
XML gives you a lot more freedom than HTML. HTML has a ce tain set of tags: the
<a></a> tags surround a link, the <p> startsa paragraph and so on. An XML document,
however, can use any tags you want. Put <rating></rating> tags around a movie rating,
>h ight></height> tags around someone's height. Thus XML gives you option to device
your own tags.
XML is very strict when it comes to document structure. HTML lets you play fast and
loose with some opening and closing tags. BUt this is not the case with XML.
This is not a valid XML document because there are no closing </li> tags to match up
with the three opening <li> tags. Every opened tag in an XML document must be closed.
</ul>
Parsing an XML Document
PHP 5's new SimpleXML module makes parsing an XML document, well, simple. It turns an XML
document into an object that provides structured access to the XML.
To create a SimpleXML object from an XML document stored in a string, pass the string to
simplexml_load_string( ). It returns a SimpleXML object.
Example
Try out following example:
<?php
$channel =<<<_XML_
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;
NOTE: You can use function simplexml_load_file( filename) if you have XML content in a file.
For a complete detail of XML parsing function check PHP Function Reference.
SimpleXML is good for parsing existing XML documents, but you can't use it to create a new one from
scratch.
The easiest way to generate an XML document is to build a PHP array whose structure mirrors that of
the XML document and then to iterate through the array, printing each element with appropriate
formatting.
Example
Try out following example:
<?php
<channel>
<title>What's For Dinner</title>
<link>http://menu.example.com/</link>
<description>Choose what to eat
tonight.</description> </channel></html>
DOM
A DOM (Document Object Model) defines a standard way for accessing and manipulating documents.
The XML DOM defines a standard way for accessing and manipulating XML documents.
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.
You can learn more about the XML DOM in our XML DOM tutorial.
The HTML DOM defines a standard way for accessing and manipulating HTML documents.
All HTML elements can be accessed through the HTML DOM.
You can learn more about the HTML DOM in our JavaScript tutor al.
The following example parses an XML document ("note.xml") into an XML DOM object and then
extracts some info from it with a JavaScript:
Example
<html>
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></sp n><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</div>
<script>
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","note.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
The following example parses an XML string into an XML DOM object and then extracts some info
from it with a JavaScript:
Example
<html>
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</div>
<script>
txt="<note>";
txt=txt+"<to>Tove</to>";
txt=txt+"<from>Jani</from>";
txt=txt+"<heading>Reminder</heading>";
txt=txt+"<body>Don't forget me this weekend!</body>";
txt=txt+"</note>";
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);
}
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
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)>
!DOCTYPE note defines that the root element of the document is note
!ELEMENT note defines that the note element must contain four 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 charact rs and character strings, used in the
document:
Example
<!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>& riter; ©right;</footer>
</note>
With a DTD, independent groups of people can agree on a standard for interchanging data.
With a DTD, you can verify that the data you receive from the outside world is valid.
XSLT (eXtensible Stylesheet Language Transformations) is the recommended style sheet language
for XML.
XSLT is far more sophisticated than CSS. With XSLT you can add/remove elements and attributes to
or from the output file. You can also rearrange and sort elements, perform tests and make decisions
about which elements to hide and display, and a lot more.
XSLT Example
We will use the following XML document:
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of r al maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles cover d with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffl s</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>