Académique Documents
Professionnel Documents
Culture Documents
• 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.
XML is nothing special. It is just plain text. Software that can handle plain text can also handle
XML.
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 used in many aspects of web development, often to simplify data storage and
sharing.
Features of XML
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.
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 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.
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.
2
• RSS languages for news feeds
• RDF and OWL for describing resources and ontology
• SMIL for describing multimedia for the web.
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.
If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE
definition with the following syntax:
<?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)
3
External DTD Declaration
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>
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.
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.
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.
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
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>
The syntax rules of XML are very simple and logical. The rules are easy to learn, and easy to
use.
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. 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.
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 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.
From HTML we will remember this: <img src= “computer.gif”>. The “src” attribute provides
additional information about the <img> element.
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:
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’>
If the attribute value itself contains double quotes we can use single quotes, like in this example:
<gangster name=’George “Shotgun” Ziegler’>
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.
Attributes are difficult to read and maintain. Use elements for data. Use attributes for information
that is not relevant to the data.
Entities
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.
To avoid this error, replace the “<” character with an entity reference:
9
XSL
It started with XSL and ended up with XSLT, XPath, and XSL-FO.
The World Wide Web Consortium (W3C) started to develop XSL because there was a need for
an XML-based Stylesheet Language.
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.
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.
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.
<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>
If you have an XSLT compliant browser it will nicely transform our XML into XHTML.
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: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.
<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
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
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.
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
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.
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.
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.
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>
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:
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
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.
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):
<?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
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.
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.
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
21
of a typical classified want ad such as companies, divisions, recruiters, contact information,
terms, experience, and more.
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
<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
JSP Architecture
24
JSP Servlet
Load Servlet
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
request
response jspService()
“JSP” Servlet
• 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
Directives
26
• Syntax
<%@ directive{attr=value}* %>
• 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
Include Directive
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
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 parent of the tag is the JSP tag within which it is nested, if there isn’t one, its set to
null.
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.
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.
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.
• 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.
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.
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” %>
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.
• 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.
• 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
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?
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
• 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.
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 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>
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”)
%>
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
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”)
%>
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.
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)
%>
46
%>
User Input
The Request object can be used to retrieve user information from forms.
47
Example HTML form
Reauest.QueryString
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.
<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:
Request.Form
Information sent from a form with the POST method is invisible to others and has no limits on
the amount of information to send.
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:
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.
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
The common way to access a database from inside an ASP page is to:
ADO Recordset
To be able to read database data, the data must first be loaded into a 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
%>
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
The ADO Recordset object is used to hold a set of records from a database table.
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.
ActualSize
Attributes
DefinedSize
Name
NumericScale
OriginalValue
Precision
Type
52
UnderlyingValue
Value
53