Web Technology - IV Unit - Notes

Web Technology - IV Unit - Notes


Representing Web Data: XML-Documents and Vocabularies-Versions and Declaration - Namespaces JavaScript and XML: Ajax-DOM based XML processing Event-oriented Parsing: SAX-Transforming XML Documents-Selecting XML Data: XPATH – Template based Transformations: XSLT-Displaying XML Documments in Browsers-Case Study- Related Technologies. Separating Programming and Presentation: JSP Technology Introduction-JSP and Servlets-Running JSP Applications Basic JSP-JavaBeans Classes and JSP-Tag Libraries and Files-Support for the Model-View-Controller Paradigm-Case Study-Related Technologies.

REPRESENTING WEB DATA:
XML

4.1 XML DOCUMENT AND VOCABULARIES XML Document:

The Root Element In any markup language, the first element to appear is called the "root element", which defines what kind of document the file will be. In an HTML file, the <html> tag is the root element. An HTML file will always have the HTML element as the root element, while in an XML file, it can be anything. In an XML file, there can only be one root element. The root element must encapsulate all other elements--meaning, these other elements must show up after the opening root tag and before the closing root tag. Here is an example of an XML document with the root element "phonebook".

XML Code:

<phonebook>
<number> </number>
<name> </name>
</phonebook>

Notice how the root element "phonebook" surrounds the other elements in XML file. Below is a broken XML file. Try to see if you can find what is wrong with this file before reading the caption below.

XML Code:

<phonebook>
<number>
 </number>
<name>
 </phonebook>
</name>

You should have noticed that the root element "phonebook" did not contain all other elements because the closing name tag </name> is not between the root element tags <phonebook> and </phonebook>. Another rule for XML files is that only one root element per file is allowed. Our previous example followed this rule, but our example below does not because it has two root elements. What are the two root elements?

XML Code:

<phonebook>
<number>
</number>
<name>
</name>
</phonebook>
<diary>
 <date>
</date>
 </diary>

If you said the two root elements were "phonebook" and "diary", then you got it right! Phone book is the first element to appear in this file, so it is automatically a root element. After the phonebook element is closed, no other elements should follow because XML can only have one root element per file. Because the "diary" element did not follow this rule, it transformed this XML file into a lawless, rule-breaking file! XML CDATA All text in an XML document will be parsed by the parser. But text inside a CDATA section will be ignored by the parser.

PCDATA - Parsed Character Data

XML parsers normally parse all the text in an XML document. When an XML element is parsed, the text between the XML tags is also parsed: <message>This text is also parsed</message> The parser does this because XML elements can contain other elements, as in this example, where the <name> element contains two other elements (first and last):
<name>
<first>Bill</first>
<last>Gates</last>
</name>
and the parser will break it up into sub-elements like this: <name> <first>Bill</first> <last>Gates</last> </name> Parsed Character Data (PCDATA) is a term used about text data that will be parsed by the XML parser.


CDATA - (Unparsed) Character Data

The term CDATA is used about text data that should not be parsed by the XML parser. Characters like "<" and "&" are illegal in XML elements. "<" will generate an error because the parser interprets it as the start of a new element. "&" will generate an error because the parser interprets it as the start of an character entity.Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA.Everything inside a CDATA section is ignored by the parser. A CDATA section starts with
"<![CDATA[" and ends with "]]>":
<script> <![CDATA[ function matchwo(a,b)
{
if (a < b && a < 0) then
{
 return 1;
 }
else
{
return 0;
}
} ]]>
</script>
 In the example above, everything inside the CDATA section is ignored by the parser. XML Parsers Here's how a simple XML file would look like. Notice how all the Tags are closed. This is called Well Formed ness. All the Tags in the XML file needs to be closed. Else the parser would throw an Exception while parsing this XML file.

<?xml version='1.0' encoding='us-ascii'?>
<!DOCTYPE Library>
<Library>
<!-- Book 1 Comments --> <Book ISBN="8763-343-2343" >
<Title>Professional JINI</Title>
<Author>Sing Li</Author>
<Publisher>Wrox Publications</Publisher>
<Date_Published>22/10/1999</Date_Published>
</Book> <!-- Book 2 Comments --> <Book ISBN="6834-423-3434">
<Title>XML Programming</Title>
<Author>Sudhir
Ancha</Author>
<Publisher>Mann Publications</Publisher>
<Date_Published/>
</Book>
</Library>

In the above XML file, after the XML Prolog "<?xml version='1.0' encoding='usascii'?>" we have added one more line called "<!DOCTYPE Library >" . Here DOCTYPE Library indicates that all the Tags inside this XML file will be under the Tag "Library". Which means "Library" will be the parent or root of all other Tags in this XML file. Each XML file can have only one DOCTYPE. Also in the XML File we have added comments for Book1 using the Following syntax <!-- Book 1 Comments -->

The Element called "Book" has both Attributes and More Tags under it. For Example in the above XML file, for the Book Element, ISBN is attribute and Title, Author and Publisher are sub Tags under the Book Element. If the Tags and Elements need to be added compulsorily or not in the XML file along with the Element is defined by DTD (Document Type Definition) file. For Example in the above XML file, For Book Element, ISBN might be compulsory if the search Based on ISBN is supported. And Date Published Tag may not be necessary at all times if there's no search facility based on get the Most Recent Books. We will explain how to create DTD's after next few sections.

Notice how we declared a Empty Tag for <Date_Published/>, under Second Book. This
Statement is equivalent to writing <Date_Published><Date_Published/>. This Feature Could save your XML File Size if there is no Data required between the Tags. From this point we will be explaining how to use different Kinds of Parsers that are available for processing the XML files and how to use them. XML file is just plain Text File. Now the next step is to retrieve the data provided in this XML file. In this Tutorial we will be explaining how to use the Javasoft's XML parser. JavaSoft currently provides three parsers. They are
  • SAX (Simple API for XML) Parser
  • DOM (Document Object Model) Parser and
  • XSLT(XML Style Sheet) Parsers.

In the Next Section, we will be developing code to retrieve the text provided in the XML tags using these Parsers.

XML DTD

The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list of legal elements:
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)> ]>

4.2 XML VERSIONS AND DECLARATIONS
XML Document Example

<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> XML

DECLARATIONS Most of the XML tags have a name associated with it. Here we explain different terms used to indicate the Elements Defined in the XML file.

WELL FORMED TAGS :

One of the most important Features of a XML file is, it should be a Well Formed File. What it means is all the Tags should have a closing tag. In a HTML file, for some tags like <br> we don’t have to specify a closing tag called </br>. Where as in a XML file, it is compulsory to have a closing tag. So we have to declare <br></br>. This is called as Well Formed Tags.

ELEMENTS AND ATTRIBUTES:

Each Tag in a XML file can have Element and Attributes. Here's how a Typical Tag looks like,
<Email to=admin@mydomain.com
from="user@mySite.com" subject="Introducing XML">
</Email>
In this Example, Email is called as Element. This Element called E-mail has three attributes, to, from and subject.

The Following Rules need to be followed while declaring the XML Elements Names:
  • Names can contain letters, numbers, and other characters
  • Names must not start with a number or "_" (underscore)
  • Names must not start with the letters xml (or XML or Xml ..)
  • Names can not contain spaces

Any name can be used, no words are reserved, but the idea is to make names descriptive. Names with an underscore separator are nice. Examples:

<author_name>, <published_date>.

Avoid "-" and "." in names. It could be a mess if your software tried to subtract name from first (author-name) or think that "name" is a property of the object "author" (author.name).

Empty Tags:

In cases where you don't have to provide any sub tags, you can close the Tag, by providing a  "/" to the Closing Tag. For example declaring <Text></Text> is same a declaring <Text /> Comments in XML File : Comments in XML file are declared the same way as Comments in HTML File.

<Text>Welcome To XML Tutorial </Text> <!-- This is a comment --> <Subject />

The XML Prolog XML file always starts with a Prolog. The minimal prolog contains a declaration that identifies the document as an XML document, like this:
<?xml version="1.0"?>
The declaration may also contain additional information, like this: <?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?> The XML declaration may contain the following attributes: version Identifies the version of the XML markup language used in the data. This attribute is not optional. Encoding Identifies the character set used to encode the data. "ISO-8859-1" is "Latin-1" the Western European and English language character set. (The default is compressed Unicode: UTF-8.). For a List of all supported Encoding Types in JDK

 Please Encodings Supported in JDK
Standalone Tells whether or not this document references an external entity or an external data type specification (see below). If there are no external references, then "yes" is appropriate Processing Instructions An XML file can also contain processing instructions that give commands or information to an application that is processing the XML data. Processing instructions have the following format: <?target instructions?> where the target is the name of the application that is expected to do the processing, and instructions is a string of characters that embodies the information or commands for the application to process.

4.3 XML NAMESPACES
XML 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): <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". <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. Namespaces 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.The most common URI is the Uniform Resource Locator (URL) which identifies an Internet domain address. Another, not so common type of URI is the Universal Resource Name (URN).In our examples we will only use URLs.

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>

What is RSS?

Really Simple Syndication (RSS) is a lightweight XML format designed for sharing headlines and other Web content. Think of it as a distributable "What's New" for your site. Originated by UserLand in 1997 and subsequently used by Netscape to fill channels for Netcenter, RSS has evolved into a popular means of sharing content between sites  including the BBC, CNET, CNN, Disney, Forbes, Motley Fool, Wired, Red Herring, Salon, Slashdot, ZDNet, and more). RSS solves myriad problems webmasters commonly face, such as increasing traffic, and gathering and distributing news. RSS can also be the basis for additional content distribution services.

RSS Syntax

RSS defines an XML grammar (a set of HTML-like tags) for sharing news. Each RSS text file contains both static information about your site, plus dynamic information about your new stories, all surrounded by matching start and end tags. Each story is defined by an <item> tag, which contains a headline TITLE, URL, and DESCRIPTION. Here's an example:
 ... <item>
<title>RSS Resources</title>
<link>http://www.webreference.com/authoring/languages/xml/rss/</link>
<description>

Defined in XML, the Rich Site Summary (RSS) format has quietly become a dominant format for distributing headlines on the Web. Our list of links gives you the tools, tips and tutorials you need to get started using RSS. 0323.
</description>
</item>
.. Each RSS channel can contain up to 15 items and is easily parsed using Perl or other open source software.

4.4 JAVASCRIPT AND XML:AJAX Ajax - Javascript Techniques

The real trick of Ajax is updating a segment of the page without actually having to reload the entire page. This little trick is often done by utilizing a Javascript property known as innerHTML. Each HTML element on a page has an innerHTML associated with it that can  be changed at any time. For us, we need to update it when our ajax-example.php script has finished executing. Updating the order.html Page First we need to create a new div on this page that will contain the results of the query. After we have that in place we can update the div's innerHTML with the information returned by ajax-example.php. Remember that this result is stored inside ajaxRequest.responseText.

order.html HTML/Javascript Code:

<html>
<body>
 <script language="javascript" type="text/javascript">
 <!-- //Browser Support
Code function ajaxFunction(){ var ajaxRequest; // The variable that makes Ajax possible!
Try
{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest();
}
catch (e)
{ //Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
Try
{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{ // Something went wrong alert("Your browser broke!");
return false;
} } } // Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var age =document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age +"&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//--> </script> <form name='myForm'> Max
Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' /> <br />
Sex: <select id='sex'>
<option value='m'>m</option>
<option value='f'>f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
 </form>
<div id='ajaxDiv'>Your result will display here</div>
 </body>
 </html>

Quick Ajax Recap

So far we have created a new MySQL table, written a new PHP script and updated order.html twice. If you have followed the directions in the Ajax MySQL lesson and created the MySQL table ajax_example and ajax-example.php script then the updated order.html page will function like our example below.

Display:

Max Age: Max WPM: Sex: m
Your result will display here AJAX XML Example AJAX can be used for interactive communication with an XML file.

AJAX XML Example

The following example will demonstrate how a web page can fetch information from an XML file with AJAX:
Example Explained - The stateChange() Function

When a user clicks on the "Get CD info" button above, the loadXMLDoc() function is executed.The loadXMLDoc() function creates an XMLHttpRequest object, adds the function to be executed when the server response is ready, and sends the request off to the server.When the server response is ready, an HTML table is built, nodes (elements) are extracted from the XML file, and it finally updates the txtCDInfo placeholder with the HTML table filled with XML data:

function loadXMLDoc(url)
 {
if (window.XMLHttpRequest)
 {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else
{// code for IE6, IE5 xmlhttp=new
ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
 if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>";
x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
for(i=0;i<x.length;i++)
{
txt=txt + "<tr>"; xx=x[i].getElementsByTagName("TITLE");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt +
"<td>&nbsp;</td>";
}
}
xx=x[i].getElementsByTagName("ARTIST");
 {
 try
{
txt=txt +"<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td>&nbsp;</td>";
}
}
 txt=txt + "</tr>"; } txt=txt + "</table>";
document.getElementById('txtCDInfo').innerHTML=txt;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}

The AJAX Server Page

The page on the server used in the example above, is an XML file called "cd_catalog.xml".

4. 5 XML DOM ADVANCED
The XML DOM - Advanced

In an earlier chapter of this tutorial we introduced the XML DOM, and we used the getElementsByTagName() method to retrieve data from an XML document. In this chapter we will explain some other important XML DOM methods.
Get the Value of an Element
The XML file used in the examples below: books.xml. The following example retrieves the text value of the first <title> element:

Example

txt=xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;

Get the Value of an Attribute
The following example retrieves the text value of the "lang" attribute of the first <title> element:

Example

Txt=xmlDoc.getElementsByTagName("title")[0].getAttribute("lang");

Change the Value of an Element

The following example changes the text value of the first <title> element:

Example

x=xmlDoc.getElementsByTagName("title")[0].childNodes[0]; x.nodeValue="Easy Cooking";

Create a New Attribute

The XML DOM setAttribute() method can be used to change the value of an existing attribute, or to create a new attribute.The following example adds a new attribute (edition="first") to each <book> element: Example:

x=xmlDoc.getElementsByTagName("book");
for(i=0;i<x.length;i++)
{
x[i].setAttribute("edition","first");
}

Create an Element

  • The XML DOM createElement() method creates a new element node.
  • The XML DOM createTextNode() method creates a new text node.
  • The XML DOM appendChild() method adds a child node to a node (after the last child).
To create a new element with text content, it is necessary to both create a new element node and a new text node, and then append it to an existing node. The following example creates a new element (<edition>), with the following text: First, and adds it to the first <book> element:

Example:

 newel=xmlDoc.createElement("edition");
newtext=xmlDoc.createTextNode("First");
newel.appendChild(newtext);
x=xmlDoc.getElementsByTagName("book");
x[0].appendChild(newel);



Example explained:

Create an <edition> element Create a text node with the following text: First Append the text node to the new <edition> element Append the <edition> element to the first <book> element

Remove an Element

The following example removes the first node in the first <book> element:

Example

x=xmlDoc.getElementsByTagName("book")[0]; x.removeChild(x.childNodes[0]);

4.6 EVENT_ORIENTED PARSING :
SAX Getting the SAX Classes and Interfaces

Once you have your parser, you need to locate the SAX classes. These classes are almost always included with a parser when downloaded, and Xerces is no exception. If this is the case with your parser, you should be sure not to download the SAX classes explicitly, as your parser is probably packaged with the latest version of SAX that is supported by the parser.. To prevent errors, we need to remove the references within the XML document to an external DTD, which constrains the XML, and the XSL stylesheets that transform it. You should comment out these two lines in the XML document, as well as the processing instruction to Cocoon requesting XSL transformation:

<?xml version="1.0"?>
 <!-- We don't need these yet
<?xml-stylesheet href="XSL\JavaXML.html.xsl" type="text/xsl"?>
<?xml-stylesheet href="XSL\JavaXML.wml.xsl" type="text/xsl" media="wap"?> <?cocoon-process type="xslt"?>  
<!DOCTYPE JavaXML:Book SYSTEM "DTD\JavaXML.dtd"> -->
<!--Java and XML --> <JavaXML:Book xmlns:JavaXML="http://www.oreilly.com/catalog/javaxml/">

Once these lines are commented, note the full path to the XML document. In the next chapter, we will look at how to resolve this reference for the XML document.
</JavaXML:Contents>
 <!-- Leave out until DTD Section
<JavaXML:Copyright> &OReillyCopyright;
</JavaXML:Copyright> -->
</JavaXML:Book>

SAX Readers

Without spending any further time on the preliminaries, let’s begin to code. Our first program will be able to take an XML file as a command-line parameter, and parse that file. We will build document callbacks into the parsing process so that we can display events in the parsing process as they occur, which will give us a better idea of what exactly is going on ―under the hood.‖If you are not sure whether you have the SAX classes, look at the jar file or class structure used by your parser. The SAX classes are packaged in the org.xml.sax structure. The latest version of these includes classes in this root directory, as well as 9 classes in org.xml.sax.helpers and 2 in org.xml.sax.ext. If you are missing any of these classes, you should try to contact your parser’s vendor to see why the classes were not included with your distribution. It is possible that some classes may have been left out if they are not supported in whole.

These class counts are for SAX 2.0 as well; fewer classes may appear if only SAX 1.0 is supported. The first thing we need to do is get an instance of a class that conforms to the SAX org.xml.sax.XMLReader interface.

Instantiating a Reader

 SAX provides an interface that all SAX-compliant XML parsers should implement. This allows SAX to know exactly what methods are available for callback and use within an application. For example, the Xerces main SAX parser class, org. apache.xerces.parsers.SAXParser, implements the org.xml.sax.XMLReader interface. If you have access to the source of your parser, you should see the same interface implemented in your parser’s main SAX parser class. Each XML parser must have one class (sometimes more!) that implements this interface, and that is the class we need to instantiate to allow us to parse

XML: XMLReader parser = new
SAXParser(); // Do something with the parser
parser.parse(uri);
For those of you new to SAX entirely, it may be a bit confusing not to see the instance variable we used named reader or XMLReader. While that would be a normal convention, the SAX 1.0 classes defined the main parsing interface as Parser, and a lot of legacy code has variables named parser because of that naming.

Example
SAX Parser Example

 import org.xml.sax.XMLReader; // Import your vendor's XMLReader implementation here
import org.apache.xerces.parsers.SAXParser;
/** *
<b>
<code>SAXParserDemo</code>
</b>
Will take an XML file and parse it using SAX, displaying the callbacks in the parsing lifecycle. *
* @author *
<a href="mailto:brettmclaughlin@earthlink.net">Brett McLaughlin</a>
*@version 1.0 */ public class SAXParserDemo
{
/** * <p> * This parses the file, using registered SAX handlers, and outputs * the events in the parsing process cycle. *
</p> * * @param uri <code>String</code> URI of file to parse. */
public void performDemo(String uri)
{
System.out.println("Parsing XML File: " + uri + "\n\n");
// Instantiate a parser
 XMLReader parser = new SAXParser();
 } /** * <p> * This provides a command-line entry point for this demo. *
</p> */ public static void main(String[] args)
{
 if
(args.length != 1) { System.out.println("Usage: java SAXParserDemo [XML URI]");
System.exit(0);
 }
String uri = args[0];
 SAXParserDemo parserDemo = new
SAXParserDemo();
parserDemo.performDemo(uri);
}
}
You should be able to load and compile this program if you made the preparations talked about earlier to ensure the SAX classes are in your class path. This simple program doesn’t do much yet; in fact, if you run it and supply a bogus filename or URI as an argument, it should happily grind away and do nothing, other than print out the initial ―Parsing XML file‖ message. That’s because we have only instantiated a parser, not requested that our XML document be parsed.

Parsing the Document

Once a parser is loaded and ready for use, we can instruct it to parse our
document. This is conveniently handled by the parse() method of org.xml.sax.XMLReader, and this method can accept either an org.xml.sax.InputSource,or a simple string URI. For now, we will defer talking about using an InputSource and look at passing in a simple URI. Although this URI could be a network-accessible address, we will use the full path to the XML document we prepared for this use earlier. If you did choose to use a URL for network accessible XML documents, you should be aware that the application would have to resolve the URL before passing it to the parser (generally this requires only some form of network connectivity). We need to add the parse() method to our program, as well as two exception handlers. Because the document must be loaded, either locally or remotely, a java.io.IOException can result, and must be caught. In addition, the org.xml. sax.SAXException can be thrown if problems occur while parsing the document. So we can add two more import statements and a few lines of code, and have an application that parses XML ready to use:

import java.io.IOException;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
 // Import your vendor's XMLReader implementation here import
org.apache.xerces.parsers.SAXParser; ... /** * <p> * This parses the file, using registered
SAX handlers, and outputs * the events in the parsing process cycle. * </p> * @param uri
<code>String</code> URI of file to parse. */
 public void performDemo(String uri)
{
System.out.println("Parsing XML File: " + uri + "\n\n");
try
{ // Instantiate a parser
XMLReader parser = new SAXParser(); // Parse the document parser.parse(uri);
}
Catch (IOException e)
{
System.out.println("Error reading URI: " + e.getMessage());
}
catch (SAXException e)
{
System.out.println("Error in parsing: " + e.getMessage());
}
}

Compile these changes and you are ready to execute the parsing example. You should specify the full
path to your file as the first argument to the program:

 D:\prod\JavaXML> java SAXParserDemo
D:\prod\JavaXML\contents\contents.xml Parsing XML File:
D:\prod\JavaXML\contents\contents.xml
Using an InputSource

Instead of using a full URI, the parse() method may also be invoked with an org. xml.sax.InputSource as an argument. There is actually remarkably little to comment on in regard to this class; it is used as a helper and wrapper class more than anything else. An InputSource simply encapsulates information about a single object. While this isn’t very helpful in our example, in situations where a system identifier, public identifier, or a stream may all be tied to one URI, using an InputSource for encapsulation can become very handy. The class has accessor and mutator methods for its system ID and public ID, a character encoding, a byte stream (java.io.InputStream), and a character stream (java.io.Reader). Passed as an argument to the parse() method, SAX also guarantees that the parser will never modify the InputSource.

4.7 TRANSFORMING XML DOCUMENTS
JAXP

The Java API for XML Processing (JAXP) makes it easy to process XML data using applications written in the Java programming language. JAXP leverages the parser standards SAX (Simple API for XML Parsing) and DOM (Document Object Model) so that you can choose to parse your data as a stream of events or to build a tree-structured representation of it. The latest versions of JAXP also support the XSLT (XML Stylesheet Language Transformations) standard, giving you control over the presentation of the data and enabling you to convert the data to other XML documents or to other formats, such as HTML. JAXP also provides namespace support, allowing you to work with schemas that might otherwise have naming conflicts. Designed to be flexible, JAXP allows you to use any XML-compliant parser from within your application. It does this with what is called a plug ability layer, which allows you to plug in an implementation of the SAX or DOM APIs. The plug ability layer also allows you to plug in an XSL processor, which lets you transform your XML data in a variety of ways, including the way it is displayed.

The SAX API

The Simple API for XML (SAX) defines an API for an event-based parser. Being event-based means that the parser reads an XML document from beginning to end, and each time it recognizes a syntax construction, it notifies the application that is running it. The SAX parser notifies the application by calling methods from the ContentHandler interface. For example, when the parser comes to a less than symbol ("<"), it calls the startElement method; when it comes to character data, it calls the characters method; when it comes to the less than symbol followed by a slash ("</"), it calls the endElement method, and so on. To illustrate, let's look at part of the example XML document from the first section and walk through what the parser does for each line. (For simplicity, calls to the method ignorableWhiteSpace are not included.)

<priceList> [parser calls startElement] <coffee> [parser calls startElement]
<name>Mocha Java</name> [parser calls startElement, characters, and endElement]
<price>11.95</price> [parser calls startElement, characters, and endElement]
</coffee> [parser calls endElement]

The default implementations of the methods that the parser calls do nothing, so you need to write a subclass implementing the appropriate methods to get the functionality you want. For example, suppose you want to get the price per pound for Mocha Java. You would write a class extending DefaultHandler (the default implementation of ContentHandler) in which you write your own implementations of the methods startElement and characters.. In this example, the price list is a file, but the parse method can also take a variety of other input sources, including an InputStream object, a URL, and an InputSource object.

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse("priceList.xml", handler);

The result of calling the method parse depends, of course, on how the methods in handler were implemented. The SAX parser will go through the file priceList.xml line by line, calling the appropriate methods. In addition to the methods already mentioned, the parser will call other methods such as startDocument, endDocument, ignorableWhiteSpace, and processingInstructions, but these methods still have their default implementations and th met.

Note that the SAX parser will have to invoke both methods more than once before the conditions for printing the price are met.
public void startElement(..., String elementName, ...)
{
if(elementName.equals("name"))
{
inName = true;
}
else if(elementName.equals("price") && inMochaJava )
{
inPrice = true; inName = false;
}
}
public void characters(char [] buf, int offset, int len)
{
String s = new String(buf, offset,len);
if (inName && s.equals("Mocha Java"))
{
inMochaJava = true; inName = false;
}
else if (inPrice)
{
System.out.println("The price of Mocha Java is: " + s);
inMochaJava = false;
inPrice = false;
}
}
}
Once the parser has come to the Mocha Java coffee element, here is the relevant state after
the following method calls:
next invocation of startElement -- inName is true
next invocation of characters -- inMochaJava is true
next invocation of startElement -- inPrice is true
next invocation of characters -- prints price

The SAX parser can perform validation while it is parsing XML data, which means that it checks that the data follows the rules specified in the XML document's schema. A SAX parser will be validating if it is created by a SAXParserFactory object that has had validation turned on. This is done for the SAXParserFactory object factory in the following line of code. factory.setValidating(true); So that the parser knows which schema to use for validation, the XML document must refer to the schema in its DOCTYPE declaration. The schema for the price list is priceList.DTD, so the DOCTYPE declaration should be similar to this:

<!DOCTYPE PriceList SYSTEM "priceList.DTD">

The DOM API

The Document Object Model (DOM), defined by the W3C DOM Working Group, is a set of interfaces for building an object representation, in the form of a tree, of a parsed XML document. Once you build the DOM, you can manipulate it with DOM methods such as insert and remove, just as you would manipulate any other tree data structure. Thus, unlike a SAX parser, a DOM parser allows random access to particular pieces of data in an XML document. Another difference is that with a SAX parser, you can only read an XML document, but with a DOM parser, you can build an object representation of the document and manipulate it in memory, adding a new element or deleting an existing one. The following code fragment creates a DocumentBuilderFactory object, which is then used to create the DocumentBuilder object builder. The code then calls the parse method on builder, passing it the file priceList.xml.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("priceList.xml");

At this point, document is a DOM representation of the price list sitting in memory. The following code fragment adds a new coffee (with the name "Kona" and a price of "13.50") to the price list document. Because we want to add the new coffee right before the coffee whose name is "Mocha Java", the first step is to get a list of the coffee elements and iterate through the list to find "Mocha Java".
Node rootNode = document.getDocumentElement();
NodeList list = document.getElementsByTagName("coffee"); // Loop through the list.
for (int i=0; i <list.getLength(); i++)
{
 thisCoffeeNode = list.item(i);
Node thisNameNode = thisCoffeeNode.getFirstChild();
 if (thisNameNode == null) continue;
if (thisNameNode.getFirstChild() == null)
continue;
if (! thisNameNode.getFirstChild()instanceof org.w3c.dom.Text)
continue;
String data = thisNameNode.getFirstChild().getNodeValue();
 if (! data.equals("Mocha Java"))
continue; //We're at the Mocha Java node. Create and insert the new //element.
Node newCoffeeNode = document.createElement("coffee");
Node newNameNode =document.createElement("name");
Text tnNode = document.createTextNode("Kona");
newNameNode.appendChild(tnNode);
Node newPriceNode = document.createElement("price");
Text tpNode = document.createTextNode("13.50");
newPriceNode.appendChild(tpNode);
newCoffeeNode.appendChild(newNameNode);
newCoffeeNode.appendChild(newPriceNode);
rootNode.insertBefore(newCoffeeNode,
thisCoffeeNode);
break;
}
Note that this code fragment is a simplification in that it assumes that none of the nodes it accesses will be a comment, an attribute, or ignorable white space.

XML Namespaces

All the names in a schema, which includes those in a DTD, are unique, thus avoiding ambiguity. However, if a particular XML document references multiple schemas, there is a possibility that two or more of them contain the same name. Therefore, the document needs to specify a namespace for each schema so that the parser knows which definition to use when it is parsing an instance of a particular schema.

There is a standard notation for declaring an XML Namespace, which is usually done in the root element of an XML document. In the following namespace declaration, the notation xmlns identifies nsName as a namespace, and nsName is set to the URL of the actual namespace:
<priceList xmlns:nsName="myDTD.dtd"
xmlns:otherNsName="myOtherDTD.dtd">
...
</priceList>

Within the document, you can specify which namespace an element belongs to as follows:
<nsName:price> ...

To make your SAX or DOM parser able to recognize namespaces, you call the method setNamespaceAware(true) on your ParserFactory instance. After this method call, any parser that the parser factory creates will be namespace aware.

The XSLT API

XML Stylesheet Language for Transformations (XSLT), defined by the W3C XSL Working Group, describes a language for transforming XML documents into other XML documents or into other formats. To perform the transformation, you usually need to supply a style sheet, which is written in the XML Stylesheet Language (XSL). The XSL style sheet specifies how the XML data will be displayed, and XSLT uses the formatting instructions in the style sheet to perform the transformation. JAXP supports XSLT with the javax.xml.transform package, which allows you to plug in an XSLT transformer to perform transformations.

Transforming a DOM Tree to an XML Document

To transform the DOM tree created in the previous section to an XML document, the following code fragment first creates a Transformer object that will perform the transformation.

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();

Using the DOM tree root node, the following line of code constructs a DOMSource object as the source of the transformation.

DOMSource source = new DOMSource(document);

The following code fragment creates a StreamResult object to take the results of the transformation and transforms the tree into an XML file.
File newXML = new File("newXML.xml");
FileOutputStream os = new FileOutputStream(newXML);
StreamResult result = new StreamResult(os);
transformer.transform(source, result);

Transforming an XML Document to an HTML Document

You can also use XSLT to convert the new XML document, newXML.xml, to HTML using a style sheet. When writing a style sheet, you use XML Namespaces to reference the XSL constructs. For example, each style sheet has a root element identifying the style

To perform the transformation, you need to obtain an XSLT transformer and use it to apply the style sheet to the XML data. The following code fragment obtains a transformer by instantiating a TransformerFactory object, reading in the style sheet and XML files, creating a file for the HTML output, and then finally obtaining the Transformer object transformer from the TransformerFactory object tFactory.

TransformerFactory tFactory = TransformerFactory.newInstance();
String stylesheet = "prices.xsl";
 String sourceId = "newXML.xml";
File pricesHTML = new File("pricesHTML.html");
FileOutputStream os =new FileOutputStream(pricesHTML);
Transformer transformer =tFactory.newTransformer(new StreamSource(stylesheet));
The transformation is accomplished by invoking the transform method, passing it the data and the output stream.

transformer.transform( new StreamSource(sourceId), new StreamResult(os));

This method applies the xslFilename to inFilename and // returns DOM document containing the result.
public static Document parseXmlFile(String inFilename, String xslFilename)
{
try
{ // Create transformer factory
TransformerFactory factory = TransformerFactory.newInstance();
// Use the factory to create a template containing the xsl file
Templates template = factory.newTemplates(new StreamSource( new ileInputStream(xslFilename)));
 // Use the template to create a transformer
Transformer xformer = template.newTransformer(); // Prepare the input file Source
source = new
StreamSource(new FileInputStream(inFilename));

// Create a new document to hold the results

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.newDocument();
Result result = new DOMResult(doc); // Apply the xsl file to the source file and create the DOM tree xformer.transform(source, result);
return doc;
}
catch
(ParserConfigurationException e)
{
 // An error occurred while creating an empty DOM document
}
catch (FileNotFoundException e)
{
}
catch (TransformerConfigurationException e)
{ // An error occurred in the XSL file
}
 catch (TransformerException e)
 { // An error occurred while applying the XSL file
}
return null;
}

XSL Programming

XSL (XML Stylesheet) Programming is the Next Generation of the CSS (Cascading Style Sheet Programming). In CSS, users can use certain style tags which the browsers can understand and are predefined by W3 consortium. XSL takes ths to one step ahead and users can define any tags in the XML file. XML sheets can help in showing the same data in different formats. For example the same data can be shown to different users with different colors and different fonts as required, based on login or personal preferences. In the XML file, reference to the Style sheet to be used is given using the Following syntax.

 <?xml-stylesheet href="doc.xsl" type="text/xsl"?>

Here we are referring to a style sheet called doc.xsl. If the Stylesheet exists in the same directory as the XML file, then no extra parameters are required while defining Stylesheet. If it exists at a different location, then you can declare it as http://www.<your sitelocation.com/styles/doc.xsl.

The next parameter indicates that the page to be shown out is a StyleSheet. For properly viewing the page, in the MIME types definitions under your Application server, you need to map XSL handler to use text/html. For example in Orion Server (http://www.orionserver.com), the Servlet which handles XSL requests is com.evermind.servlet.XSLServlet. In the File global-web-application.xml you need to declare the Mime Type for XML to be text/html. Here's the Syntax for doing this,

<servletchaining servlet-name="xsl" mime-type="text/html" />

XML Style Sheet (XSL) Syntax
XSL is used to define, how the XML file should be converted so that it can seen in the required format in the Browser. For Example say in the XML file we declare a Tag called

<showbold>This is The Heading Text </showbold> ,

and you want to show the Text inside these tags in a different Font and Color , then in your XSL file you would declare it as
<xsl:template match="showbold">
<b>
<font color="#FF0000" face="Arial" size="3">
<xsl:apply-templates/>
</font></b>
</xsl:template>

Here as soon as the Tag "showbold" is encountered in the XML file, then automatically the Text is replaced with Different Font size and color in bold. This is just an example. In real time, some tags, will be creating Table and show the Data in a well formatted way. Also note that tag "showbold" is not part of the standard HTML and here you have defined a Custom Tag.
<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
 <xsl:template match="/">
<html>
 <body>
 <table border="2" bgcolor="blue"> <tr> <th>Title</th> <th>Author</th>
<th>Publisher</th>
</tr> <xsl:for-each select="LIBRARY/BOOK"> <tr>
<td><xsl:value-of select="TITLE"/>
</td>
<td><xsl:value-of select="AUTHOR"/>
</td>
 <td><xsl:value-of select="PUBLISHER"/>
</td>
 </tr> </xsl:for-each> </table>
 </body>
</html>
</xsl:template>
</xsl:stylesheet>

Also note that when we say xsl:value-of select="PUBLISHER , then it retrieves the Value given inside the Tags </PUBLISHER> within the current Tag <BOOK>. XSL COMPONENT VIEW XSL is actually is a collection of three separate W3C recommendations
1. XSLT
2. XPath
3. XSL-FO

The next image shows how the input elements presented in the list are filtered depending on the context node. The template selects the "personnel", the xsl:for-each selects "person" elements. The "person" element is thus the context for the evaluation of the test. The context is further changed by the partial XPath expression edited so far, the result being the "family" added to the completion list.

Content completion offers the list of components from included/imported XSLT stylesheets

The content completion offers XSLT variables, templates, functions and modes not only from the current stylesheet but also from the included or imported ones.

Allow Different Element Colors Depending on XML Prefix

This allows for instance to have the XSLT elements in a different color than the result elements, or the XML schema elements different from the elements used inside annotations. You can add your own prefixes to the list of prefix to color mappings. In the next image, the "fo" prefix has been mapped to green.

XSLT Input Document View

This view presents the tree structure of the XML document set as input for the current stylesheet in the associated transformation scenario. You can create templates or other XSLT snippets by dragging the nodes from the tree into the stylesheet. The generated XPath expressions are context aware. For example dragging the node "/personnel/person/name" into a xsl:template matching "person" will insert for instance an "xsl:for-each" with the select attribute equal to "name", while dragging the same node into a template matching "personnel", will set a "person/name" as value of the select attribute.

4.8 SELECTING XML DATA:XPATH

XPath is used to navigate through elements and attributes in an XML document.XPath is a major element in W3C's XSLT standard - and XQuery and XPointer are both built on XPath expressions.

XPath : Introduction
XPath is a language for finding information in an XML document.

What You Should Already Know
Before you continue you should have a basic understanding of the follow

HTML / XHTML
XML / XML Namespaces
If you want to study these subjects first, find the tutorials on our Home page.

FIG 4.1XPath Path Expressions
WHAT IS XPATH?
XPath is a syntax for defining parts of an XML document
XPath uses path expressions to navigate in XML documents
XPath contains a library of standard functions
XPath is a major element in XSLT
XPath is a W3C recommendation

XPath is Used in XSLT

XPath is a major element in the XSLT standard. Without XPath knowledge you will not be able to create XSLT documents. XQuery and XPointer are both built on XPath expressions. XQuery 1.0 and XPath 2.0 share the same data model and support the same functions and operators.

XPATH is a W3C Recommendation

XPath became a W3C Recommendation 16. November 1999.XPath was designed to be used by XSLT, XPointer and other XML parsing software.

XPath Nodes
Nodes

In XPath, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction, comment, and document nodes. XML documents are treated as trees of nodes. The topmost element of the tree is called the root element. Look at the following XML document:
<?xml version="1.0" encoding="ISO-8859-1"?>
 <bookstore>
<book>
<title lang="en">Harry Potter</title> <author>J K. Rowling</author>
 <year>2005</year>
<price>29.99</price>
 </book>
 </bookstore>
 Example of nodes in the XML document above:
 <bookstore> (root element node)
 <author>J K. Rowling</author> (element node)
lang="en" (attribute node)

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
..
Selects the parent of the current node
@
Selects attributes


In the table below we have listed some path expressions and the result of the expressions

Path Expression
Result
bookstore
Selects all the child nodes of the bookstore element
/bookstore
Selects the root element bookstore Note: If the path starts with a slash ( / ) it always represents an absolute path to an element!
bookstore/book
Selects all book elements that are children of bookstore
//book
Selects all book elements no matter where they are in the

Predicates

Predicates are used to find a specific node or a node that contains a specific value. Predicates are always embedded in square brackets.

Selecting Several Paths :

By using the | operator in an XPath expression you can select several paths. In the table below we have listed some path expressions and the result of the expressions:

Path Expression
Result
//book/title | //book/price
Selects all the title AND price elements of all book elements
//title | //price
Selects all the title AND price elements in the document
/bookstore/book/title | //price
Selects all the title elements of the book element of the bookstore element AND all the price elements in the document


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>

XPath Axes

 An axis defines a node-set relative to the current node.

AxisName
Result
ancestor
Selects all ancestors (parent, grandparent, etc.) of the current node
ancestor-or-self
Selects all ancestors (parent, grandparent, etc.) of the current node and the current node itself
attribute
Selects all attributes of the current node
child
Selects all children of the current node
descendant
Selects all descendants (children, grandchildren, etc.) of the current node
descendant-or-self
Selects all descendants (children, grandchildren, etc.) of the current node and the current node itself
following
Selects everything in the document after the closing tag of the current node
following-sibling
Selects all siblings after the current node
namespace
Selects all namespace nodes of the current node
parent
Selects the parent of the current node
preceding
Selects everything in the document that is before the start tag of the current node
preceding-sibling
Selects all siblings before the current node
self
Selects the current node

Location Path Expression
A location path can be absolute or relative. An absolute location path starts with a slash ( / ) and a relative location path does not. In both cases the location path consists of one or more steps, each separated by a slash:

An absolute location path:
 /step/step/...
A relative location path:
 step/step/...

Each step is evaluated against the nodes in the current node-set.
 A step consists of: an axis (defines the tree-relationship between the selected nodes and the current node)
a node-test (identifies a node within an axis)  zero or more predicates (to further refine the selected node set)

4 . 9 TEMPLATE BASED TRANSFORMATION :XSLT

XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents.XSLT stands for XSL Transformations. In this tutorial you will learn how to use XSLT to transform XML documents into other formats, like XHTML.

XSL Languages

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 the 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

XSLT Introduction

XSLT is a language for transforming XML documents into XHTML documents or to other XML documents.XPath is a language for navigating in XML documents.

What is XSLT?

XSLT stands for XSL Transformations
XSLT is the most important part of XSL
XSLT transforms an XML document into another XML document
XSLT uses XPath to navigate in XML documents
XSLT is a W3C Recommendation



XSLT = XSL Transformations

XSLT is the most important part of XSL.XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element.With XSLT you can add/remove elements and attributes to or from the output file. You can also rearrange and sort elements, perform tests and make decisions about which elements to hide and display, and a lot more.A common way to describe the transformation process is to say that XSLT transforms an XML source-tree into an XML result-tree.

XSLT Uses XPath

XSLT uses XPath to find information in an XML document. XPath is used to navigate through elements and attributes in XML documents.
If you want to study XPath first, please read our XPath Tutorial.

How Does it Work?

In the transformation process, XSLT uses XPath to define parts of the source document that should match one or more predefined templates. When a match is found, XSLT will transform the matching part of the source document into the result document.

XSLT - Transformation

Example study: How to transform XML into XHTML using XSLT.

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:
<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">


Create an XSL Style Sheet

Then you create an XSL Style Sheet ("cdcatalog.xsl") with a transformation template:
<?xmlversion="1.0"encoding="ISO-8859-1"?>
<xsl:stylesheetversion="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:template match="/">
 <html>
<body>
 <h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr> <xsl:for-each select="catalog/cd">
 <tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
 </tr>
 </xsl:for-each>
</table>
 </body>
 </html>
 </xsl:template>
</xsl:stylesheet>

Link the XSL Style Sheet to the XML Document

Add the XSL style sheet reference to your XML document ("cdcatalog.xml"):

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<catalog>
<cd>
<title>EmpireBurlesque</title>
<artist>Bob Dylan</artist>
<country>USA</country>
<company>Columbia</company>
 <price>10.90</price>
 <year>1985</year>
</cd>
 .
 .
 </catalog>

XSLT Functions

XSLT includes over 100 built-in functions. There are functions for string values, numeric values, date and time comparison, node and QName manipulation, sequence manipulation, Boolean values, and more
 The default prefix for the function namespace is fn:  The URI of the function namespace is: http://www.w3.org/2005/xpath-functions

 Tip: Functions are often called with the fn: prefix, such as fn:string(). However, since fn: is the default prefix of the namespace, the function names do not need to be prefixed when called.

The reference of all the built-in XSLT 2.0 functions is located in our XPath tutorial. In addition, there are the following built-in XSLT functions:

Name
Description
current()
Returns the current node
document()
Used to access the nodes in an external XML document
element-available()
Tests whether the element specified is supported by the XSLT processor


4.10 DISPLAYING XML FILES IN A BROWSER

You can use Microsoft® Internet Explorer 5.0 or later to view XML documents in the browser, just as you would view HTML pages. Unlike HTML, XML does not predefine display properties for specific elements. Therefore, XML requires a separate style sheet that specifies how the XML data should be displayed. This separation of XML content from its presentation allows the content to be easily repurposed.

To view an XML file in Internet Explorer, you can specify a style sheet the following ways.

Use the default style sheet, which presents the file as a collapsible tree.
Specify a specific style sheet at the top of the XML file, in an href attribute such as the following:

Copy
 <?xml-stylesheet type="text/xsl" href="myfile.xsl" ?>

Specify any style sheet at the command prompt, for example:

Copy
 c:\bat\msxsl mydata.xml mytransform.xsl -o myoutput.html

4.11.CASE STUDY Displaying data using CSS style sheet.

Style sheet example 1

title
 {
 font-family:helvetica;font-size: 30px;display:block;color:red;
 }
items
{
display: block;font-family:helvetica;font-size: 12px;color: black;
 }
 item
{
 display: block;border:1px solid gray;margin: 3mm;font-family:helvetica;
 font-size: 12px;color: black;
 }
question
{
display: block;font-family:helvetica;font-size: 16px;
font-weight: bold;color: blue;
}
answer
{
display: block;font-family:helvetica;font-size: 12px;color: black;
}




Result on IE6:

The Example Quiz


In Which continent is the country japan located?
Asia
Europe
Africa
America
Which one cannot swim?
Tuna
Cow
Whale
L0bster
How many points are on a hexagon?
5
6
7
8


Style sheet  example 2:

title
{
font-family:helvetica;
font-size: 30px;
 display:block;
color:white;
background:rgb(0,0,0);
 }
 items
{
bacgkround:#DDDDDD;
 display: block;
 font-family:helvetica;
font-size: 12px;
color: black;
}
item
{
display: block;
margin: 0mm;
font-family:helvetica;
 font-size: 12px;
 color: black;
}
question
 {
 display: block;
font-family:helvetica;
font-size: 16px;
font-weight: bold;
 color: blue;
position: relative;
 background:#DDDDDD;
 border: solid 1px;
 } answer
 {
display: block;
 position:relative;
 left:50px; font-family:helvetica;
font-size: 12px;
color: black;
background:#DDDD88;
 }












Result on IE6:



Displaying Data Using XSLT.

Hides answers: example 1

<?xml version="1.0"?>
<quiz:stylesheet xmlns:quiz="http://www.w3.org/1999/XSL/Transform"
 version="1.0">
<quiz:template match="/">
<html>
 <head>
<title>Quiz Example formatted with XSLT</title></head>
 <body>
 <quiz:apply-templates />
 </body>
</html>
 </quiz:template>
 <quiz:template match="title">
 <H1><quiz:value-of select="."/></H1>
 </quiz:template>
<quiz:template match="answer">
 </quiz:template>
<quiz:template match="question">
 <b><quiz:value-of select="."/></b><br/>
 </quiz:template>
</quiz:stylesheet>

Result on IE6:

The Example Quiz

In Which continent is the country japan located?
Which one cannot swim?
How many points are on a hexagon?


4.12 RELATED TECHNOLOGIES
Below is a list of XML-related technologies.

DTD (Document Type Definition) is used to define the legal elements in an XML document.

XSD (XML Schema) is an XML-based alternative to DTDs.

XHTML (Extensible HTML) is a stricter and cleaner version of HTML.

XSL (Extensible Style Sheet Language) - XSL consists of three parts: XSLT - a language for transforming XML documents, XPath - a language for navigating in XML documents, and XSL-FO - a language for formatting XML documents.
XSLT (XSL Transformations) is used to transform XML documents into other XML formats, like XHTML.

XML DOM (XML Document Object Model) defines a standard way for accessing and manipulating XML documents.

XPath is a language for navigating in XML documents.

 XSL-FO (Extensible Style Sheet Language Formatting Objects) is an XML based markup language describing the formatting of XML data for output to screen, paper or other media.

XLink (XML Linking Language) is a language for creating hyperlinks in XML documents.

XPointer (XML Pointer Language) allows the XLink hyperlinks to point to more specific parts in the XML document.

XForms (XML Forms) uses XML to define form data.
 XQuery (XML Query Language) is designed to query XML data.

SOAP (Simple Object Access Protocol) is an XML-based protocol to let applications exchange information over HTTP.

WSDL (Web Services Description Language) is an XML-based language for describing web services.

RDF (Resource Description Framework) is an XML-based language for describing web resources.

RSS (Really Simple Syndication) is a format for syndicating news and the content of news-like sites.

WAP (Wireless Application Protocol) was designed to show internet contents on wireless clients, like mobile phones.

SMIL (Synchronized Multimedia Integration Language) is a language for describing audiovisual presentations. SVG (Scalable Vector Graphics) defines graphics in XML format

4.13 JSP

Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database driven web applications. JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy. JSP pages are efficient, it loads into the web servers memory on receiving the request very first time and the subsequent calls are served within a very short period of time

Installing JSP

First of all download JavaServer Web Development Kit (JSWDK1.0.1) from http://java.sun.com/products/servlet/download.html. JSWDK comes with full documentation and it's very easy to install, so the installation process is not mentioned here. The JSWDK is the official reference implementation of the servlet 2.1 and JSP 1.0 specifications. It is used as a small stand-alone server for testing servlets and JSP pages before they are deployed to a full Web server that supports these technologies. It is free and reliable, but takes quite a bit of effort to install and configure.

Other Servers that support JSP
Apache Tomcat. Tomcat is the official reference implementation of the servlet 2.2 and JSP 1.1 specifications. It can be used as a small stand-alone server for testing servlets and JSP pages, or can be integrated into the Apache Web server.
Allaire JRun.

JRun is a servlet and JSP engine that can be plugged into Netscape Enterprise or FastTrack servers, IIS, Microsoft Personal Web Server, older versions of Apache, O’Reilly’s WebSite, or StarNine WebSTAR.

Developing first JSP
 Java Server Pages are save with .jsp extension. Following code which generates a simple html page.

Execute the example.
 <html>
 <head>
 <title>First JSP page.</title>
 </head>
<body>
 <p align="center"><font color="#FF0000" size="6"><%="Java Developers Paradise"%></font></p>
<p align="center"><font color="#800000" size="6"><%="Hello JSP"%> </font></p>
</body>
 </html>
In jsp java codes are written between '<%' and '%>' tags. So it takes the following form :
 <%= Some Expression %> In this example we have use
<%="Java Developers Paradise"%>

What is Java Server Pages Technology?

o JSP is a technology, specified and introduced by Sun Microsystems.
o Create dynamic web content (HTML, XML, ...) for a Web Application.
o Make it easier/cleaner to mix static HTML parts with dynamic Java servlet
code.

JSP could make external calls to other Web components as Java Beans, Java Servlet,
o applets or to forward execution to another JSP document.
o Write Once, Run Anywhere

JSP Elements
Directives

Providing information for the page as a whole. This information is used in translation or execution the page
 <%@ directive-name [attribute=―value‖ attribute=―value‖]%>

Scripting elements

Java coding elements as declarations, expressions, scriptlets and comments. They produce the dynamic output.

Objects and Scopes

JSP page contains objects, implicitly or explicitly created, which are accessible in certain scope.

Actions

An action creates objects or manages the JSP output.

Directives

page

Specifies page dependant attributes like language, libraries to import, error page or buffer size. If the JSP page uses an error page, the buffer size cannot be ―none‖

. <%@ page info="a hello world example" %>

Attributes:language,import,session,buffer,autoflush,errorpage,content type

include
Used when an resource, presenting text or code, should be included in the page. The resource path is specified relatively to the JSP path

. <%@ include file="response.jsp" %>

taglib

Specifies the location of tag library description (TLD) file, which describes a library of custom JSP tags, which will be used in the page.

 <%@ taglib uri=―csp-taglib.tld‖ prefix=―cwp‖ %>


Scripting elements

Declarations

The declarations are statements declaring methods or member variables, that are used in the page
. <%! … %> <%! int i = 0; %> <%! int a, b; double c; %> <%! Circle a = new Circle(2.0); %>

Expressions

These are Java expressions, which result is being converted to string and embedded in HTML code, where they are encountered.
 <%= …%>

<%= Math.sqrt(2) %>
<%= items[i] %


<%= a + b + c %>
<%= new java.util.Date() %>

Scriptlets

Scriptlets are fragments of Java code, and located between HTML code fragments.
 <% … %>
 <%
String name = null;
if (request.getParameter("name") == null) {
%>

Comments
 Comments in the scriptlets are the same as in Java.
 <!-- … -- >






4.14 JSP AND SERVLET

What are Java Servlets?

Servlets are Java technology's answer to CGI programming. They are programs that run on a Web server and build Web pages. Building Web pages on the fly is useful (and commonly done) for a number of reasons:

The Web page is based on data submitted by the user.

For example the results pages from search engines are generated this way, and programs that process orders for e-commerce sites do this as well.

The data changes frequently.

For example, a weather-report or news headlines page might build the page dynamically, perhaps returning a previously built page if it is still up to date.

The Web page uses information from corporate databases or other such sources.

 For example, you would use this for making a Web page at an on-line
store that lists current prices and number of items in stock.

What are the Advantage of Servlets Over "Traditional" CGI?

Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technologies. (More importantly, servlet developers get paid more than Perl programmers :-).

Efficient.

With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times.



Convenient.

Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.

Powerful.

 Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't).

Portable.

 Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server.
Inexpensive.

 There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive

BASIC JSP?

Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically-generated HTML. Many Web pages that are built by CGI programs are mostly static, with the dynamic part limited to a few small locations. But most CGI variations, including servlets, make you generate the entire page via your program, even though most of it is always the same. JSP lets you create the two parts separately. Here's an example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 <HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
 <BODY>
 <H1>Welcome to Our Store</H1>
<SMALL>Welcome,
 <!-- User name is "New User" for first-time visitors -->
 <% out.println(Utils.getUserNameFromCookie(request)); %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
 <P>
Regular HTML for all the rest of the on-line store's Web page.
 </BODY></HTML>

What are the Advantages of JSP?

vs. Active Server Pages (ASP)

 ASP is a similar technology from Microsoft. The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS-specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers.

vs. Pure Servlets.

JSP doesn't give you anything that you couldn't in principle do with a servlet. But it is more convenient to write (and to modify!) regular HTML than to have a zillion println statements that generate the HTML. Plus, by separating the look from the content you can put different people on different tasks: your Web page design experts can build the HTML, leaving places for your servlet programmers to insert the dynamic content.

vs. Server-Side Includes (SSI).
SSI is a widely-supported technology for including externally-defined pieces into a static Web page. JSP is better because it lets you use servlets instead of a separate program to generate that dynamic part. Besides, SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like.

vs. JavaScript.
JavaScript can generate HTML dynamically on the client. This is a useful capability, but only handles situations where the dynamic information is based on the client's environment. With the exception of cookies, HTTP and form submission data is not available to JavaScript. And, since it runs on the client, JavaScript can't access server-side resources like databases, catalogs, pricing information, and the like.

vs. Static HTML.
 Regular HTML, of course, cannot contain dynamic information. JSP is so easy and convenient that it is quite feasible to augment HTML pages that only benefit marginally by the insertion of small amounts of dynamic data. Previously, the cost of using dynamic data would preclude its use in all but the most valuable instances
4.15 RUNNING JSP APPLICATIONS

Installation Documentation#

o http://doc.jspwiki.org/2.4 - Latest official installation documentation
o http://doc.jspwiki.org/2.4/wiki/InstallingJSPWiki - Goes Directlty to the main install wiki
o Tomcat - Apache Tomcat JSPWiki install, Setup and deployment.

Comments and Small Snippets Below:#

* RefactorMe, please!

Please see the README document contained in the JSPWiki distribution for up-to-date information. (The attached version is from the cutting-edge 2.1 series - make sure you read the README of the distribution you are installing, too.)

If you are upgrading, see UpgradingJSPWiki.

Some problems you may find while installing JSPWiki#

The items below are stumbling points people have reported. If you notice an installation problem that you suspect is not yours, please add a description here.  I am trying to import the JSPWiki source code into Netbeans. Does anybody know of a step-by-step tutorial as none of Netbeans imports tools seem to work.

After Installation#
NoClassDefFound#

After you installed JSPWiki you got the exception shown below. Example: ViewPermission class not found in the log you get something like:
 *root cause*
 java.lang.NoClassDefFoundError: ....

Problem:
 you have probably got some old, generated JSPs in your Tomcat work directories. These are referencing the older classes (e.g., ViewPermission class). Make sure you stop Tomcat, flush (delete) your work directory, then restart. - Andrew



4.16 BASIC JSP
 JSP EL

EL means the expression language , it is a simple language for accessing data, it makes it possible to easily access application data stored in JavaBeans components. The jsp expression language allows a page author to access a bean using simple syntax such as $(name). Before JSP 2.0, we could use only a scriptlet, JSP expression, or a custom tag to include server state in the jsp page output. Expression Language (EL) was first introduced in JSTL 1.0. EL makes it easier to integrate server side state with the presentation output. EL expressions are no longer limited to JSTL action attributes, but may be used in any standard or custom action attribute declared to accept a runtime expression. EL expressions can be used in static text. EL expressions can be used directly in template text outside of any actions.

 EL expression is always written between the delimiters ${ and }. In the JSP page response, the result of expression evaluation replaces the expression and its delimiters in the template text. Within tags, expression can be used only in attribute values.

Code of the program is given below:

 <html>
 <head>
 <title> Use of Expression Language in jsp</title>
</head> <%pageContext.setAttribute("pageColor", "#FFFFDF"); %>
 <body>
<table bgcolor= "${pageScope.pageColor}" border ="1" cellpadding="0" cellspacing="0"
align ="center" width="50%" height="50%">
 <tr>
 <td>
 <b>Welcome to the Roseindia.net</b></td>
 </tr>
 <tr> <td>
 You appear to be using the following browser:<br>
${header["user-agent"]}
</td> </tr>
</table>
</body>
 </html>




Output of the Program:


Overview of the JSP Markup Language (JML) Tag Library

OC4J supplies the JSP Markup Language (JML) tag library, which is portable to any standard JSP environment. JML tags, as with those of any standard tag library, are completely compatible with regular JSP script and can be used in any JSP page. JML tags are intended to simplify coding syntax for JSP developers who are not proficient with Java. There are two main categories of JML tags: 1) logic/flow control; 2) bean binding.

This section covers the following topics:
JML Tag Library Philosophy

JML Tag Categories

Note the following requirements for using JML tags:

Verify that the file ojsputil.jar is installed and in your classpath. This file is provided with the OC4J installation.
As with any tag library following the JSP 1.1 specification, the tags of the JML library are specified in an XML-style tag library description (TLD) file, jml.tld. In an Oracle9iAS installation, this file is located in the [Oracle_Home]/j2ee/tlds directory. The TLD file must be deployed with any JSP application that uses JML tags, and specified in a taglib directive for any page using JML tags. The taglib directive supplies a standard universal resource

indicator (URI) to locate the file. The URI syntax is typically application-relative, such as in the following example:
<%@ taglib uri="/WEB-INF/jml.tld" prefix="jml" %>       
JML Tag Library
JavaServer Pages technology is intended for two separate developer communities:

those whose primary skill is Java programming
those whose primary skill is in designing static content, particularly in HTML, and who may have limited scripting experience

The JML tag library is designed to allow most Web developers, with little or no knowledge of Java, to assemble JSP applications with a full complement of program flow-control features.

This model presumes that the business logic is contained in JavaBeans that are developed separately by a Java developer.

JML Tag Categories
The JML tag library covers a feature set split into two functional categories, as summarized in Table 4-1.



Tag Categories
Tags
Functionality
bean binding tags
useVariable useForm useCookie remove
The purpose of these tags is to declare or undeclare a JavaBean at a specified JSP scope. See "Bean Binding Tag Descriptions".
logic/flow control tags
if choose..when..[otherwise] foreach return flush
These tags offer simplified syntax to define code flow, such as for iterative loops or conditional branches. See "Logic and Flow Control Tag Descriptions".

Table 4-1 JML Tag Functional Categories

JSP Markup Language (JML) Tag Descriptions

This section documents the JML tags that are supported in the current JSP runtime implementation, following the JSP 1.1 specification. They are categorized as follows:

Bean Binding Tag Descriptions
Logic and Flow Control Tag Descriptions
JML useForm Tag

This tag provides a convenient syntax for declaring variables and setting them to values passed in from the request.

Syntax

<jml:useForm id = "beanInstanceName"
[ scope = "page" | "request" | "session" | "application" ]
[ type = "string" | "boolean" | "number" | "fpnumber" ]
param = "requestParameterName" />

Attributes

id (required)--Names the variable being declared or referenced.
scope--Defines the duration or scope of the variable (as with a jsp:useBean tag). This attribute is optional; the default scope is page.
type--Specifies the type of the variable. Type specifications refer to JmlString, JmlBoolean, JmlNumber, or JmlFPNumber. This attribute is optional; its default value is "string".
param (required)--Specifies the name of the request parameter whose value is used in setting the variable. If the request parameter exists, then the variable value is always updated, regardless of whether this declaration brings the variable into existence. If the request parameter does not exist, then the variable value remains unchanged.

Example

The following example sets a session variable named user of the type string to the value of the request parameter named user.

<jml:useForm id = "user" type = "string" param = "user" scope = "session" />

This is equivalent to the following:

<jsp:useBean id = "user" class = "oracle.jsp.jml.JmlString" scope = "session" />
<jsp:setProperty name="user" property="value" param = "user" />

JML useCookie Tag

This tag offers a convenient syntax for declaring variables and setting them to values contained in cookies.

Syntax

<jml:useCookie id = "beanInstanceName"
[ scope = "page" | "request" | "session" | "application" ]
[ type = "string" | "boolean" | "number" | "fpnumber" ]
cookie = "cookieName" />

Attributes
id (required)--Names the variable being declared or referenced.
scope-- Defines the duration or scope of the variable. This attribute is optional; the default scope is page.
type-- Identifies the type of the variable. Type specifications refer to JmlString, JmlBoolean, JmlNumber, or JmlFPNumber. This attribute is optional; the default setting is "string".

cookie (required)--Specifies the name of the cookie whose value is used in setting this variable. If the cookie exists, then the variable value is always updated, regardless of whether this declaration brings the variable into existence. If the cookie does not exist, then the variable value remains unchanged.

Example

The following example sets a request variable named user of the type string to the value of the cookie named user.
<jml:useCookie id = "user" type = "string" cookie = "user" scope = "request" />
This is equivalent to the following:

<jsp:useBean id = "user" class = "oracle.jsp.jml.JmlString" scope = "request" />
<%
Cookies [] cookies = request.getCookies();
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("user")) {
user.setValue(cookies[i].getValue());
break;
}
}
%>

JML remove Tag

This tag removes an object from its scope.


Syntax

<jml:remove id = "beanInstanceName"
[ scope = "page" | "request" | "session" | "application" ] />

Attributes

id (required)--Specifies the name of the bean being removed.
scope--This attribute is optional. If not specified, then scopes are searched in the following order: 1) page, 2) request, 3) session, 4) application. The first object whose name matches id is removed.

Example

The following example removes the session user object:
<jml:remove id = "user" scope = "session" />
This is equivalent to the following:
<% session.removeValue("user"); %>

Logic and Flow Control Tag Descriptions

This section documents the following JML tags, which are used for logic and flow control:
JML if Tag
JML choose...when...[otherwise] Tags

4.17 JAVABEANS CLASS AND JSP PAGES

JavaBeans components are Java classes that can be easily reused and composed together into applications. Any Java class that follows certain design conventions can be a JavaBeans component. JavaServer Pages technology directly supports using JavaBeans components with JSP language elements. You can easily create and initialize beans and get and set the values of their properties. This chapter provides basic information about JavaBeans components and the JSP language elements for accessing beans in your JSP pages.

JavaBeans Component Design Conventions

JavaBeans component design conventions govern the properties of the class, and govern the public methods that give access to the properties.

A JavaBeans component property can be
Read/write, read-only, or write-only
Simple, which means it contains a single value, or indexed, which means it represents an array of values

There is no requirement that a property be implemented by an instance variable; the property must simply be accessible using public methods that conform to certain conventions:

For each readable property, the bean must have a method of the form PropertyClass getProperty() { ... }
For each writable property, the bean must have a method of the form setProperty(PropertyClass pc) { ... }

The Duke's Bookstore application JSP pages enter.jsp, bookdetails.jsp, catalog.jsp, and showcart.jsp use the database.BookDB and database.BookDetails JavaBeans components. BookDB provides a JavaBeans component front end to the enterprise bean BookDBEJB. Both beans are used extensively by bean-oriented custom tags (see Tags That Define Scripting Variables). The JSP pages showcart.jsp and cashier.jsp use cart.ShoppingCart to represent a user's shopping cart.

The JSP pages catalog.jsp, showcart.jsp, and cashier.jsp use the util.Currency JavaBeans component to format currency in a locale-sensitive manner. The bean has two writable properties, locale and amount, and one readable property, format. The format property does not correspond to any instance variable, but returns a function of the locale and amount properties.
public class Currency {
 private Locale locale;
private double amount;
public Currency() {
locale = null;
 amount = 0.0;
}
public void setLocale(Locale l) {
 locale = l;
}
public void setAmount(double a) {
 amount = a;
 }
 public String getFormat() {
NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
return nf.format(amount);
 }
}




Why Use a JavaBeans Component?

A JSP page can create and use any type of Java programming language object within a declaration or scriptlet. The following scriptlet creates the bookstore shopping cart and stores it as a session attribute

 <%
ShoppingCart cart = (ShoppingCart)session.
getAttribute("cart");
// If the user has no cart, create a new on
e if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("cart", cart);
}
%>

If the shopping cart object conforms to JavaBeans conventions, JSP pages can use JSP elements to create and access the object. For example, the Duke's Bookstore pages bookdetails.jsp, catalog.jsp, and showcart.jsp replace the scriptlet with the much more concise JSP useBean element:

<jsp:useBean id="cart" class="cart.ShoppingCart" scope="session"/>

Creating and Using a JavaBeans Component

You declare that your JSP page will use a JavaBeans component using either one of the following formats:
<jsp:useBean id="beanName"
 class="fully_qualified_classname" scope="scope"/>

The second format is used when you want to include jsp:setProperty statements, described in the next section, for initializing bean properties.
The jsp:useBean element declares that the page will use a bean that is stored within and accessible from the specified scope, which can be application, session, request, or page. If no such bean exists, the statement creates the bean and stores it as an attribute of the scope object (see Using Scope Objects). The value of the id attribute determines the name of the bean in the scope and the identifier used to reference the bean in other JSP elements and scriptlets.

The following element creates an instance of Currency if none exists, stores it as an attribute of the session object, and makes the bean available throughout the session by the identifier currency:
 <jsp:useBean id="currency" class="util.Currency"
scope="session"/
Setting JavaBeans Component Properties

There are two ways to set JavaBeans component properties in a JSP page: with the jsp:setProperty element or with a scriptlet

 <% beanName.setPropName(value); %>

The syntax of the jsp:setProperty element depends on the source of the property value. Table 12-1 summarizes the various ways to set a property of a JavaBeans component using the jsp:setProperty element.



Value Source
Element Syntax
String constant
<jsp:setProperty name="beanName" property="propName" value="string constant"/>
Request parameter
<jsp:setProperty name="beanName" property="propName" param="paramName"/>
Request parameter name matches bean
<jsp:setProperty name="beanName"
property
property="propName"/> <jsp:setProperty name="beanName" property="*"/>
Expression
<jsp:setProperty name="beanName" property="propName" value="<%= expression %>"/>
1. beanName must be the same as that specified for the id attribute in a useBean element. 2. There must be a setPropName method in the JavaBeans component. 3. paramName must be a request parameter name.

Table 4.2 Setting JavaBeans Component Properties



A property set from a constant string or request parameter must have a type listed in Table 12-2. Since both a constant and request parameter are strings, the Web container automatically converts the value to the property's type; the conversion applied is shown in the table. String values can be used to assign values to a property that has a PropertyEditor class. When that is the case, the setAsText(String) method is used. A conversion failure arises if the method throws an IllegalArgumentException. The value assigned to an indexed property must be an array, and the rules just described apply to the elements.

Property Type
Conversion on String Value
Bean property
Uses setAsText(string-literal)
boolean or Boolean
As indicated in java.lang.Boolean.valueOf(String)
byte or Byte
As indicated in java.lang.Byte.valueOf(String)
char or Character
As indicated in java.lang.String.charAt(0)
double or Double
As indicated in java.lang.Double.valueOf(String)
int or Integer
As indicated in java.lang.Integer.valueOf(String)
float or Float
As indicated in java.lang.Float.valueOf(String)
long or Long
As indicated in java.lang.Long.valueOf(String)
short or Short
As indicated in java.lang.Short.valueOf(String)
Object
new String(string-literal)

Table 4.3 Valid Value Assignments

The Duke's Bookstore application demonstrates how to use the setProperty element and a scriptlet to set the current book for the database helper bean. For example, bookstore3/bookdetails.jsp uses the form
<jsp:setProperty name="bookDB" property="bookId"/>

whereas bookstore2/bookdetails.jsp uses the form
 <% bookDB.setBookId(bookId); %>

The following fragments from the page bookstore3/showcart.jsp illustrate how to initialize a currency bean with a Locale object and amount determined by evaluating request-time expressions. Because the first initialization is nested in a useBean element, it is only executed when the bean is created

. <jsp:useBean id="currency" class="util.Currency"
 scope="session">
<jsp:setProperty name="currency" property="locale"
value="<%= request.getLocale() %>"/>
</jsp:useBean>

<jsp:setProperty name="currency" property="amount"
 value="<%=cart.getTotal()%>"/>

Retrieving JavaBeans Component Properties

There are several ways to retrieve JavaBeans component properties. Two of the methods (the jsp:getProperty element and an expression) convert the value of the property into a String and insert the value into the current implicit out object:

<jsp:getProperty name="beanName" property="propName"/>
<%= beanName.getPropName() %>

For both methods, beanName must be the same as that specified for the id attribute in a useBean element, and there must be a getPropName method in the JavaBeans component.

If you need to retrieve the value of a property without converting it and inserting it into the out object, you must use a scriptlet:

 <% Object o = beanName.getPropName(); %>

Note the differences between the expression has an = after the opening % and does not terminate with a semicolon, as does the scriptlet.

<jsp:getProperty name="currency" property="format"/>

whereas bookstore2/showcart.jsp uses the form
 <%= currency.getFormat() %>

The Duke's Bookstore application page bookstore2/showcart.jsp uses the following scriptlet to retrieve the number of books from the shopping cart bean and open a conditional insertion of text into the output stream:
 <%
// Print a summary of the shopping cart
 int num = cart.getNumberOfItems();
 if (num > 0) {
 %>

Although scriptlets are very useful for dynamic processing, using custom tags  to access object properties and perform flow control is considered to be a better approach. For example, bookstore3/showcart.jsp replaces the scriptlet with the following custom tags:
<bean:define id="num" name="cart" property="numberOfItems" />
 <logic:greaterThan name="num" value="0" >

Figure 4.2 summarizes where various types of objects are stored and how those objects can be accessed from a JSP page. Objects created by the jsp:useBean tag are stored as attributes of the scope objects and can be accessed by jsp:[get|set]Property tags and in scriptlets and expressions. Objects created in declarations and scriptlets are stored as variables of the JSP page's servlet class and can be accessed in scriptlets and
expressions.

Figure 4-2 Accessing Objects from a JSP Page

4.18 TAG LIBRARY AND FILES

ColdFusion developers have been using custom tags extensively for quite a long time. There is a very simple reason for this—in CFML, they are extremely easy to write! JSP custom tags were not quite so easy to write and took considerably longer to develop. But now, with the arrival of Tag Files in JSP 2.0, there is a better, faster, and easier way to build custom tags. You'll need some familiarity with basic JSP syntax, and you have access to Tomcat 5 or some other JSP 2.0 capable server

Your first JSP tag file

A tag file is simply a plain text file with a file extension of .tag. Other than the JSP page directive, all the usual JSP elements can be used within this file. Let's start off really simple: Create a file called tagDemo.tag and put the following text inside:
<%
 String whoAmI = "I am a String within a scriptlet";
%>
 Hello There, <%= whoAmI %>

Hello There, <%= whoAmI %>

That's it; your first tag file is finished! Of course, you haven't yet made use of the tag from inside a jsp. Before you can do that, make sure you save the newly created tagDemo.tag file in a folder called tags inside your Web application's WEB-INF directory. The next step is to create your test jsp page and add the following line:

 <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>

The taglib directive above simply tells the jsp container where to find your tag (the tagdir attribute) and what prefix you will be using to identify your tag (the prefix attribute). To use the tag requires a combination of the prefix and the tag file name in the following form:

 <tags:tagDemo/>

This simply prints the value of the whoAmI variable at the location that the tag appears in the page.

 It is worth mentioning that you can create subfolders off the tags directory to organize your tag files into tag libraries. For example; WEB-INF/tags/shoppingCart/ or WEB-INF/tags/StringUtilities. Just include the proper path when specifying the tagdir attribute. What makes tag files so cool is this simplicity—you did not need to implement any interfaces, compile any java source code, write any tag library descriptors or do any of the usual things you had to do in versions of JSP to get a custom tag up and running. You get all the benefits of a custom tag without the tedium of the traditional class-based custom tag API.

Using doBody to access body content

One of the more useful things about custom tags is the fact that you can access the tag's body content and manipulate or make use of it. For example, let's create a functional implementation for the following:
<tags:uppercase>
 I want to be in capital letters.
</tags:uppercase>

This is where the <jsp:doBody/> action comes in to play. <jsp:doBody/> is an example of a jsp action that can only be used inside a tag file. (You will see another such action shortly). This time your tag file will be called uppercase.tag:

<jsp:doBody var="theBody"/>
<%
String bc = (String) pageContext.getAttribute("theBody");
%>
<%= bc.toUpperCase() %>

The first line is the <jsp:doBody/> declaration. What is important here is the var attribute,
which places a String variable into the pageContext of the tag file. This variable contains the actual body content of the doBody tag. In the next line, you retrieve this value using pageContext.getAttribute("theBody"), and finally you use Java's toUpperCase() function  to print out the all-uppercase value

While the example is trivial, it hopefully demonstrates that tag files have the potential to
shift a lot of that messy scriptlet code into nice reusable tags. Sure, you could do that prior to JSP 2.0 but now it's almost a pleasure instead of a pain.

The <jsp:doBody/> tag has a couple other features you may find interesting.
<%@ tag body-content="scriptless"  %>
<jsp:doBody var="theBody" scope="page"/>
<%
String bc = (String) pageContext.getAttribute("theBody");
%>
<%= bc.toUpperCase() %>

The code above does exactly the same thing as the previous code. But this time I included  the tag directive—another tag-file-only element—and explicitly set its body-content attribute to 'scriptless'. As it happens, this is the default value. When using 'scriptless' you are allowed to put template text, standard actions and custom actions within your tag's  body – but not Java code. When set to 'empty' your tag must not have a body at all, and  finally, when set to 'tagdependant', the tag's body content is treated as pure text.
You should also know about the varReader attribute—you can use this instead of the var attribute to have the variable stored as a java.io.Reader instead of a String. In some  circumstances this may be more efficient when processing large amounts of body content.

4.19 SUPPORT FOR THE MVC PARADIGM
MVC Overview

Flexibility in large component based systems raise questions on how to organize a  project for easy development and maintenance while protecting your data and reputation,  especially from new developers and unwitting users. The answer is in using the Model, View, Control (MVC) architecture. An architecture such as MVC is a design pattern that  describes a recurring problem and its solution where the solution is never exactly the  same for every recurrence. To use the Model-View-Controller MVC paradigm effectively
you must understand the division of labor within the MVC triad. You also must  understand how the three parts of the triad communicate with each other and with other  active views and controllers; the sharing of a single mouse, keybord and display screen  among several applications demands communication and cooperation. To make the best  use of the MVC paradigm you need also to learn about the available subclasses of View  and Controller which provide ready made starting points for your applications.

In the MVC design pattern , application flow is mediated by a central controller. The  controller delegates requests to an appropriate handler. The controller is the means by  which the user interacts with the web application. The controller is responsible for the  input to the model. A pure GUI controller accepts input from the user and instructs the  model and viewport to perform action based on that input. If an invalid input is sent to the  controller from the view, the model informs the controller to direct the view that error
occurred and to tell it to try again.

FIG 4.3 Model, View, Control (MVC) architecture
By dividing the web application into a Model, View, and Controller we can, therefore, separate the presentation from the business logic. If the MVC architecture is designed purely, then a Model can have multiple views and controllers. Also note that the model does not necessarily have to be a Java Servlet. In fact a single Java Servlet can offer multiple models. The Java Servlet is where you would place security login, user authentication and database pooling for example. After all these latter have nothing to do
with the business logic of the web application or the presentation.

MVC in Java Server Pages

Now that we have a convenient architucture to separate the view, how can we  leverage that?  Java Server Pages  (JSP) becomes more interesting because the HTML  content can be separated from the Java business objects. JSP can also make use of Java  Beans. The business logic could be placed inside Java Beans. If the design is architected correctly, a Web Designer could work with HTML on the JSP site without interfering  with the Java developer. The Model/View/Controller architecture also works with JSP. In fact it makes the initial implementation a little easier to write. The controller object is  master Servlet. Every request goes through the controller who retrieves the necessary  model object. The model may interact with other business entities such as databases or  Enterprise Java Beans  (EJB). The model object sends the output results back to the  controller. The controller takes the results and places it inside the web browser session  and forwards a redirect request to a particular Java Server Page. The JSP, in the case, is the view.


FIG 4.4 MVC in Java Server Pages



The controller has to bind a model and a view, but it could be any model and  associated any view. Therein lies the flexibility and perhaps an insight to developing a  very advanced dynamic controller that associates models to a view. The prior sections have concentrated on their being one controller, one model, and
one view. In practice, multiple controllers may exist  -  but only one controls a section of  the application at a time. For example, the administrator's functions may be controlled by one controller and the main logic controlled by  another. Since only one controller can be in control at a given time, they must communicate. There may also be multiple models  -but the controller takes the simplified view representation and maps it to the models appropriately and also translates that response back to the view. The view never needs to
know how the logic is implemented.

4.20 CASE STUDY

Creation Of Blog Using Scriplets

We have already seen how to embed Java expressions in JSP pages by putting them between the <%= and %> character sequences.

But it is difficult to do much programming just by putting Java expressions inside HTML.

JSP also allows you to write blocks of Java code inside the JSP.  You do this by placing your Java code between <% and %> characters (just like expressions, but without  the = sign at the start of the sequence.)

This block of code is known as a "scriptlet".  By itself, a scriptlet doesn't contribute any HTML (though it can, as we will see down below.)  A scriptlet contains Java code that is executed every time the JSP is invoked. 

Here is a modified version of our JSP from previous section, adding in a scriptlet.

<HTML>
<BODY>
<%
// This is a scriptlet.  Notice that the "date"
// variable we declare here is available in the
// embedded expression later on.
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello!  The time is now <%= date %>
</BODY>
</HTML>       

If you run the above example, you will notice the output from the "System.out.println" on the server log.  This is a convenient way to do simple debugging (some servers also have techniques of debugging the JSP in the IDE.  See your server's documentation to see if it offers such a technique.) 

By itself a scriptlet does not generate HTML.  If a scriptlet wants to generate HTML, it can use a variable called "out".  This variable does not need to be declared.  It is already predefined for scriptlets, along with some other variables.  The following example shows how the scriptlet can generate HTML output.

<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello!  The time is now
<%
// This scriptlet generates HTML output
out.println( String.valueOf( date ));
%>
</BODY>
</HTML>
Here, instead of using an expression, we are generating the HTML directly by printing to the "out" variable.  The "out" variable is of type javax.servlet.jsp.JspWriter.

Another very useful pre-defined variable is "request".  It is of type
javax.servlet.http.HttpServletRequest     

A "request" in server-side processing refers to the transaction between a browser and the server.  When someone clicks or enters a URL, the browser sends a "request" to the server for that URL, and shows the data returned.  As a part of this "request", various data is available, including the file the browser wants from the server, and if the request is coming from pressing a SUBMIT button, the information the user has entered in the form fields.

The JSP "request" variable is used to obtain information from the request as sent by the browser.  For instance, you can find out the name of the client's host (if available, otherwise the IP address will be returned.)  Let us modify the code as shown:
<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello!  The time is now
<%
out.println( date );
out.println( "<BR>Your machine's address is " );
out.println( request.getRemoteHost());
%>

</BODY>
</HTML>
A similar variable is "response".  This can be used to affect the response being sent to the browser.  For instance, you can call response.sendRedirect( anotherUrl ); to send a response to the browser that it should load a different URL.  This response will actualy go all the way to the browser.  The browser will then send a different request, to "anotherUrl".  This is a little different from some other JSP mechanisms we will come across, for including another page or forwarding the browser to another page.

Exercise:  Write a JSP to output the entire line, "Hello!  The time is now ..." but use a
scriptlet for the complete string, including the HTML tags.

4.21 RELATED TECHNOLOGIES
JSP SCRIPLETS:

Syntax of JSP Scriptles are:
<%
//java codes
%>

JSP Scriptlets begins with <% and ends %> .We can embed any amount of java code in the JSP Scriptlets. JSP Engine places these code in the _jspService() method. Variables  available to the JSP Scriptlets are:

request:
request represents the clients request and is a subclass of HttpServletRequest. Use
this variable to retrieve the data submitted along the request.

Example:

<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>

response:
response is subclass of HttpServletResponse.

session:
session represents the HTTP session object associated with the request

out:
out is an object of output stream and is used to send any output to the client.

Other variable available to the scriptlets are pageContext, application,config and
exception.

Introduction To JSP Expressions

Syntax of JSP Expressions are:

<%="Any thing"   %>

JSP Expressions start with

Syntax of JSP Scriptles are with <%= and ends with  %>. Between these this you can
put anything and that will converted to the String and that will be displayed.

Example:
<%="Hello World!" %>
Above code will display 'Hello World!'.

Comments