Vous êtes sur la page 1sur 53

What is XML?

• XML stands for Extensible Markup Language


• XML is a markup language much like HTML
• XML was designed to carry data, not to display data
• XML tags are not predefined. We must define our own tags
• XML is a W3C Recommendation

Comparison with HTML

XML is not a replacement for HTML.

XML and HTML were designed with different goals:

• XML was designed to transport and store data, with focus on what data is.
• HTML was designed to display data, with focus on how data looks.

HTML is about displaying information, while XML is about carrying information.

XML was created to structure, store, and transport information.

XML is nothing special. It is just plain text. Software that can handle plain text can also handle
XML.

XML is a complement to HTML.

It is important to understand that XML is not a replacement for HTML. In most web
applications, XML is used to transport data, while HTML is used to format and display the data.

XML is a software- and hardware- independent tool for carrying information.

XML is used in many aspects of web development, often to simplify data storage and
sharing.

Features of XML

XML Separates Data from HTML

If we need to display dynamic data in our HTML document, it will take a lot of work to
edit the HTML each time the data changes.

With XML, data can be stored in separate XML files. This way we can concentrate on
using HTML for layout and display, and be sure that changes in the underlying data will not
require any changes to the HTML.

With a few lines of JavaScript, we can read an external XML file and update the data
content of our HTML.

1
XML Simplifies Data Sharing

In the real world, computer systems and databases contain data in incompatible formats.

XML data is stored in plain text format. This provides a software-and hardware-
independent way of storing data.

This makes it much easier to create data that different applications can share.

XML Simplifies Data Transport

With XML, data can easily be exchanged between incompatible systems.

One of the most time-consuming challenges for developers is to exchange data between
incompatible systems over the Internet.

Exchanging data as XML greatly reduces this complexity, since the data can be read by
different incompatible applications.

XML Simplifies Platform Changes

Upgrading to new systems (hardware or software platforms), is always very time


consuming. Large amounts of data must be converted and incompatible data is often lost.

XML data is stored in text format. This makes it easier to expand or upgrade to new
operating systems, new applications, or new browsers, without losing data.

XML Makes Our Data More Available

Since XML is independent of hardware, software and application, XML can make our
data more available and useful.

Different applications can access our data, not only in HTML pages, but also from XML
data sources.

With XML, our data can be available to all kinds of “reading machines” (Handheld
computers, voice machines, news feeds, etc), and make it more available for blind people, or
people with other disabilities.

XML is Used to Create New Internet Languages

A lot of new Internet languages are created with XML.

Here are some examples:

• XHTML the latest version of HTML


• WSDL for describing available web services
• WAP and WML as markup languages for handheld devices

2
• RSS languages for news feeds
• RDF and OWL for describing resources and ontology
• SMIL for describing multimedia for the web.

Document Type Definition (DTD)

A Document Type Definition (DTD) defines the legal building blocks of an XML
document. It defines the document structure with a list of legal elements and attributes.

A DTD can be declared inline inside an XML document, or as an external reference.

Internal DTD Declaration

If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE
definition with the following syntax:

<! DOCTYPE root-element [element-declarations]>

Examples XML document with an internal DTD:

<?xml version=”1.0”?>
<!DOCTYPE note [
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don’t forget me this weekend</body>
</note>

Open the XML file above in our browser (select “view source” or “view page source” to view
the DTD)

The DTD above is interpreted like this:


• !DOCTYPE note defines that the root elements of this document is note
• !ELEMENT note defines that the note element contains four elements: “to, from,
heading, body”
• !ELEMENT to defines the to element to be of type “#PCDATA”
• !ELEMENT from defines the form 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”

3
External DTD Declaration

If the DTD is declared in an external file, it should be wrapped in a DOCTYPE definition


with the following syntax:

<!DOCTYPE root-element SYSTEM “filename”>

This is the same XML document as above, but with an external DTD (Open it, and select
view source):

<?xml version=”1.0”?>
<!DOCTYPE note SYSTEM “note.dtd”>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don’t forget me this weekend!</body>
</note>

And this is the file “note.dtd” which contains the DTD:

<!ELEMENT note (to, from, heading, body)>


<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>

Why Use a DTD?

With a DTD, each of our XML files can carry a description of its own format.

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

Our application can use a standard DTD to verify that the data we receive from the
outside world is valid.

We can also use a DTD to verify our own data.

XML Elements

An XML element is everything from (including) the element’s start tag to (including) the
element’s end tag.

4
An element can contain other elements, simple text or a mixture of both. Elements can
also have attributes.

<bookstore>
<book category = “CHILDREN”>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category = “WEB”>
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

In the example above, <bookstore> and <book> have element contents, because they
contain other elements. <author> has text content because it contains text.

In the example above only <book> has an attribute (category = “CHILDREN”).

XML Naming Rules

XML elements must follow these naming rules:

• Names can contain letters, numbers, and other characters


• Names cannot start with a number or punctuation character
• Names cannot start with the letters xml ( or XML, or Xml, etc)
• Names cannot contain spaces

Any name can be used, no words are reserved.

Best Naming Practices

Make names descriptive. Names with an underscore separator are nice: <first_name>,
<last_name>.

Names should be short and simple, like this: <book_title> not like this:
<the_title_of_the_book>.

Avoid “-“ characters. If we name something “first-name,” some software may think we
want to subtract name from first.

Avoid “.“ characters. If we name something “first.name,” some software may think the
“name” is a property of the object “first.”

5
Avoid “:” characters. Colons are reserved to be used for something called
namespaces(more later).
XML documents often have a corresponding database. A good practice is to use the
naming rules of our database for the elements in the XML documents.

Non-English letters like éòá are perfectly legal in XML, but watch out for problems if
our software vendor doesn’t support them.

XML Elements are Extensible

XML elements can be extended to carry more information.

Look at the following XML example:


<note>
<to>Tove</to>
<from>Jani</from>
<body>Don’t forget me this weekend!</body>
</note>

Let’s imagine that we created an application that extracted the <to>, <from>, and <body>
elements from the XML document to produce this output:

MESSAGE

To: Tove
From: Jani

Don’t forget me this weekend!

Imagine that the author of the XML document added some extra information to it:
<note>
<date>2008-01-10</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don’t forget me this weekend!</body>
</note>

XML Content Creation

The syntax rules of XML are very simple and logical. The rules are easy to learn, and easy to
use.

All XML Elements must have a closing tag.

In HTML, we will often see elements that don’t have a closing tag:

<p>This is a paragraph
<p> This is another paragraph
6
In XML, it is illegal to omit the closing tag. All elements must have a closing tag:

<p>This is a paragraph</p>
<p> This is another paragraph</p>

Note: We might have noticed from the previous example that the XML declaration did not have
a closing tag. This is not an error. The declaration is not a part of the XML document itself, and
it has no closing tag.

XML Tags are Case Sensitive

XML elements are defined using XML tags.

XML tags are case sensitive. With XML, the tag <Letter> is different from the tag <letter>.

Opening and closing tags must be written with the same case:

<Message>This is incorrect</message>
<message>This is correct</message>

Note: “Opening and closing tags” are often referred to as “Start and end tags”. Use whatever we
prefer. It is exactly the same thing.

XML Elements Must be Properly Nested

In HTML, we might see improperly nested elements:


<b><i>This text is bold and italic</b></i>
In XML, all elements must be properly nested within each other:

<b><i>This text is bold and italic</i></b>

In the example above, “Properly nested” simply means that since the <i> element is opened
inside the <b> element, it must be closed inside the <b> element.

XML Documents Must Have a Root Element

XML documents must contain one element that is the parent of all other elements. This element
is called the root element.

<root>
<child>
<subchild>…</subchild>
</child>
</root>

7
XML Attributes

XML elements can have attributes in the start tag, just like HTML.

Attributes provide additional information about elements.

From HTML we will remember this: <img src= “computer.gif”>. The “src” attribute provides
additional information about the <img> element.

In HTML (and in XML) attributes provide additional information about elements:


<img src=”computer.gif”>
<a href=”demo.asp”>

Attributes often provide information that is not a part of the data. In the example below, the file
type is irrelevant to the data, but important to the software that wants to manipulate the element:

<file type= “gif”>computer.gif</file>

XML Attributes Must be Quoted

Attribute values must always be enclosed in quotes, but either single or double quotes can be
used. For a person’s sex, the person tag can be written like this:

<person sex = “female”>


or like this:

<person sex=’female’>

If the attribute value itself contains double quotes we can use single quotes, like in this example:
<gangster name=’George “Shotgun” Ziegler’>

or we can use character entities:

<gangster name=”George &quot;Shotgun&quot; Ziegler”>

XML Elements vs. Attributes

Take a look at these examples:

<person sex = “female”>


<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

8
<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

In the first example sex is an attribute. In the last, sex is an element. Both examples provide the
same information.

There are no rules about when to use attributes and when to use elements. Attributes are handy in
HTML. In XML my advice is to avoid them. Use elements instead.

Avoid XML Attributes?

Some of the problems with using attributes are:

• Attributes cannot contain multiple values(elements can)


• Attributes cannot contain tree structures(elements can)
• Attributes are not easily expandable(for future changes)

Attributes are difficult to read and maintain. Use elements for data. Use attributes for information
that is not relevant to the data.

Entities

Some characters have a special meaning in XML.

If you place a character like “<” inside an XML element, it will generate an error because the
parser interprets it as the start of a new element.

This will generate an XML error:

<message>if salary < 1000 then </message>

To avoid this error, replace the “<” character with an entity reference:

<message>if salary &lt; 1000 then </message>

There are 5 predefined entity references in XML:

&lt; < Less than


&gt; > Greater than
&amp; & Ampersand
&apos; ‘ Apostrophe
&quot; “ Quotation mark

9
XSL

It started with XSL and ended up with XSLT, XPath, and XSL-FO.

It started with XSL.

XSL stands for EXtensible Stylesheet Language.

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

CSS = Style Sheets for HTML

HTML uses predefined tags, and meaning of each tag is well understood.

The <table> tag in HTML defines a table – and a browser knows how to display it.

Adding styles to HTML elements are simple. Telling a browser to display an element in a special
font or color, is easy with CSS.

XSL = Style Sheets for XML

XML does not use predefined tags (we can use any tag-names we like ), and therefore the
meaning of each tag is not well understood.

A <table> tag could mean an HTML table, a piece of furniture, or something else- and a browser
does not know how to display it.

XSL describes how the XML document should be displayed!

XSL – More Than a Style Sheet Language

XSL consists of three parts:

• XSLT – a language for transforming XML documents


• XPath – a language for navigating in XML documents
• XSL-FO- a language for formatting XML documents

Correct Style Sheet Declaration

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

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

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

10
<xsl:stylesheet version = “1.0”
xmlns:xsl=“http://www.w3.org/1999/XSL/Transform”>
or:
<xsl:transform version = “1.0”
xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>

To get access to the XSLT elements, attributes and features we must declare the XSLT
namespace at the top of the document.

The xmlns:xsl=”http://www.w3.org/1999/XSL/Transform” points to the official W3C XSLT


namespace. If we use this namespace, we must also include the attribute version=”1.0”.

Viewing XML Files in Firefox and Internet Explorer:


Open the XML file (typically by clicking on a link) – The XML document will be displayed with
color-coded root and child elements. A plus (+) or minus sign (-) to the left of the elements can
be clicked to expand or collapse the element structure. To view the raw XML source (without the
+ and – signs), select “View Page Source” or “View Source” from the browser menu.

Viewing XML Files in Netscape 6:


Open the XML file, then right-click in XML file and select “View Page Source”. The XML
document will then be displayed with color-coded root and child elements.

Viewing XML Files in Opera 7:


Open the XML file, then right-click in XML file and select “Frame”/ “View Source”. The XML
document will be displayed as plain text.

Create an XSL Style Sheet

Then we create an XSL Style Sheet (“cdcatalog.xsl”) with a transformation template:


<?xml version=”1.0” encoding=”ISO-8859-1”?>

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

<xsl:template match=”/”>
<html>
<body>
<h2>My CD Collection</h2>
<table border = “1”>
<tr bgcolor=”#9acd32”>
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select=”catalog/cd”>
<tr>

11
<td><xsl:value-of select=”title”/></td>
<td><xsl:value-of select=”artist”/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Link the XSL Style Sheet to the XML Document


Add the XSL style sheet reference to our XML document (“cdcatalog.xml”):

<?xml version=”1.0” encoding=”ISO-8859-1”?>


<?xml-stylesheet type=”text/xsl” href=”cdcatalog.xsl”?>
<catalog>
<cd>
<title>Empire Burlesque</title>
<artist>Bob Dylan</artist>
<country>USAL</country>
<company>Columbia</company>
<price>10.90</price>
<year>1985</year>
</cd>
.
.
.
</catalog>

If you have an XSLT compliant browser it will nicely transform our XML into XHTML.

XLINK, XPATH And XPOINTER

XLink defines a standard way of creating hyperlinks in XML documents.


XPath is a language for finding information in an XML document.
XPointer allows the hyperlinks to point to more specific parts (fragments) in the XML
document.

What is XLink?
• XLink is short for XML Linking Language
• XLink is used to create hyperlinks in XML documents
• Any element in an XML document can behave as a link
• XLink supports simple links (like HTML) and extended
XQuery Xpointer XLink links (for linking multiple resources together)
• With XLink, the links can be defined outside the linked
files
Xpath

XSLT 12
• XLink is a W3C Recommendation
What is XPath?
• XPath is a syntax for defining parts of an XML
document
• XPath uses path Expression to navigate in XML
XQuery XPointer XLink doucments
• XPath contains a library of standard functions
Xpath • XPath is a major element in XSLT
• XPath is a W3C Recommendation
XSLT

What is XPointer?
• XPointer is a short for XML Pointer Language
• XPointer allows the links to point to specific parts of
XQuery XPointer XLink an XML doucment
• XPointer uses XPath expressions to navigate in the
Xpath XML document
• XPointer is a W3C Recommendation
XSLT

XLink Syntax

In HTML, we know (and all the browsers know!) that the <a> element defines a hyperlink.
However, this is not how it works with XML. In XML documents, we can use whatever element
names we want-therefore it is impossible for browsers to predict what hyperlink elements will be
called in XML documents.

The Solution for creating links in XML documents was to put a marker on elements that should
acts as hyperlinks.

Below is a simple example of how to use XLink to create links in an XML document:

<?xml version=”1.0”?>

<homepages xmlns:xlink=”http://www.w3.org/1999/xlink”>

<homepage xlink:type=”simple”
xlink:href=”http://www.w3schools.com”>Visit W3Schools</homepage>

<homepage xlink:type=”simple”
xlink:href=”http://www.w3.org”>Visit W3C</homepage>

</homepages>

13
To get access to the XLink attributes and features we must declare the XLink namespace at the
top of the document.

The XLink namespace is: ”http://www.w3.org/1999/xlink”.

The xlink:type and the xlink:href attributes in the <homepage> elements define that the type and
href attributes come form the xlink namespace.

The xlink:type=”simple” creates a simple, two-ended link (means “click from here to go there”).
We will look at multi-ended (multidirectional) links later.

XPath Syntax

XPath uses path expressions to select nodes or node-sets in an XML document. The node is
selected by following a path or steps.

The XML Example Document

We will use the following XML document in the examples below.


<?xml version=”1.0” encoding=”ISO-8859-1”?>

<bookstore>

<book>
<title lang=”eng”>Harry Potter</title>
<price>29.99</price>
</book>

<book>
<title lang=”eng”>Learning XML</title>
<price>39.95</price>
</book>

</bookstore>

Selecting Nodes
XPath uses path expressions to select nodes in an XML document. The node is selected by
following a path or steps. The most useful path expressions are listed below:

Expression Description
nodename Selects all child nodes of the named node
/ Selects from the root node
// Selects nodes in the document from the current node
that match the selection no matter where they are
. Selects the current node

14
.. Selects the parent of the current node
@ Selects attributes
Selecting Unknown Nodes

XPath wildcards can be used to select unknown XML elements.

Wildcard Description
* Matches any element node
@* Matches any attribute node
node() Matches any node of any kind

XPointer Syntax

In HTML, we can create a hyperlink that either points to an HTML page or to a bookmark inside
an HTML page (using #).

Sometimes it is more useful to point to more specific content. For example, let’s say that we
want to link to the third item in a particular list, or to the second sentence of the fifth paragraph.
This is easy with XPointer.

If the hyperlink points to an XML document, we can add an XPointer part after the URL in the
xlink:href attribute, to navigate (with an XPath expression) to a specific palce in the document.

For example, in the example below we use XPointer to point to the fifth item in a list with a
unique id of “rock”:

href=”http://www.example.com/cdlist.xml#id(‘rock’).child(5,item)”

XML Namespaces

XML Namespaces provide a method to avoid element name conflicts.

Name Conflicts

In XML, element names are defined by the developer. This often results in a conflict when trying
to mix XML documents from different XML applications.

This XML carries HTML table information:

<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>

This XML carries information about a table (a piece of furniture):

15
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>

If these XML fragments were added together, there would be a name conflict. Both contain a
<table> element, but the elements have different content and meaning.

An XML parser will not know how to handle these differences.

Solving the Name Conflict Using a Prefix

Name conflicts in XML can easily be avoided using a name prefix.

This XML carries information about an HTML table, and a piece of furniture:

<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>

<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
In the example above, there will be no conflict because the two <table> elements have different
names.

XML Namespaces – The xmlns Attribute

When using prefixes in XML, a so-called namespace for the prefix must be defined.

The namespace is defined by the xmlns attribute in the start tag of an element.

The namespace declaration has the following syntax. xmlns:prefix=”URI”.

16
<root>

<h:table xmlns:h=”http://www.w3.org/TR/html4/”>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f=”http://www.w3schools.com/furniture”>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>

</root>

In the example above, the xmlns attribute in the <table> tag give the h: and f: prefixes a qualified
namespace.

When a namespace is defined for an element, all child elements with the same prefix are
associated with the same namespace.

Namespace can be declared in the elements where they are used or in the XML root element:

<root
xmlns:h=”http://www.w3.org/TR/html4/”
xmlns:f=”http://www.w3schools.com/furniture”>

<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>

<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>

</root>

Uniform Resource Identifier (URI)

A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet


Resource.

17
The most common URI is the Uniform Resource Identifier (URI) which identifies an Internet
domain address. Another, not so common type of URI is the Universal Resource Name (URN).

Default Namespaces

Defining a default namespace for an element saves us from using prefixes in all the child
elements. It has the following syntax:

xmlns=”namespaceURI”
This XML carries HTML table information:

<table xmlns=”http://www.w3.org/TR/html4/” >


<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>

This XML carries information about a piece of furniture:

<table xmlns=”http://www.w3schools.com/furniture” >


<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>

Namespaces in Real Use

XSLT is an XML language that can be used to transform XML documents into other formats,
like HTML.

In the XSLT document below, we can see that most of the tags are HTML tags.

The tags that are not HTML tags have the prefix xsl,identified by the namespace
xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”:

18
<?xml version=”1.0” encoding=”ISO-8859-1”?>

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

<xsl:template match=”/”>
<html>
<body>
<h2>My CD Collection</h2>
<table border=”1”>
<tr>
<th align=”left”>Title</th>
<th aligh=”left”>Artist</th>
</tr>
<xsl:for-each select=”catalog/cd”>
<tr>
<td><xsl:value-of select=”title”/></td>
<td><xsl:value-of select=”artist”/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl: template>

</xsl:stylesheet>

XML Application

XML is a meta-markup language for designing domain-specific markup languages. Each


XML-based markup language is called an XML application. This is not an application that uses
XML like that Mozilla web browser, the Gnumeric spreadsheet, or the XML Pro editor, but
rather an application of XML to a specific domain such as Chemical Markup Language (CML)
for chemistry or GedML for genealogy.

Each XML application has its own syntax and vocabulary. This syntax and vocabulary
adheres to the fundamental rules of XML. This is much like human languages, which each have
their own vocabulary and grammar, while at the same time adhering to certain fundamental rules
imposed by human anatomy and the structure of the brain.

Chemical Markup Language

Peter Murray-Rust’s Chemical Markup Language (CML) may have been the first XML
application. CML was originally developed as an SGML application, and gradually transitioned
to XML as the XML standard developed. In its most simplistic form, CML is “HTML plus
molecules”, but it has applications far beyond the limited confines of the web.

Molecular documents often contain thousands of different, very detailed objects. For
example, a single medium-sized organic molecule may contain hundreds of atoms, each with

19
several bonds. CML seeks to organize these complex chemical objects in a straightforward
manner that can be understood, displayed, and searched by a computer. CML can be used for
molecular structures and sequences, spectrographic analysis, crystallography, publishing,
chemical databases, and more. Its vocabulary includes molecules, atoms, bonds, crystals,
formulas, sequences, symmetries, reactions, and other chemistry terms. For instance Listing 2-1
is a basic CML document for water (H2O):

The water molecule H2O

<?xml version=”1.0”>
<CML>
<MOL TITLE=”Water”>
<ATOMS>
<ARRAY BUILTIN=”ELSYM”>H O H</ARRAY>
</ATOMS>
<BONDS>
<ARRAY BUILTIN=”ATID1”>1 2</ARRAY>
<ARRAY BUILTIN=”ATID2”>2 3</ARRAY>
<ARRAY BUILTIN=”ORDER”>1 1</ARRAY>
</BONDS>
</MOL>
</CML>
Mathematical Markup Language

The Mathematical Markup Language (MathML) is an XML application for mathematical


equations. MathML is sufficiently expressive to handle pretty much all forms of math-from
grammar-school arithmetic through calculus and differential equations. It can handle many
considerably more advanced topics as well, though there are definite gaps in some of the more
advanced and obscure notations used by certain sub-fields of mathematics. While there are limits
to MathML on the high end of pure mathematics and theoretical physics, it is eloquent enough to
handle almost all educational, scientific, engineering, business, economics, and statistics needs.
And MathML is likely to be expanded in the future, so even the purest of the pure
mathematicians and the most theoretical of the theoretical physicists will be able to publish and
do research on the Web. MathML completes the development of the web into a serious tool for
scientific research and communication (despite its long digression to make it suitable as a new
medium for advertising brochures).

Netscape Navigator and Internet Explorer do not yet support MathML. Nonetheless, it is
the fervent hope of many mathematicians that they soon will. The W3C has integrated some
MathML support into their test-bed browser, Amaya.

Channel Definition Format

Microsoft’s Channel Definition Format (CDF) is an XML application for defining


channels. Web sites use channels to upload information to readers who subscribe to the site
rather than waiting for them to come and get it. This is alternately called Webcasting or push.
CDF was first introduced in Internet Explorer 4.0.

A CDF document is an XML file, separate from, but linked to an HTML document on the
site being pushed. The channel defined in the CDF document determines which pages are sent to

20
the readers, how the pages are transported, and how often the pages are sent. Pages can either be
pushed by sending notifications, or even whole Web sites, to subscribers; or pulled down by the
readers at their convenience.

Synchronized Multimedia Integration Language

The Synchronized Multimedia Integration Language (SMIL, pronounced “smile”) is a


W3C recommended XML application for writing “TV-like” multimedia presentations for the
Web. SMIL documents don’t describe the actual multimedia content (that is the video and sound
that are played) but rather when and where they are played.

Open Software Description

The Open Software Description (OSD) format is an XML application co-developed by


Marimba and Microsoft for updating software automatically. OSD defines XML tags that
describe software components. The description of a component includes the version of the
component, its underlying structure, and its relationships to and dependencies on other
components. This provides enough information for OSD to decide whether a user needs a
particular update or not. If they do need the update, it can be automatically pushed to users,
rather than requiring them to manually download and install it.

Vector Markup Language

Microsoft has developed their own XML application for vector graphics called the Vector
Markup Language (VML). VML is more finished than SVG, and is already supported by Internet
Explorer 5.0 and Microsoft Office 2000. VML is not nearly as ambitious a format as SVG, and
leaves out a lot of advanced features SVG includes such as clipping, masking, and compositing.

MusicML

The Connection Factory has created an XML application for sheet music called
MusicML. MusicML includes notes, beats, clefs, staffs, rows, rhythms, rests, beams, chords and
more.

VoxML

Motorola’s VoxML (http://www.voxml.com/) is and XML application for the spoken


word. In particular, it’s intended for those annoying voice mails and automated phone response
systems. VoxML enables the same data that’s used on a Web site to be served up via telephone.
It’s particularly useful for information that’s created by combining small nuggets of data, such as
stock prices, sports scores, weather reports, and test results. The Weather Channel and CBS
MarketWatch.com are considering using VoxML to provide more information over regular voice
phones.

Human Resources Markup Language

HireScape’s Human Resources Markup Language (HRML) is an XML application that


provides a simple vocabulary for describing job openings. It defines elements matching the parts

21
of a typical classified want ad such as companies, divisions, recruiters, contact information,
terms, experience, and more.

HRML is designed to automate the exchange of job information between companies,


applicants, recruiters, job boards, and other interested parties. There are hundreds of job boards
on the Internet today as well as numerous Usenet newsgroups and mailing lists. It’s impossible
for one individual to search them all, and it’s hard for a computer to search them all because they
all use different formats for salaries, locations, benefits, and the like.

Resource Description Framework

The Resource Description Framework (RDF) is an XML application that adds semantics.
RDF can be used to specify anything from the author and abstract of a Web page to the version
and dependencies of a software package to the director, screenwriter, and actors in a movie.
What links all of these uses is that what’s being encoded in RDF is not the data itself (the Web
page, the software, the movie) but information about the data. This data about data is called
meta-data.

An RDF vocabulary defines a set of elements and their permitted content that’s
appropriate for meta-data in a given domain. RDF enables communities of interest t standardize
their vocabularies and share those vocabularies with other who may extend them.

JSP Fundamentals
What do you mean by Static & Dynamic Contents?

• Static contents
 Typically static HTML page
 Same display for everyone
• Dynamic contents
 Contents is dynamically generated based on conditions
 Conditions could be
• User identity
• Time of the day
• User entered values through forms and selections
 Examples
• Etrade webpage customized just for us, my Yahoo

Applet Containers
EJB Container
HTTP/ Web Container RMI EJB
Applet JSP
HTTPS Servlet
J2SE
JavaMail OP
JM JavaMail
RMI/IIOP

S DI A BC/II
DI
App Client S JM JN JT
JTA
JTA

JDBC

JN JDMI
Container M JAF R
S JAF
HTTP/
HTTPS 22
J2SE
J2SE
App
Client

RMI
RMI/IIOP
JNDI

JDBC
JMS

J2SE
Database
Fig: JSP & Servlet as Web Components

What is JSP Page?


• A text-based document capable of returning both static and
dynamic content to a client browser
• Static content and dynamic content can be intermixed
• Static content
 HTML, XML, Text
• Dynamic content
 Java code
 Displaying properties of JavaBeans
 Invoking business logic defined in Custom tags

A Simple JSP Page

<html>
<body>
Hello World!
<br>
Current time is <%= new java.util.Date()%>
</body>
</html>

Output

23
Difference between Servlets and JSP

Servlets JSP
HTML code in Java Java-like code in HTML
Not easy to author Very easy to author
Code is compiled into a servlet

JSP Bebefits

• Content and display logic are separated


• Simplify web application development with JSP, JavaBeans and custom tags
• Supports software reuse through the use of components(JavaBeans, Custom tags)
• Automatic deployment
 Recompile automatically when changes are made to JSP pages
• Easier to author web pages
• Platform-independent

JSP Architecture

Client Request JSP


Translator
Servlet Engine

Reject JSP Create Servlet

Response Load JSP Servlet

24
JSP Servlet
Load Servlet

Fig: JSP Architecture

Life Cycle of a JSP Page

User Request

Server

File JSP
Change
d
?

Create Source

Compile

Execute Servlet
JSP Page Lifecycle phases

• Translation phase
• Compile phase
• Execution phase

Translation/Compilation Phase

• JSP files get translated into servlet source code, which is then compiled
• Done by the container automatically
• The first time JSP page is accessed after it is deployed (or modified and redeployed)
• For JSP page “Page Name”, the source code resides
• Static Template data is transformed into code that will emit data into the stream

25
• JSP elements are treated differently
 Directives are used to control how Web container translates and executes JSP
page
 Scripting elements are inserted into JSP page’s servlet class
 Elements of the form >jsp:xxx…/>are converted into method calls to JavaBeans
components

JSP Lifecycle Methods during Execution Phase

init event jspInit()

request
response jspService()

destroy event jspDestroy()

“JSP” Servlet

Initialization of a JSP Page

• Declare methods for performing the following tasks using JSP declaration mechanism
 Read persistent configuration data
 Initialize resources
 Perform any other one-time activities by overriding jspInit() method of JspPage
Interface

Finalization of a JSP Page


• Declare methods for performing the following tasks using JSP declaration
mechanism
 Read persistent configuration data
 Release resources
 Perform any other one-time cleanup activities by overriding
jspDestroy() method of JSP Page interface

Directives

• Directives are messages to the JSP container in order to affect overall


structure of the servlet
• Do not produce output into the current output stream

26
• Syntax
 <%@ directive{attr=value}* %>

Three Types of Directives

• page: Communicate page dependent attributes and communicate these to the JSP
container
 <%@ page import=”java.util.* %>
• include: Used to include text and/or code at JSP page translation-time
 <%@ include file=”header.html” %>
• Taglib: Indicates a tag library that the JSP container should interpret
 <%@ taglib uri =”mytags” prefix=”codecamp” %>

Page Directives

• Give high-level information about the servlet that results from the JSP page
• Control
 Which classes are imported
 <%@ page import=”java.util.* %>
 What MIME type is generated
 <%@ page contentType=”MIME-Type”%>
 How multithreading is handled
 <%@ page isThreadSafe=”true” %> <%!—Default--%>
 <%@ page isThreadSafe=”false” %>
 What page handles unexpected errors
<%@ page errorPage=”errorpage.jsp”%>

Example

<%@page language=”java” %>


<html>
<head><title>Hello World JSP page.</title></head>
<body>
<font size=”10”>
<%
String name=”www.jmc.edu”;
out. println(“Hello” + name +”!”);
%>
</font>
</body>
</html>

Include Directive

• Is processed when the JSP page is translated into a servlet class


• Effect of the directive is to insert the text contained in another file—either static content
or another JSP page—in the including JSP page

27
• Used to include banner content, copyright information, or any chunk of content that we
might want to reuse in another page
• Syntax and Example
 <%@include file=”filename” %>
 <%@include file=”banner.jsp” %>

Benefits

• Use include directive if the file changes rarely


 It is faster than jsp:include
• Use jsp:include for content that changes often
• Use jsp:include if which page to include cannot be decided until the main page is
requested

The taglib Directive

JSP’s offer a unique feature of “Tag Libraries”. Simply put, these are custom defined JSP
tags. They are basically meant for componentizing presentation level logic. They are very similar
to beans except the fact that Beans are used to separate Business logic.

Every tag is mapped to a particular class file which is executed whenever the tag is
encountered in an JSP file.

The general syntax:

<%@ taglib uri=”-----“ prefix=”---“ %>

The parent of the tag is the JSP tag within which it is nested, if there isn’t one, its set to
null.

There are two things to remember while using TAGLIB’s:

The class file should be created and it should be deployed in the Servlet folder of the web
server. The class file should implement the Tag and BodyTag interfaces.

The mapping of a particular tag to a particular class file should be done in the taglib.tld
file.

The tag is then ready to be used in the JSP file!!


The taglib file forms the central description for the tag library:

This file is an XML document that defines the tag’s operation .

It maps the tag name on the page to the implementing class.

It defines inputs to the class.

It references the helper class that provides details of any output variables set by the tag
class.

28
This tag and Bodytag have some methods, these all methods are callback methods.

Tag method: doStartTag()


doEndTag()

Body Tag : doAfterBody()

JSP Standard Actions

Servlet container provides many built in functionality to ease the development of the
applications. Programmers can use these functions in JSP applications. The JSP Actions tag
enables the programmer to use these functions. The JSP Actions are XML tags that can be used
in the JSP page.

Here is the list of JSP Actions:

• jsp:include
The jsp:include action work as a subroutine, the Java Servlet temporarily passes the
request and response to the specified JSP/Servlet. Control is then returned back to the
current JSP page.

• jsp:param
The jsp:param action is used to add the specific parameter to current request. The
jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block.

• jsp:forward
The jsp:forward tag is used to hand off the request and response to another JSP or
servlet. In this case the request never return to the calling JSP page.

• jsp:plugin
In older versions of Netscape Navigator and Internet Explorer; different tags is used to
embed applet. The jsp:plugin tag actually generates the appropriate HTML code the
embed the Applets correctly.

• jsp:fallback
The jsp:fallback tag is used to specify the message to be shown on the browser if applets
is not supported by browser.

Example:
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>
• jsp:getProperty
The jsp:getProperty is used to get specified property form the Java Bean object.

• jsp:setProperty
The jsp:setProperty tag is used to set a property in the Java Bean object.

29
• jsp:useBean
The jsp:useBean tag is used to instantiate an object of Java Bean or it can re-use existing
java bean object.

In JSP tags can be divided into 4 different types. These are:

1. Directives
In the directives we can import packages, define error handling pages or the session
information of the JSP page.
2. Declarations
This tag is used for defining the functions and variables to be used in the JSP.

3. Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in
_jspService method by the JSP engine.
4. Expressions
We can use this tag to output any data on the generated page. These data are
automatically converted to string and printed on the output stream.

Now we will examine each tags in details with examples. DIRECTIVES

Syntax of JSP directives is:

<%@directive attribute=”value” %>

Where directive may be:

1. page: page is used to provide the information about it.


Example: <%@page language=”java” %>

2. include: include is used to include a file in the JSP page.


Example: <%@include file=”/header.jsp” %>

3. taglib: taglib is used to use the custom tags in the JSP pages(custom tags allows us to
defined our own tags).
Example: <%@taglib uri=”tlds/taglib.tld” prefix=”mytag” %>

and attribute may be:

1. language=”java”
This tells the server that the page is using the java language. Current JSP
specification supports only java language.
Example: <%@page language=”java”%>

2. extends=”mypackage.myclass”
This attribute is used when we want to extend any class. We can use comma(,) to
import more than one packages.

30
Example: <%@page language=”java” import=”java.sql.*,mypackage.myclass”
%>

3. session=”true”
When this value is true session data is available to the JSP page otherwise not. By
default this value is true.
Example: <%@page language=”java” session=”true” %>

4. errorPage=”error.jsp”
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language=”java” session=”true” errorpagePage=”error.jsp”
%>

5. contentType=”text/html;charset=ISO-8859-1”
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page language=”java” session=”true”
contentType=”text/html;charset=ISO-8859-1” %>

Java Beans

• Java classes that can be easily reused and composed together into an application.
• Any Java class that follows certain design conventions can be a Java Beans component
 Properties of the class
 Public methods to get and set properties
• Within a JSP page, we can create and initialize beans and get and set the values of their
properties.
• Java Beans can contain business logic or data base access logic.
• Java Beans maintain internal properties.
• A property can be
 Read/Write, read-only, or write-only
 Simple or indexed
• Properties should be accessed and set via getXxx and setXxx methods
 PropertyClass getProperty() {…}
 PropertyClass setProperty() {…}
• Java Beans must have a zero-argument (empty) constructor.

Why use Java Beans

• A JSP page can create and use any type of Java programming language object within a
declaration.
• JSP pages can use JSP elements to create and access the object that conforms to Java
Beans conventions.
• No need to learn Java programming language for page designers.
• Stronger separation between content and presentation.
• Higher re-usability of code.

31
• Simpler object sharing through built-in sharing mechanism.
• Convenient matching between request parameters and object properties.

Creating a Java Beans

• Declare that the page will use a bean that is stored within and accessible from the
specified scope by jsp:useBean element
<jsp:useBean id=”beanName”
class=”fully_qualified_classname” scope=”scope”/>
or
<jsp:useBean id=”beanName”
class=”fully_qualified_classname” scope=”scope”>
<jsp:setProperty…/>
</jsp:useBean>
• 2 ways to set a property of a bean
• Via scriptlet
 <% beanName.setPropName(value); %>
• Via JSP:setProperty
 <jsp:setPropery name=”beanName”
property=”propName” value=”string constant”/>
 “beanName” must be the same as that specified for the id attribute in a useBean
element

 There must be asetPropName method in the bean

• Jsp:setProperty syntax depends on the source of the property.

Error Handling
• Determine the exception thrown
• In each of our JSP, include the name of the error page
 <%@page errorPage=”errorpage.jsp” %>
• Develop an error page, it should include
 <%@page isErrorPage=”true” %>
• In the error page, use the exception reference to display exception information
 <%=exception.toString() %>

Introduction to ASP

An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed
on the server.

What is ASP?

• ASP stands for Active Server Pages

32
• ASP is a Microsoft Technology
• ASP is a program that runs inside IIS
• IIS stands for Internet Information Services
• IIS comes as a free component with Windows 2000
• IIS is also a part of the Windows NT 4.0 Option Pack
• The Option Pack can be downloaded from Micorsoft
• PWS is a smaller – but fully functional – version of IIS
• PWS can be found on our Windows 95/98 CD

ASP Compatibility

• To run IIS we must have Windows NT 4.0 or later


• To run PWS we must have windows 95 or later
• ChiliASP is a technology that runs ASP without Windows OS
• InstantASP is another technology that runs ASP without Windows

What is an ASP File?

• An ASP file is just the same as an HTML file


• An ASP file can contain text, HTML, XML, and scripts
• Scripts in an ASP file are executed on the server
• An ASP file has the file extension “.asp”

How Does ASP Differ from HTML?

• When a browser requests an HTML file, the server returns the file
• When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP
engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the
ASP file is returned to the browser as plain HTML.

What can ASP do for us?

• Dynamically edit, change, of add any content of a Web page


• Respond to user queries or data submitted form HTML forms
• Access any data or databases and return the results to a browser
• Customize a Web page to make it more useful for individual users
• The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed
• Provide security – since ASP code cannot be viewed from the browser
• Clever ASP programming can minimize the network traffic

Objects

Response Object

The ASP Response object is used to send output to the user from the server. Its collections,
properties, and methods are described below:

33
Collections

Collection Description
Cookies Sets a cookie value. If the cookie does not exist, it will be
created and take the value that is specified

Properties

Property Description
Buffer Specifies whether to buffer the page output or not
CacheControl Sets whether a proxy server can cache the output generated
by ASP or not
Charset Appends the name of a character-set to the content-type
header in the Response object
Content Type Sets the HTTP content type for the Response object
Expires Sets how long (in minutes) a page will be cached on a
browser will expieres
ExpiresAbsolute Sets a date and time when a page cached on a bworser will
expire
IsClientConnected Indicates if the client has disconnected form the server
Pics Appends a value to the PICS label response header
Status Specifies the value of the status line returned by the server

Methods

Methods Description
AddHeader Adds a new HTTP header and a value to the HTTP response
AppendToLog Adds a string to the end of the server log entry
BinaryWrite Writes data directly to the output without any character
conversion
Clear Clears any buffered HTML output
End Stops processing a script, and returns the current result
Flush Sends buffered HTML output immediately
Redirect Redirects the user to a different URL
Write Writes a specified string to the output

Example 1:

<html>
<body>
<%
response.write(“Hello World!”)
%>
</body>

34
</html>

Example 2:

<html>
<body>
<%
response.write(“<h2>We can use HTML tags to format the text!</h2>”)
%>
<%
response.write(“<p style=’color:#0000ff’>This text is styled with the style attribute!</p>”)
%>
</body>
</html>

Example 3:

<%
if Request.Form(“select”)<>””then
Response.Redirect(Request.Form(“select”))
end if
%>
<html>
<body>
<form action=”demo_redirect.asp” method=”post”>
<input type=”radio” name=”select” value=”demo_server.asp”>
Server Example<br/>
<input type=”radio” name=”select” value=”demo_text.asp”>
Text Example<br/><br/>
<input type=”submit” value=”Go!”>
</form>
</body>
</html>

Request Object

The Request object is used to get information from a visitor. When a browser asks for a
page from a server, it is called a request. The Request object is used to get information from a
visitor. Its collections, properties, and methods are described below:

Collections
Collection Description
ClientCertificate Contains all the field values stored in the client certificate
Cookies Contains all the cookie values sent in a HTTP request
Form Contains all the form (input) values from a form that uses
the post method
QueryString Contains all the variable values in a HTTP query string

35
ServerVariables Contains all the server variable values

Properties
Property Description
TotalBytes Returns the total number of bytes the client sent in the
body of the request

Methods
Methods Description
BinaryRead Retrieves the data sent to the server form the client as part
of a post request and stores it in a safe array

Example 4:

<html>
<body>
<a href=”demo_simplequerystring.asp?color=green”>Example</a>
<%
Response.Write(Request.QueryString)
%>
</body>
</html>

Example 5:

<html>
<body>
<form action=”demo_simplereqquery.asp” method=”get”>
First name: <input type=”text” name=”fname”><br/>
Last name: <input type=”text” name=”lname”><br/>
<input type=”submit” value=”Submit”>
</form>
<%
Response.Write(Request.QueryString)
%>
</body>
</html>

Example 6:

<html>
<body>
<form action=”demo_simpleform1.asp” method=”post”>
First name:<input type=”text” name=”fname” value=”Donald”/>
<br/>

36
Last name:
<input type=”text” name=”lname” value=”Duck”/>
<br/>
<input type=”submit” value=”Submit”/>
</form>
<%
Response.Write(Request.Form )
%>
</body>
</html>

Example 7:

<html>
<body>
<form action=”demo_simpleform.asp” method=”post”>
Your name: <input type=”text” name=”fname” size=”20”/>
<input type=”submit” value=”Submit”/>
</form>
<%
dim fname
fname=Request.Form(“fname”)
If fname<>”” Then
Response.write(“Hello” &fname&”!<br/>”)
Response.Write(“How are you today?”)
End If
%>
</body>
</html>

Example 8:

<html>
<%
dim cars
cars=Request.Form(“cars”)
%>
<body>
<form action=”demo_radiob.asp” method=”post”>
<p>Please select your favorite car:</p>
<input type=”radio” name=”cars”
<%if cars=”Volvo” then Response.Write(“checked”)%>
value=”Volvo”>Volvo</input>
<br/>
<input type=”radio” name=”cars”
<%if cars=”Saab” then Response.Write(“checked”)%>
value=”Saab”>Saab</input>
<br/>
<input type=”radio” name=”cars”
<%if cars=”BMW” then Response.Write(“checked”)%>

37
value=”BMW”>BMW</input>
<br/><br/>
<input type=”submit” value=”Submit”/>
</form>
<%
If cars<> “” then
Response.Write(“<p>Your favorite car is:” &cars& “</p>”)
End If
%>
</body>
</html>

Application Object
A group of ASP files that work together to perform some purpose is called an application. The
Application object is used to tie these files together. An application on the Web may consist of
several ASP files that work together to perform some purpose. The Application object is used to
tie these files together.

The Application object is used to store and access variables form any page, just like the Session
object. The difference is that ALL users share ONE Application object (with Sessions there is
ONE Session object for EACH user).

The Application object holds information that will be used by many pages in the application (like
database connection information). The information can be accessed from any page. The
information can also be changed in one place, and the changes will automatically be reflected on
all pages. The Application object’s collections, methods, and events are described below:

Collections
Collection Description
Contents Contains all the items appended to the application through a
script command
StaticObjects Contains all the objects appended to the application with the
HTML <object> tag

Methods
Method Description
Contents.Remove Deletes an item from the Contents collection
Contents.RemoveAll() Deletes all items from the Contents collection
Lock Prevents other users from modifying the variables in the
Application object
Unlock Enables other users to modify the variables in the
Application object
Events

Event Description
Application_OnEnd Occurs when all user sessions are over, and the application
ends
Application_OnStart Occurs before the first new session is created (when the
Application object is first referenced)

38
Session Object

A Session object stores information about, or change settings for a user session. When we
are working with an application on our computer, we open it, do some changes and then we close
it. This is much like a Session. The computer knows who we are. It knows when we open the
application and when we close it. However, on the internet there is one problem: the web server
does not know who we are and what we do, because the HTTP address doesn’t maintain state.

ASP solves this problem by creating a unique cookie for each user. The cookie is sent to
the user’s computer and it contains information that identifies the user. This interface is called
the Session object.

The Session object stores information, about, or change settings for a user session.
Variables stored in a Session obect hold information about one single user, and are available to
all pages in one application. Common information stored in session variables is name, id, and
preferences. The server creates a new Session object for each new user, and destroys the Session
object when the session expires.

The Session object’s collections, properties, methods, and events are described below:

Collections
Collection Description
Contents Contains all the items appended to the application through a
script command
StaticObjects Contains all the objects appended to the application with the
HTML <object> tag

Properties
Property Description
CodePage Specifies the character set that will be used when displaying
dynamic content
LCID Sets or returns an integer that specifies a location or region.
Contents like date, time, and currency will be displayed
according to that location or region
SessionID Returns a unique id for each user. The unique id is generated
by the server
Timeout Sets or returns the timeout period (in minutes) for the
Session object in this application

Methods
Methods Description
Abandon Destroys a user session
Contents.Remove Deletes an item form the Contents collection
Contents.RemoveAll() Deletes all items form the Contents collection

Events

39
Event Description
Session_OnEnd Occurs when a session ends
Session_OnStart Occurs when a session starts

Server Object

The Server object is used to access properties and methods on the server. The ASP Server
object is used to access properties and methods on the server. Its properties and methods are
described below:

Properties
Property Description
ScriptTimeout Sets or returns the maximum number of seconds a script
can run before it is terminated

Methods
Methods Description
CreateObject Creates an instance of an object
Execute Executes an ASP file from inside another ASP file
GetLastError() Returns an ASPError object that describes the error condition
that occurred
HTMLEncode Applies HTML encoding to a specified string
MapPath Maps a specified path to a physical path
Transfer Sends (transfers) all the information created in on ASP file to
a second ASP file
URLEncode Applies URL encoding rules to a specified string

ASPError Object

The ASPError object displays information about errors in scripts.

The ASPError object was implemented in ASP 3.0 and is available in IIS5 and later.

The ASPError object is used to display detailed information of any error that occurs in scripts in
an ASP page.

Note: The ASPError object is created when Server.GetLastError is called, so the error
information can only be accessed by using the Server.GetLastError method.

The ASPError object’s properties are described below (all properties are read-only):

Properties
Property Description
ASPCode Returns an error code generated by IIS
ASPDescription Returns a detailed description of the error (if the error is
ASP-related)
Category Returns the source of the error (was the error generated by
ASP? By a scripting language? By an object?)

40
Column Returns the column position within the file that generated the
errors
Description Returns a short description of the error
File Returns the name of the ASP file that generated the error
Line Returns the line number where the error was detected
Number Returns the standard COM error code for the error
Source Returns the actual source code of the line where the error
occurred

Components

AdRotator Component

The ASP AdRotator component creates an AdRotator object that displays a different
image each time a user enters or refreshes a page. A text file includes information about the
images.

Syntax
<% set adrotator=server.createobject(“MSWC.AdRotator”)
adrotator.GetAdvertisement(“textfile.txt”)
%>

AdRotator Example

REDIRECT banners.asp
*
w3s.gif
http://www.w3schools.com
Free Tutorials from W3Schools
50
xmlspy.gif
http://www.altova.com
XML Editor from Altova
50

The lines below the asterisk in the text file above specifies the name of the images (ads) to be
displayed, the hyperlink addresses, the alternate text (for the images), and the display rates (in
percent). The first line in the text file above specifies what to happen when a visitor clicks on one
of the images. The redirection page (banners.asp) will receive a querystring with the URL to
redirect to.

REDIRECT banners.asp
WIDTH 468
HEIGHT 60
BORDER 0
*
w3s.gif

41
The “banners.asp” file looks like this:

Example

<%
url=Request.QueryString(‘url”)
If url<>”” then Response.Redirect(url)
%>
<html>
<body>
<%
set adrotator=Server.CreateObject(“MSWC.AdRotator”)
response.write(adrotator.GetAdvertisement(“textfile.txt”))
%>
</body>
</html>

ASP AdRotator Properties


Property Description Example
Border Specifies the size of <%set adrot=Server.CreateObject(“MSWC.AdRotator”)
the borders around adrot.Border=”2”
the advertisement Response.Write(adrot.GetAdvertisement(“ads.txt”)) %>
Clickable Specifies whether <%set adrot=Server.CreateObject(“MSWC.AdRotator”)
the advertisement is adrot.Clickable=false
a hyperlink Response.Write(adrot.GetAdvertisement(“ads.txt”)) %>
TargetFrame Name of the frame <%set adrot=Server.CreateObject(“MSWC.AdRotator”)
to display the adrot.TargetFrame=”target=’_blank’”s
advertisement Response.Write(adrot.GetAdvertisement(“ads.txt”)) %>

ASP AdRotator Methods


Method Description Example
GetAdvertisement Returns HTML <%
that displays the set adrot=Server.CreateObject(“MSWC.AdRotator”)
advertisement in Response.Write(adrot.GetAdvertisement(“ads.txt”))
the page %>

Browser Capabilities Component

The ASP Browser Capabilities component creates a BrowserType object that determines
the type, capabilities and version number of a visitor’s browser. When a browser connects to a
server, a User Agent header is also sent to the server. This header contains information about the
browser.

42
The BrowserType object compares the information in the header with information in a
file on the server called “Browscap.ini”.

If there is a match between the browser type and version number in the header and the
information in the “Browsercap.ini” file, the BrowserType object can be used to list the
properties of the matching browser. If there is no match for the browser type and version number
in the Browscap.ini file, it will set every property to “UNKNOWN”.

Syntax
s<%
set MyBrow=Server.CreateObject(“MSWC.BrowserType”)
%>

ASP Browser Capabilities Example

The example below creates a BrowserType object in an ASP file, and displays some of the
capabilities of our browser:

Example

<html>
<body>
<%
set MyBrow=Server.CreateObject(“MSWC.BrowserType”)
%>
<table border=”0” width=”100%”>
<tr>
<th>Client OS</th><th><%=MyBrow.platform%></th>
</tr><tr>
<td>Web Browser</td><td><%=MyBrow.browser%></td>
</tr><tr>
<td>Browser version</td><td><%=MyBrow.version%></td>
</tr><tr>
<td>Frame support?</td><td><%=MyBrow.frames%></td>
</tr><tr>
<td>Table support?</td><td><%=MyBrow.tables%></td>
</tr><tr>
<td>Sound support?</td><td><%=MyBrow.backgroundsounds
%></td>
</tr><tr>
<td>Cookies support?</td><td><%=MyBrow.cookies%></td>
</tr><tr>
<td>VBScript support?</td><td><%=MyBrow.vbscript%></td>
</tr><tr>
<td>JavaScript support?</td><td><%=MyBrow.javascript%></td>
</tr>
</table>
</body>
</html>

43
Parameter Description
Comments Optional. Any line that starts with a semicolon are ignored
by the BrowserType object
HTTPUserAgentHeader Optional. Specifies the HTTP User Agent header to
associate with the browser-property value statements
specified in propertyN. Wildcard characters are allowed
browserDefinition Optional. Specifies the HTTP User Agent header-string of
a browser to use as the parent browser. The current
browser’s definition will inherit all of the property values
declared in the parent browser’s definition
propertyN Optional. Specifies the browser properties. The following
table lists some possible properties:
• ActiveXControls – Support ActiveX® controls?
• Backgroundsounds – Support background sounds?
• CDF- Support Channel Definition Format for
Webcasting?
• Tables- Support tables?
• Cookies – Support cookies?
• Frames – Support frames?
• Javaapplets – Support Java applets?
• Javascript – Supprot JScript?
• Vbscript – Supports VBScript?
• Browser – Specifies the name of the browser
• Beta – Is the browser beta software?
• Platform – Specifies the platform that the browser
runs on
• Version – Speicifies the version number of the
browser
valueN Optional. Specifies the value of propertyN. Can be a
string, an integer (prefix with #), or a Boolean value
defaultPropertyN Optional. Specifies the name of the browser property to
which to assign a default value if none of the defined
HTTPUserAgentHeader values match the HTTP User
Agent header sent by the browser
defaultvalueN Optional. Specifies the value of defaultPropertyN. Can be
a string, an integer (prefix with #), or a Boolean value

Content Linking Component

The ASP Content Linking component is used to create a quick and easy navigation system!

The Content Linking component returns a Nextlink object that is used to hold a list of Web pages
to be navigated.

44
Syntax
<%
set nl=Server.CreateObject(“MSWC.NextLink”)
%>

ASP Content Linking Example

First we create a text file - “links.txt”:

asp_intro.asp ASP Intro


asp_syntax.asp ASP Syntax
asp_variables.asp ASP Variables
asp_procedures.asp ASP Procedures

The text file above contains the pages to be navigated. The pages must be listed in the same
order we want them to be displayed, and it must also contain a description for each file name
(use the tab key to separate file name from description).

Note: If we want to add a page, or change the order of the pages in the list; we only have to
modify the text file! The navigation will automatically be corrected!

Then we create an include file, “nlcode.inc”. The .inc filecreates a NextLink object to navigate
between the pages listed in “links.txt”.

“nlcode.inc”:

<% dim nl
set nl=Server.CreateObject (“MSWC.NextLink”)
if (nl.GetListIndex(“links.txt”)>1) then
Response.Write(“<a href=’” & nl.GetPreviousURL(“links.txt”))
Response.Write(“’>Previous Page</a>”)
end if
Response.Write(“<a href=’” & nl.GetNextURL(“links.txt”))
Response.Write(“’>Next Page</a>”)
%>

In each of the .asp pages listed in the text file “links.txt”, put one line of code: <!-- #include
file=”nlcode.inc”-->. This line will include the code in “nlcode.inc” on every page listed in
“links.txt” and the navigation will work.

ASP Content Linking Component’s Methods


Method Description Example
GetListCount Returns the number <% dim nl,c
of items listed in the set nl=Server.CreateObject(“MSWC.NextLink”)
Content Linking List c= nl.GetListCount(“links.txt”)
file Response.Write(“There are”)

45
Response.Write(c)
Response.Write(“item in the list”) %>
GetListIndex Returns the index <% dim nl,c
number of the set nl=Server.CreateObject(“MSWC.NextLink”)
current item in the c= nl.GetListIndex(“links.txt”)
Content Linking List Response.Write(“Item number”)
file. The indeed Response.Write(c) %>
number of the first
item is 1. 0 is
returned if the Output: Item number 3
current page is not in
the Content Linking
List file
GetNextDescription Returns the text <% dim nl,c
description of the set nl=Server.CreateObject(“MSWC.NextLink”)
next item listed in the c= nl.GetNextDescription(“links.txt”)
Content Linking List Response.Write(“Next”)
file. If the current Response.Write(“description is:”)
page is not found in Response.Write(c)
the list file it returns %>
the text description
of the last page on Next description is: ASP Variables
the list
GetNextURL Returns the URL of <% dim nl,c
the next item listed in set nl=Server.CreateObject(“MSWC.NextLink”)
the Content Linking c= nl.GetNextURL(“links.txt”)
List file. If the Response.Write(“Next”)
current page is not Response.Write(“URL is:”)
found in the list file Response.Write(c)
it returns the URL of %>
the last page on the
list Next description is: asp_variables.asp
GetNthDescription Returns the <% dim nl,c
description of the set nl=Server.CreateObject(“MSWC.NextLink”)
Nth page listed in the c= nl.GetNthDescription(“links.txt”,3)
Content Linking List Response.Write(“Third”)
file Response.Write(“description is:”)
Response.Write(c)
%>

Third description is: ASP Variables

GetNthURL Returns the URL <% dim nl,c


of the Nth page set nl=Server.CreateObject(“MSWC.NextLink”)
listed in the c= nl.GetNthURL(“links.txt”,3)
Content Linking Response.Write(“Third”)
List file Response.Write(“URL is:”)
Response.Write(c)

46
%>

Thirds URL is: asp_variables.asp


GetPreviousDescription Returns the text <% dim nl,c
description of the set nl=Server.CreateObject(“MSWC.NextLink”)
previous item c= nl.GetPreviousDescription(“links.txt”)
listed in the Response.Write(“Previous”)
Content Linking Response.Write(“description is:”)
List file. If the Response.Write(c)
current page is not %>
found in the list
file it returns the Previous description is: ASP Variables
text description of
the first page on
the list
GetPreviousURL Returns the URL <% dim nl,c
of the previous set nl=Server.CreateObject(“MSWC.NextLink”)
item listed in the c= nl.GetPreviousURL(“links.txt”)
Content Linking Response.Write(“Previous”)
List file. If the Response.Write(“URL is:”)
current page is not Response.Write(c)
found in the list %>
file it returns the
URL of the first Previous description is: asp_variables.asp
page on the list

Working with HTML Forms

User Input

The Request object can be used to retrieve user information from forms.

47
Example HTML form

<form method=”get” action=”simpleform.asp”>


First name: <input type=”text” name=”fname” /><br/>
Last name: <input type=”text” name=”lname” /><br/>
<input type=”submit” value=”Submit” ssss/>
</form>

User input can be retrieved with the Request.QueryString or Request.Form command.

Reauest.QueryString

The Request.QueryString command is used to collect values in a form with method=”get”.

Information sent from a form with the GET method is visible to everyone (it will be displayed in
the browser’s address bar) and has limits on the amount of information to send.

Assume that “simpleform.asp” contains the following ASP script:

<body>
Welcome
<%
response.write(request.querystring(“fname”))
response.write(“ “ & request.querystring(“lname”))
%>
</body>

The browser will display the following in the body of the document:

Welcome Bill Gates

Request.Form

The Request.Form command is used to collect values in a form with method=”post”.

Information sent from a form with the POST method is invisible to others and has no limits on
the amount of information to send.

Assume that “simpleform.asp” contains the following ASP script:

48
<body>
Welcome
<%
response.write(request.form(“fname”))
response.write(“ “ & request.formsss(“lname”))
%>
</body>

The browser will display the following in the body of the document:

Welcome Bill Gates

Form Validation

User input should be validated on the browser whenever possible (by client scripts). Browser
validation is faster and reduces the server load.

We should consider server validation if the user input will be inserted into a database. A good
way to validate a form on the server is to post the form to itself, instead of jumping to a different
page. The user will then get the error messages on the same page as the form. This makes it
easier to discover the error.

Connecting to Microsoft SQL Server & MS – Access Database

Connecting to MS Access database from Classic ASP can be accomplished in several


ways. We can connect using OLEDB DSN-less connection, we can connect using ODBC
connection or we can use DSN.

1. Connect to a Microsoft Access Database from ASP using a DSN


Set oConnection = Server.CreateObject(“ADODB.Connection”)
oConnection.Open “DSN=; UID=; PWD=”
oConnection.Close

The ASP connection example above is very simple and all we need to do is to create
a DSN for our MS Access database.

2. Connect to a Microsoft Access Database from ASP using DSN-less ODBC connection
Set oConnection = Server.CreateObject(“ADODB.Connection”)
oConnection.Open “DRIVER={Microsoft Access Driver (*.mdb)};DBQ=” &
Server.MapPath(“ “) & “; UID=; PWD=”
oConnection.Close
Set oConnection = Nothing

This ASP MS Access connection example doesn’t require DSN, but requires that
we have Microsoft Access Driver installed on our computer/server.

49
3. Connect to a Microsoft Access Database form ASP using DSN-less OLEDB
connection
Set oConnection = Server.CreateObject(“ADODB.Connection”)
oConnection.Open “Provider=Microsoft.Jet.OLEDB.4.0; Data Source=” &
Server.MapPath(“ “) & “;s”
oConnection.Close
Set oConnection = Nothing

SQL Statements with connection object

ADO can be used to access databases from our web pages.

• ADO is a Microsoft technology


• ADO stands for ActiveX Data Objects
• ADO is a Microsoft Active-X component
• ADO is automatically installed with Microsoft IIS
• ADO is a programming interface to access data in a database

Accessing a Database form an ASP Page

The common way to access a database from inside an ASP page is to:

1. Create an ADO connection to a database


2. Open the database connection
3. Create an ADO recordset
4. Open the recordset
5. Extract the data we need from the recordset
6. Close the recordset
7. Close the connection

ADO Recordset

To be able to read database data, the data must first be loaded into a recordset.

Create an ADO Table Recordset

After an ADO Database Connection has beeen created, as demonstrated in the previous chapter,
it is possible to create an ADO Recordset.

Suppose we have a database named “Northwind”, we can get access to the “Customers” table
inside the database with the following lines:

50
<%
set conn=Server.CreateObject(“ADODB.Connection”)
conn.Provider=”Microsoft.Jet.OLEDB.4.0”
conn.Open “c:/webdata/northwind.mdb”

set rs =Server.CreateObejct(“ADODB.recordset”)
rs.Open “Customers”, conn
%>
Create an ADO SQL Recordset

We can also get access to the data in the “Customers” table using SQL:
<%
set
conn=Server.CreateObject(“ADODB.Connection”)conn.Provider=”Microsoft.Jet.OLEDB.4.
0”
conn.Open “c:/webdata/northwind.mdb”

set rs =Server.CreateObejct(“ADODB.recordset”)
rs.Open “Select * from Customers”, conn
%>

Extract Data from the Recordset

After a recordset is opened, we can extract data from recordset.

Suppose we have a database named “Northwind”, we can get access to the “Customers” table
inside the database with the following lines:
<%
set conn=Server.CreateObject(“ADODB.Connection”)
conn.Provider=”Microsoft.Jet.OLEDB.4.0”
conn.Open “c:/webdata/northwind.mdb”

set rs =Server.CreateObejct(“ADODB.recordset”)
rs.Open “Select * from Customers”, conn

for each x in rs.fields


response.write(x.name)
response.write(“ = “)
response.write(x.value)
next
%>

The ADO Recordset Object

The ADO Recordset object is used to hold a set of records from a database table.

Working with RecordSets

51
Using the RecordSet with different cursor and locking attributes set and some of the
advanced properties and methods of the RecordSet object.

Retrieving a RecordSet

A RecordSet can be used to represent the rows returned from a SQL query within an ASP
script. A RecordSet object can be used to represent only a single row or it can be used to
represent dozens or even millions of rows. The same object is used no matter how much data is
returned by a query.

The following is the code to retrieve the data from table using SQL.

<%
set con=Server.CreateObject(“ADODB.Connection”)
con.Open “FILE NAME = c:\myDataLink.UDL; DATABASE = pubs”
set RS = con.Execute (“Select * from Authors ORDER By au_lname”)
%>

RecordSet Fields

Every RecordSet contains a Fields collection. The Fields collection contains individual
Field objects. The fields in the Fields collection represent the columns returned from a database
query. The Fields collection can be used in a number or different ways to display a column
value.

For example, the following script displays a column named phone by name:

<%
set con=Server.CreateObject(“ADODB.Connection”)
con.Open “FILE NAME = c:\myDataLink.UDL; DATABASE = pubs”
set RS = con.Execute (“Select * from Authors ORDER By au_lname”)
Response.Write Rs(“phone”)
%>

The above script retrieves a single column and row from the pubs database table and
displays the column’s value.

Properties of the Field Object

 ActualSize
 Attributes
 DefinedSize
 Name
 NumericScale
 OriginalValue
 Precision
 Type

52
 UnderlyingValue
 Value

53

Vous aimerez peut-être aussi