ITiCSE 2003 Tutorial on

Using XML and XSL with JavaServer Pages

presented by Jesse Heines, University of Massachusetts Lowell

Go to main SIG CSE Web site Go to main ITiCSE 2003 Web site

Contents


Samples and Starter Code for Activities

XML and XSL files without explicit stylesheets attached will display as document trees in Internet Explorer Version 6.0+ and Mozilla Version 1.3+

Additional Resources

Links to Participant File Areas



Technical Notes on XML (eXtensible Markup Language)

[ top ]

HTML vs. XML

HTML

XML

Tags pertain to data formatting

Tags pertain to data structure

Tag names are predefined

Tag names are user-defined

Tags have specific meanings for specific formatting constructs

Tags have no predefined meaning (they can denote whatever the user desires)

Tags have a loose hierarchical structure

Tags have a strict hierarchical structure

Tag names are not case-sensitive

Tag names are case-sensitive

Some tags can stand alone, such as <hr> and <br>

All tags must consist of a start and end tag pair

A browser can display an HTML file because it contains formatting information as well as data

A browser cannot display an XML file without further formatting information

HTML content can be manipulated by scripts

XML content can also be manipulated by scripts

HTML cannot be extended by the user,  that is, users cannot invent new tags

XML, as its name implies, is an “eXtensible” technology; users can define new tags

Displaying XML in Internet Explorer


Well-Formedness of XML Documents

HTML’s Loose Document Structure

 

XML’s Strict Document Structure


XML Document Structure

An XML document consists of two main parts

 1  <?xml version="1.0" ?> «– prolog
 2  <Homeowners> «– root element start tag
 3    <Resident>
 4      <LastName>Armstrong</LastName>
 5      <FirstName>George</FirstName>
 6      <HouseNumber>31</HouseNumber>
 7      <StreetName>St. Andrews Way</StreetName>
 8      <ClosingDate>
 9        <Month>5</Month>
10        <Day>13</Day>
11        <Year>1999</Year>
12      </ClosingDate>
13    </Resident>
14    <Resident>
15      ···
16    </Resident>
17    ···
18  </Homeowners>
«– root element end tag

Elements in Plain English

  1. All start tags must have complementary end tags
  2. All tags are case-sensitive
    <TAGNAME> does not match <tagName>
  3. Tags cannot begin with numbers
    <1st_name> is not a legal tag
  4. Tags cannot contain spaces in or around the tag name
    <First Name>  is not a legal tag
    < FirstName >
    is not a legal tag
    </ FirstName>
    is not a legal tag
    < /FirstName>
    is not a legal tag
  5. All tags must be properly nested
  6.  In general, multiple white space in content is ignored

Attributes

Comments  (handout p. 2-18)

Legal Comments Illegal Comments
<!-- root element --> <!---- root element -->
<!--- root element --> <!-- root element --->
<!-- root-element --> <!-- root--element -->
<!-- root- -element --> <!-- root---element -->
  • A comment can extend over multiple lines
    <!--
      File: Example001.xml
      (c) 2000 by Hands On Technology Transfer, Inc.
    -->
  • Built-In Entity References  (handout p. 2-19)

    Entity
    Reference
    Character
    Inserted
    Name or
    Description
     &amp; & ampersand
     &apos; ' apostrophe (single quote)
     &gt; > greater-than sign
     &lt; < less-than sign
     &quot; " quotation mark (double quote)

    1  <Name>Jesse &amp; Bonnie</Name>
    2  <Name>George Herman &quot;Babe&quot; Ruth</Name>
    3  <Name>Bill O&apos;Malley</Name>
    4  <Formula>(x &gt; y) AND (x &lt; z)</Formula>

    Character Data Sections

     1  <Example>
     2    A member record has the following format:
     3    <![CDATA[
     4      <Member>
     5        <Name First="Robert" Last="Boyle"></Name>
     6        <Address>
     7          <Street>13 Paris Road</Street>
     8          <City>Chelmsford</City>
     9          <State ZIP="01863">Massachusetts</State>
    10         </Address>
    11       </Member>
    12     ]]>
    13   </Example>


    Technical Notes on XSL (XML Stylesheet Language)

    [ top ]

    CSS “Decorates” While XSL “Transforms”


    Creating a Stylesheet

    <?xml version='1.0'?> 
    <?xml version='1.0'?> 
    <xsl:stylesheet ... > 
       ... 
    </xsl:stylesheet> 
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

    xsl:stylesheet Element

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


    Defining a Template

    <xsl:template match="node-context">
       ...
    </xsl:template>

    <xsl:template match="/"> 

    xsl:template Element

    <xsl:template match="node-context">
       ...
    </xsl:template>

    Sample XSL Patterns (adapted from MSDN)


    XSL Pattern Operators and Special Characters (adapted from MSDN)

     Operator   Use 
     /  Child operator — selects immediate children of the left-side collection. At the start of a pattern, this operator indicates that children should be selected from the root node
     //  Recursive descent — searches for a specified element at any depth. At the start of a pattern, this operator indicates recursive descent from the root
     .  Indicates the current context
     *  Wildcard — selects all elements regardless of name
     @  Attribute — prefix for an attribute name
     @*  Attribute wildcard — selects all attributes regardless of name
     :  Namespace separator — separates the namespace prefix from the element or attribute name
     [ ]  Applies a filter pattern
     Extended XSL Pattern methods in the XQL Proposal:
     !  Applies the method following the ! to the reference node preceding the !
     ( )  Groups operations to set precedence explicitly
     [ ]  Subscript operator. Used for indexing within a collection


    File Systems vs. XSL Patterns (adapted from MSDN)

    File Systems (URLs)  XSL Patterns
     Hierarchy comprised of directories and files in a file system  Hierarchy comprised of elements and other nodes in an XML document
     Files at each level have unique names-URLs always identify a single file  Element names at each level might not be unique-XSL patterns identify a set of all the matching elements
     URLs are evaluated relative to a particular directory-called the “current directory”  XSL patterns are evaluated relative to a particular node-called the “context” for the query


    xsl:value-of
    Element

    Example:  XSL Patterns - XML File

     1  <?xml version="1.0" ?>
     2  <?xml-stylesheet type="text/xsl" href="HomeOwners04a.xsl"?>
     3  <!--
     4    File: HomeOwners04.xml
     5    (c) 2000 by Hands On Technology Transfer, Inc.
     6  -->
     7  <HomeOwners>
     8    <Resident>
     9      <LastName>Armstrong</LastName>
    10      <FirstName>George</FirstName>
    11      <UnitNumber>49</UnitNumber>
    12      <HouseNumber>31</HouseNumber>
    13      <StreetName>St. Andrews Way</StreetName>
    14      <ClosingDate>
    15        <Month>5</Month>
    16        <Day>13</Day>
    17        <Year>1999</Year>
    18      </ClosingDate>
    19    </Resident>
    20    <Resident>
    21      <LastName>Beaudoin</LastName>
    22      <FirstName>Carole</FirstName>
    23      <UnitNumber>11</UnitNumber>
    24      <HouseNumber>21</HouseNumber>
    25      <StreetName>Augusta Way</StreetName>
    26      <ClosingDate>
    27        <Month>8</Month>
    28        <Day>12</Day>
    29        <Year>1998</Year>
    30      </ClosingDate>
    31    </Resident>
    32    <Resident>
    33      ...
    34    </Resident>
    35    ... additional Resident elements ...
    36  </HomeOwners>

    Example:  XSL Patterns - XSL File

    37  <?xml version="1.0" ?>
    38  <!--
    39    File: HomeOwners04a.xsl
    40    (c) 2000 by Hands On Technology Transfer, Inc.
    41  -->
    42  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    43    <xsl:template match="/">
    44      <html>
    45      <body>
    46        <p>
    47          <i>Name:&#160;</i>
    48          <b><xsl:value-of
    49                select="HomeOwners/Resident/LastName"/>,
    50             <xsl:value-of
    51                select="HomeOwners/Resident/FirstName"/></b><br/>
    52
    53          <i>Unit Number:&#160;</i>
    54          <b><xsl:value-of
    55                select="HomeOwners/Resident/UnitNumber"/></b><br/>
    56
    57          <i>Address:&#160;</i>
    58          <b><xsl:value-of
    59                select="HomeOwners/Resident/HouseNumber"/>
    60             <xsl:value-of
    61                select="HomeOwners/Resident/StreetName"/></b><br/>
    62
    63          <i>Closing Date:&#160;</i>
    64          <b><xsl:value-of
    65                select="HomeOwners/Resident/ClosingDate/Month"/> /
    66             <xsl:value-of
    67                select="HomeOwners/Resident/ClosingDate/Day"/> /
    68             <xsl:value-of
    69                select="HomeOwners/Resident/ClosingDate/Year"/>
    70        </p>
    71      </body>
    72      </html>
    73    </xsl:template>
    74  </xsl:stylesheet>
    

    Example:  XSL Patterns - Discussion


    Applying Templates, Sorting, Conditionals, and Filtering

    Processing Multiple Records

     1  <?xml version="1.0" ?>
     2  <!--
     3    File: HomeOwners04b.xsl
     4    (c) 2000 by Hands On Technology Transfer, Inc.
     5  -->
     6  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
     7
     8    <xsl:template match="/">
     9      <html>
    10      <body>
    11        <xsl:apply-templates select="HomeOwners/Resident"/>
    12      </body>
    13      </html>
    14    </xsl:template>
    15
    16    <xsl:template match="Resident">
    17        <p>
    18          <i>Name:&#160;</i>
    19          <b><xsl:value-of select="LastName"/>,
    20             <xsl:value-of select="FirstName"/></b><br/>
    21
    22          <i>Unit Number:&#160;</i>
    23          <b><xsl:value-of select="UnitNumber"/></b><br/>
    24
    25          <i>Address:&#160;</i>
    26          <b><xsl:value-of select="HouseNumber"/>
    27             <xsl:value-of select="StreetName"/></b><br/>
    28
    29          <i>Closing Date:&#160;</i>
    30          <b><xsl:value-of select="ClosingDate/Month"/> /
    31             <xsl:value-of select="ClosingDate/Day"/> /
    32             <xsl:value-of select="ClosingDate/Year"/></b>
    33        </p>
    34    </xsl:template>
    35  </xsl:stylesheet>
    

    xsl:apply-templates Element

    order-by Attribute

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
     1  <xsl:template match="/">
     2    <xsl:apply-templates select="HomeOwners/Resident"
     3      order-by="+UnitNumber">
     4        <!--
     5          <xsl:sort select="UnitNumber"
     6                    data-type="number"
     7                    order="ascending"/>
     8        -->
     9    </xsl:apply-templates>
    10  </xsl:template>
    

    Simple Conditionals

     1  <i>Closing Date:&#160;</i>
     2  <b><xsl:if test="ClosingDate/Month[.='2']">February </xsl:if>
     3     <xsl:if test="ClosingDate/Month[.='3']">March </xsl:if>
     4     <xsl:if test="ClosingDate/Month[.='4']">April </xsl:if>
     5     <xsl:value-of select="ClosingDate/Day"/>,
     6     <xsl:value-of select="ClosingDate/Year"/></b>
    

    More on XSL Patterns and Filters

    Examples


    XSL Filter Information Methods

     Method  Use
     date  Casts values to date format.
     end  Returns true for the last element in a collection.
     index  Returns the index number of the node within the parent.
     nodeName   Returns the tag name of the node, including the namespace prefix. 
     nodeType   Returns a number to indicate the type of the node.
     number  Casts values to number format.
     text  Returns the content of the node.
     value  Returns a typed version of the value of the node.

    Examples


    XSL Filter Operators

    Microsoft  W3C  Use
     Oper.   Alt.
     Logical Operators
     $and$  and  and  logical AND
     $or$  or  or  logical OR
     $not$  not()   not()  logical NOT
     Comparison Operators
     $eq$  =  =  equal
     $ieq$  none  nyi *  case-insensitive equality
     $ne$  !=  !=  not equal
     $ine$  none  nyi  case-insensitive inequality
     $lt$  <  &lt;  less than
     $igt$  none  nyi  case-insensitive greater than
     $gt$  >  >  greater than
     $ilt$  none  nyi  case-insensitive less than
     $le$  <=  &lt;=  less than or equal to
     $ile$  none  nyi  case-insensitive less than or equal to
     $ge$  >=  >=  greater than or equal to
     $ige$  none  nyi  case-insensitive greater than or equal to
     Set Operators
     $all$   none  use set
    functions 
     returns true if filter-specified conditions are met by all occurrences of the pattern
     $any$  none  use set
    functions
     returns true if filter-specified conditions are met by any occurrences of the pattern

    * nyi = not yet implemented (after Ceponkus and Hoodbhoy, 2000, pp. 397-399)

    xsl:if Element


    Multiple Conditionals

     1 <xsl:choose>
     2   <xsl:when test="pattern"> output </xsl:when>
     3     ...
     4  
    as many additional xsl:when elements as desired
     5     ...
     6   <xsl:otherwise>
    output </xsl:otherwise>  ¬ optional
     7 </xsl:choose>

    Example:  Transforming Month Numbers

     1 <?xml version="1.0" ?>
     2 <!--
     3   File: HomeOwners04e.xsl
     4   (c) 2000 by Hands On Technology Transfer, Inc.
     5 -->
     6 <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
     7
     8   <xsl:template match="/">
     9     <html>
    10      <body>
    11        <h3>Note that closing dates in January are followed by dates
    12        in October, November, and December because these are sorted
    13        alphabetically by month number.  Thus, the months are output
    14        in the following order: 1, 10, 11, 12, 2, 3, ...  In
    15        addition, the days are output in alphabetical order, so
    16        January 5 follows January 29.</h3>
    17
    18        <xsl:apply-templates select="HomeOwners/Resident"
    19          order-by="+ClosingDate/Year; +ClosingDate/Month;
    20                    +ClosingDate/Day"/>
    21            <!-- new syntax in W3C Working Draft and May 2000 MXSML Parser
    22              <xsl:sort select="ClosingDate/Year"
    23                        data-type="number" order="ascending"/>
    24              <xsl:sort select="ClosingDate/Month"
    25                        data-type="number" order="ascending"/>
    26              <xsl:sort select="ClosingDate/Day"
    27                        data-type="number" order="ascending"/>
    28            -->
    29      </body>
    30      </html>
    31    </xsl:template>   code continues on next page
    32    <xsl:template match="Resident">
    33        <p>
    34          <i>Name:&#160;</i>
    35          <b><xsl:value-of select="LastName"/>,
    36             <xsl:value-of select="FirstName"/></b><br/>
    37
    38          <i>Unit Number:&#160;</i>
    39          <b><xsl:value-of select="UnitNumber"/></b><br/>
    40
    41          <i>Address:&#160;</i>
    42          <b><xsl:value-of select="HouseNumber"/>
    43             <xsl:value-of select="StreetName"/></b><br/>
    44
    45          <xsl:apply-templates select="ClosingDate"/>
    46        </p>
    47    </xsl:template>
    48
    49    <xsl:template match="ClosingDate">
    50      <i>Closing Date:&#160;</i><b>
    51      <xsl:choose>
    52         <xsl:when test="Month[.='1']">January </xsl:when>
    53         <xsl:when test="Month[.='2']">February </xsl:when>
    54         <xsl:when test="Month[.='3']">March </xsl:when>
    55         <xsl:when test="Month[.='4']">April </xsl:when>
    56         <xsl:when test="Month[.='5']">May </xsl:when>
    57         <xsl:when test="Month[.='6']">June </xsl:when>
    58         <xsl:when test="Month[.='7']">July </xsl:when>
    59         <xsl:when test="Month[.='8']">August </xsl:when>
    60         <xsl:when test="Month[.='9']">September </xsl:when>
    61         <xsl:when test="Month[.='10']">October </xsl:when>
    62         <xsl:when test="Month[.='11']">November </xsl:when>
    63         <xsl:when test="Month[.='12']">December </xsl:when>
    64         <xsl:otherwise>Bad Month Number </xsl:otherwise>
    65       </xsl:choose>
    66       <xsl:value-of select="Day"/>,
    67       <xsl:value-of select="Year"/></b>
    68    </xsl:template>
    69
    70  </xsl:stylesheet>
    

    xsl:choose and xsl:otherwise Elements

    xsl:when Element


    Looping

     1  <Book>
     2    <Title>Professional Site Server 3.0</Title>
     3    <Authors>
     4      <Author>Rob Howard</Author>
     5      <Author>Craig McQueen</Author>
     6      <Author>Marco Tabini</Author>
     7    </Authors>
     8    <Publisher>Wrox Press, Ltd.</Publisher>
     9    <PubDate>July 1999</PubDate>
    10    <Pages>1058</Pages>
    11    <ISBN>1-861002-69-6</ISBN>
    12    <RecSubjCategories>
    13      <Category>Internet</Category>
    14      <Category>Web Server</Category>
    15      <Category>Site Server</Category>
    16    </RecSubjCategories>
    17  </Book>
    

    xsl:for-each Element

    Example:   XSL Iteration - XML File

     1 <?xml version="1.0" encoding="utf-8" standalone="yes"?>
     2 <?xml-stylesheet type="text/xsl" href="RowWiseJMH.xsl" ?>
     3 <!--
     4   File: CatalogJMH.xml
     5   The Wrox Press Book Catalog Application
     6   adapted from Martin et al., 2000, pp. 356-357, by Jesse Heines, May 2000
     7 -->
     8 <Catalog>
     9   <Book>
    10       <Title>Professional Java XML</Title>
    11       <Authors>
    12          <Author>Alexander Nakhimovsky</Author>
    13          <Author>Tom Myers</Author>
    14       </Authors>
    15       <Publisher>Wrox Press, Ltd.</Publisher>
    16       <PubDate>August 1999</PubDate>
    17       <Pages>600</Pages>
    18       <ISBN>1-861002-85-8</ISBN>
    19       <RecSubjCategories>
    20          <Category>Java</Category>
    21          <Category>Programming</Category>
    22          <Category>XML</Category>
    23       </RecSubjCategories>
    24       <Price>$49.99</Price>
    25    </Book>
    26    <Book>
    27       <Title>Professional ASP 3.0</Title>
    28       <Authors>
    29          <Author>Brian Francis</Author>
    30          <Author>Alex Homer</Author>
    31          <Author>David Sussman</Author>
    32       </Authors>
    33       <Publisher>Wrox Press, Ltd.</Publisher>
    34       <PubDate>October 1999</PubDate>
    35       <Pages>1278</Pages>
    36       <ISBN>1-861002-61-0</ISBN>
    37       <RecSubjCategories>
    38          <Category>Internet</Category>
    39          <Category>Web Publishing</Category>
    40          <Category>ASP</Category>
    41       </RecSubjCategories>
    42       <Price>$59.99</Price>
    43    </Book>
    44       ... additional Book elements ...
    45  </Catalog>

    Example:   XSL Iteration - XSL File

    46  <?xml version="1.0"?>
    47  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    48  <!--
    49    File: RowWiseJMH.xml
    50    The Wrox Press Book Catalog Application
    51    adapted from Martin et al., 2000, pp. 357-358 by Jesse Heines, May 2000
    52    see p. 380 for important note on use of the WD-xsl namespace
    53  -->
    54    <xsl:template match="/">
    55      <HTML>
    56      <BODY>
    57        <xsl:apply-templates select="Catalog"/>
    58      </BODY>
    59      </HTML>
    60    </xsl:template>
    61
    62    <xsl:template match="Catalog">
    63      <xsl:for-each select="Book/Authors[Author='Alex Homer']">
    64      <!-- node context is now an Authors node within a Book element -->
    65        <P>
    66        Book/Title: <B>
    67          <xsl:value-of select="../Title"/></B><BR/>
    68        Book/Authors (collection): <B>
    69          <xsl:value-of select="."/></B><BR/>
    70        First Author (<code>Author[position()=1]</code>): <B>
    71 <xsl:value-of select="Author[position()=1]"/></B><BR/> 72 Last Author (<code>Author[position()=last()]</code>): <B> 73 <xsl:value-of select="Author[position()=last()]"/></B><BR/> 74 First Author with Name that starts with "A" (<code>Author[starts-with(.,'A')]</code>): <B>
    75 <xsl:value-of select="Author[starts-with(.,'A')]"/></B><BR/>
    76 First Author with Name that starts with "A" or "B"<br />
    77 &#160;&#160;&#160;(<code>Author[substring(.,1,1)='A' or substring(.,1,1)='B']</code>): <B>
    78 <xsl:value-of select="Author[substring(.,1,1)='A' or substring(.,1,1)='B']"/></B><BR/>
    79 First Author with Name that starts with "A" or "B"<br />
    80 &#160;&#160;&#160;(alternative solution, <code>Author[contains('AB', substring(.,1,1))]</code>): <B>
    81 <xsl:value-of select="Author[contains('AB', substring(.,1,1))]"/></B><BR/>
    82 First Author with Name that starts with a letter greater than "C"<br />
    83 &#160;&#160;&#160;(<code>Author[contains('DEFGHIJKLMNOPQRSTUVWXYZ', substring(.,1,1))]</code>): <B>
    84 <xsl:value-of select="Author[contains('DEFGHIJKLMNOPQRSTUVWXYZ', substring(.,1,1))]"/></B><BR/>
    85 </P> 86 </xsl:for-each> 87 </xsl:template> 88 89 </xsl:stylesheet>

    Example:  XSL Iteration - Result (handout p. 6-45)

    1 All Authors with Name that starts with a letter greater than "C"<br />
    2   <xsl:for-each select="Author[contains('DEFGHIJKLMNOPQRSTUVWXYZ', substring(.,1,1))]">
    3     <xsl:value-of select="."/>
    4   </xsl:for-each></b><BR/>
    

    XSL Element Summary  (after Ceponkus & Hoodbhoy, 1999, p. 372)

     Element  Use
     Elements discussed in this tutorial
     xsl:stylesheet  Begins definition of a stylesheet - the root node that encompasses the set of templates applied to an XML source tree to generate an output tree
     xsl:template  Defines a series of transformations or formatting procedures that are applied when the node context matches a particular pattern
     xsl:value-of  Inserts the string value of the specified node into the output stream
     xsl:apply-templates   Invokes other templates based on their match attributes
     xsl:if  Provides simple if/then conditional processing
     xsl:choose  Provides multiple conditional processing with the xsl:when and xsl:otherwise elements
     xsl:when  Defines one conditional case within the body of an xsl:choose element
     xsl:otherwise  Defines the default action to be taken if all xsl:when conditions within an xsl:choose element are false
     xsl:for-each  Defines a loop that is applied to all nodes which match its select attribute
     Additional XSL elements
     xsl:comment  Inserts a comment into the output
     xsl:pi  Inserts a processing instruction into the output
     xsl:element  Inserts an XML element with a specified name into the output
     xsl:attribute  Creates an attribute with a specified name and appends that attribute and its value to its parent element
     xsl:copy  Copies the contents of all subelements to the output


    Technical Notes on JSP (JavaServerTM Pages)

    [ top ]

    Why use Java on the server rather than JavaScript on the client?

    A first program

    <html>
    <body>
      <% for ( int k=0 ; k < 5 ; k++ )
         { 
      %>
           k is now <%= k %><br>
      <% } %>
      <p><% out.println( getServletName() ) ; %></p>
    </body>
    </html>

    Output

    k is now 0
    k is now 1
    k is now 2
    k is now 3
    k is now 4
    
    jsp

    Equivalent, alternative code that produces the same output

    <html>
    <body>
      <% 
         for ( int k=0 ; k < 5 ; k++ )
         {
           out.println( "k is now " + k + "<br/>" ) ;
         }
         out.println( "<p>" + getServletName() + "<p>" ) ; 
      %>
    </body>
    </html>

    Characteristics of both versions


    JSP Syntax Basics

    You’re writing real Java code

    Comments

    Defining Functions

    Expressions

    We’ll see lots of examples in the remainder of the tutorial


    JSP Syntax Summary

    Source:  http://javaboutique.internet.com/tutorials/JSP/part11/page02.html
    Captured by JMH on March 03, 2003 at 02:23 PM

    JSP Element Syntax Interpretation Notes
    JSP Expression
    <%= expression %>
    Expression is evaluated and placed in output. XML equivalent is
       <jsp:expression>
          expression
       </jsp:expression>

    Predefined variables are request, response, out, session, application, config, and pageContext (available in scriptlets also).
    JSP Scriptlet
    <% code %>
    Code is inserted in service method. XML equivalent is
       <jsp:scriptlet>
          code
       </jsp:scriptlet>
    JSP Declaration
    <%! code %>
    Code is inserted in body of servlet class, outside of service method. XML equivalent is
       <jsp:declaration>
          code
       </jsp:declaration>
    JSP page Directive <%@ page
          attr="
    value" %>
    Directions to the servlet engine about general setup.

    XML equivalent is
       <jsp:directive.page att="val" />.
    Legal attributes, with default values in bold, are:

    • import="package.class"
    • contentType="MIME-Type"
    • isThreadSafe="true|false"
    • session="true|false"
    • buffer="sizekb|none"
    • autoflush="true|false"
    • extends="package.class"
    • info="message"
    • errorPage="url"
    • isErrorPage="true|false"
    • language="java"
    JSP include Directive <%@ include
          file="
    url" %>
    A file on the local system to be included when the JSP page is translated into a servlet. XML equivalent is
       <jsp:directive.include file="url" />
    The URL must be a relative one. Use the jsp:include action to include a file at request time instead of translation time.
    JSP Comment
    <%-- comment --%>
    Comment; ignored when JSP page is translated into servlet. If you want a comment in the resultant HTML, use regular HTML comment syntax of
        <-- comment -->
    The jsp:include Action <jsp:include
       page="
    relative URL"
       flush="true"/>
    Includes a file at the time the page is requested. If you want to include the file at the time the page is translated, use the page directive with the include attribute instead. Warning: on some servers, the included file must be an HTML file or JSP file, as determined by the server (usually based on the file extension).
    The jsp:useBean Action

    <jsp:useBean 
       attr="
    value"* />

         or

    <jsp:useBean 
       attr="
    value"*>
          ...
    </jsp:useBean>

    Find or build a Java Bean.

    Possible attributes are:

    • id="name"
    • scope="page|request|session|application"
    • class="package.class"
    • type="package.class"
    • beanName="package.class"
    The jsp:setProperty Action <jsp:setProperty
       attr="
    value"* />
    Set bean properties, either explicitly or by designating that value comes from a request parameter.

    Legal attributes are

    • name="beanName"
    • property="propertyName|*"
    • param="parameterName"
    • value="val"
    The jsp:getProperty Action <jsp:getProperty
       name="
    propertyName"
       value="
    value"/>
    Retrieve and output bean properties.  
    The jsp:forward Action <jsp:forward
       page="
    relative URL"/>
    Forwards request to another page.  
    The jsp:plugin Action <jsp:plugin
        attr="
    value"*>
          ...
    </jsp:plugin>
    Generates OBJECT or EMBED tags, as appropriate to the browser type, asking that an applet be run using the Java Plugin.  



    Starter XSL File for Activity 2

    [ top ]
     1  <?xml version="1.0" ?>
     2  
     3  <!--
     4    starter.xsl
     5    Jesse M. Heines, UMass Lowell Computer Science, heines@cs.uml.edu
     6    for ITiCSE XML and XSL Tutorial, Thessaloniki, Greece
     7    Copyright (c) 2003 by Jesse M. Heines.  All rights reserved, but may be freely 
     8      copied or extracted from for educational purposes with credit to the author.
     9    updated by JMH on June 18, 2003 at 02:21 PM
    10  -->
    11  
    12  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    13  
    14  
    15  <!-- main template -->
    16  
    17  <xsl:template match="/">
    18    <html>
    19      <body>
    20        <!--
    21          change the select attribute below to the XPath to your second level elements
    22        -->
    23        <xsl:apply-templates select="root/secondlevel" />
    24      </body>
    25    </html>
    26  </xsl:template>
    27  
    28  
    29  <xsl:template match="secondlevel">
    30    <!--
    31      add processing statements here
    32    -->
    33  </xsl:template>
    34  
    35  
    36  </xsl:stylesheet>


    Starter Tutorial XML and XSL Files for Activity 3

    [ top ]

    tutorialRoster.xml

      9  <?xml version="1.0" ?>
     10  
     11  <!--
     12    tutorialRoster.xml
     13    Jesse M. Heines, UMass Lowell Computer Science, heines@cs.uml.edu
     14    for ITiCSE XML and XSL Tutorial, Thessaloniki, Greece
     15    Copyright (c) 2003 by Jesse M. Heines.  All rights reserved, but may be freely 
     16      copied or extracted from for educational purposes with credit to the author.
     17    updated by JMH on June 18, 2003 at 02:21 PM
     18  -->
     19  
     20  <?xml-stylesheet type="text/xsl" href="tutorialRoster.xsl" ?>
     21  
     22  <tutorialRoster>
     23    <particulars>
     24      <title>Using XML and XSL with JavaServer Pages</title>
     25      <date>2003-06-29</date>
     26      <location>Thessaloniki, Greece</location>
     27      <organization>ACM SIG CSE</organization>
     28      <conference>ITiCSE</conference>
     29    </particulars>
     30    <presenter>
     31      <name last="Heines" first="Jesse" />
     32      <institution name="University of Massachusetts Lowell" />
     33      <emailaddress>heines@cs.uml.edu</emailaddress>
     34    </presenter>
     35    <participant>
     36      <name last="Adams" first="Elizabeth" />
     37      <institution name="James Madison University" />
     38      <emailaddress>adamses@jmu.edu</emailaddress>
     39    </participant>
     40    <participant>
     41      <name last="Eyfrosynh" first="Grousouzakou" />
     42      <institution name="1o Esperino Tee Peristeriou" />
     43      <emailaddress>efigr@dolnet.gr</emailaddress>
     44    </participant>
     45    <participant>
     46      <name last="Haddow" first="John" />
     47      <institution name="Bell College" />
     48      <emailaddress>j.haddow@bell.ac.uk</emailaddress>
     49    </participant>
     50    <participant>
     51      <name last="Meyerowitz" first="Jane" />
     52      <institution name="University of Natal" />
     53      <emailaddress>meyerowi@nu.ac.za</emailaddress>
     54    </participant>
     55    <participant>
     56      <name last="Or-Bach" first="Rachel" />
     57      <institution name="Emek Yezreel College" />
     58      <emailaddress>orbach@yvc.ac.il</emailaddress>
     59    </participant>
     60    <participant>
     61      <name last="Pothering" first="George" />
     62      <institution name="College of Charleston" />
     63      <emailaddress>pother@cs.cofc.edu</emailaddress>
     64    </participant>
     65    <participant>
     66      <name last="Psarri" first="Dimitra" />
     67      <institution name="1st Lykeio Agias Varvaras" />
     68      <emailaddress>mail@1lyk-ag-varvar.att.sch.gr</emailaddress>
     69    </participant>
     70    <participant>
     71      <name last="Stalvey" first="RoxAnn" />
     72      <institution name="College of Charleston" />
     73      <emailaddress>stalveyr@cs.cofc.edu</emailaddress>
     74    </participant>
     75    <participant>
     76      <name last="Walker" first="Henry" />
     77      <institution name="Grinnell College" />
     78      <emailaddress>walker@grinnell.edu</emailaddress>
     79    </participant>
     80  </tutorialRoster>

    Display this file -- right-click this link and select “Save Target As...” from the popup menu to download this code

    To download file the linked file tutorialRoster.xsl (see below), right-click HERE and select “Save Target As...” from the popup menu


    tutorialRoster.xsl

     88  <?xml version="1.0" ?>
     89  
     90  <!--
     91    tutorialRoster.xsl
     92    Jesse M. Heines, UMass Lowell Computer Science, heines@cs.uml.edu
     93    for ITiCSE XML and XSL Tutorial, Thessaloniki, Greece
     94    Copyright (c) 2003 by Jesse M. Heines.  All rights reserved, but may be freely 
     95      copied or extracted from for educational purposes with credit to the author.
     96    updated by JMH on June 18, 2003 at 02:21 PM
     97  -->
     98  
     99  <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    100  
    101  
    102  <!-- main template -->
    103  
    104  <xsl:template match="/">
    105    <html>
    106      <body>
    107        <h1><xsl:value-of select="tutorialRoster/particulars/title" /></h1>
    108        <table>
    109          <xsl:apply-templates select="tutorialRoster/participant" />
    110        </table>
    111      </body>
    112    </html>
    113  </xsl:template>
    114  
    115  
    116  <!-- template executed once for each participant -->
    117  
    118  <xsl:template match="participant">
    119    <tr>
    120      <td><xsl:value-of select="name/@last" />, <xsl:value-of select="name/@first" /></td>
    121      <td>&#160;&#160;&#160;&#160;&#160;</td>
    122      <td><xsl:value-of select="institution/@name" /></td>
    123      <td>&#160;&#160;&#160;&#160;&#160;</td>
    124      <td><a href="mailto:{emailaddress}"><xsl:value-of select="emailaddress" /></a></td>
    125    </tr>
    126  </xsl:template>
    127  
    128  
    129  </xsl:stylesheet>

    To download this file, right-click HERE and select “Save Target As...” from the popup menu



    Minimum JavaServer Page to Apply XSL to XML for Activity 4

    [ top ]
     1  <html>
     2  <!--
     3    minimum.jsp - code to apply an XSL file to an XML file on the server side
     4      adapted from xalan-j_2_3_1\samples\SimpleTransform\SimpleTransform.java
     5      download Xalan-Java from http://xml.apache.org/xalan-j free of charge
     6    Jesse M. Heines, UMass Lowell Computer Science, heines@cs.uml.edu
     7    Copyright (c) 2003 by Jesse M. Heines.  All rights reserved, but may be freely 
     8      copied or extracted from for educational purposes with credit to the author.
     9    updated by JMH on June 18, 2003 at 05:01 PM
    10  -->
    11  
    12  <%@ page import="java.io.*" %>                    <!-- for StringWriter                    -->
    13  <%@ page import="javax.xml.transform.*" %>        <!-- for Transformer, TransformerFactory -->
    14                                                    <!--    and TransformerException         -->
    15  <%@ page import="javax.xml.transform.stream.*" %> <!-- for StreamSource and StreamResult   -->
    16    
    17  <head>
    18  <%!
    19    /** Apply an XSL file to an XML file and return the results as a String.
    20     *  @param  strXMLfile  String containing full URL to the XML file 
    21     *  @param  strXSLfile  String containing full URL to the XSL file 
    22     *  @return String containing the output of the transformation
    23     */
    24    String ApplyXSL( String strXMLfile, String strXSLfile )
    25    {
    26      // StringWriter is a child of java.io.Writer and can therefore be 
    27      // used as an argument to a StreamResult constructor, which is 
    28      // required by Transformer.transform().
    29      StringWriter swResult = new StringWriter() ;
    30    
    31      try {
    32        // Use the static TransformerFactory.newInstance() method to instantiate
    33        // a TransformerFactory. The javax.xml.transform.TransformerFactory
    34        // system property setting determines the actual class to instantiate --
    35        // org.apache.xalan.transformer.TransformerImpl.
    36  
    37        TransformerFactory tFactory = TransformerFactory.newInstance();
    38    
    39        // Use the TransformerFactory to instantiate a Transformer that will work
    40        // with the stylesheet you specify. This method call also processes the 
    41        // stylesheet into a compiled Templates object.
    42  
    43        Transformer transformer = 
    44            tFactory.newTransformer( new StreamSource( strXSLfile ) ) ;
    45    
    46        // Use the Transformer to apply the associated Templates object to an XML 
    47        // document (foo.xml) and write the output to a file (foo.out).
    48  
    49        transformer.transform( new StreamSource( strXMLfile ),
    50                               new StreamResult( swResult ) ) ;
    51  
    52        // Return the result.
    53        return swResult.toString() ;
    54  
    55      } catch ( TransformerConfigurationException tfce ) {
    56        return tfce.toString() ;
    57  
    58      } catch ( TransformerException tfe ) {
    59        return tfe.toString() ;
    60      }
    61    }
    62  %>
    63  </head>
    64  
    65  <body>
    66  <%
    67    // This code assumes that the XML and XSL files reside in the same directory
    68    // as this JSP.  Those file names are hard-code here, but they could be passed
    69    // as parameters from an HTML form or via some other such technique.
    70    String strXMLfilename = "tutorialRoster.xml" ;  // replace with your XML file name
    71    String strXSLfilename = "tutorialRoster.xsl" ;  // replace with your XSL file name
    72    
    73    // We need to construct a full URL to the XML and XSL files, including the
    74    // "http://" protocol specification, server name, and server port number (if 
    75    // it's not the default of 80).  The following code accomplishes this.
    76    String strFullPath = "http://" + request.getServerName() ;
    77    if ( request.getServerPort() != 80 ) 
    78      strFullPath += ":" + request.getServerPort() ;
    79  
    80    // We then add the full path to this JSP and finally strip off this JSP's file 
    81    // name and extension that follow the last forward slash (/).
    82    strFullPath += request.getRequestURI() ;
    83    strFullPath = strFullPath.substring( 0, strFullPath.lastIndexOf( "/" ) + 1 ) ;
    84  
    85    // We append the XML and XSL file names to the full path to pass them to our
    86    // ApplyXSL method, which applies the XSL file to the XML file and returns the 
    87    // result as a string.  Printing that String shows the result in the browser.
    88    out.println( ApplyXSL( strFullPath + strXMLfilename,
    89                           strFullPath + strXSLfilename ) ) ;
    90  %>
    91  </body>
    92  </html>
    

    Run this code -- right-click this link and select “Save Target As...” from the popup menu to download this code



    JavaServer Page to Create XSL “On-the-Fly” for Activity 5

    [ top ]
      1  <html>
      2  <!--
      3    onthefly.jsp - JSP code to apply an XSL document stored in a String to an XML file
      4      adapted from xalan-j_2_3_1\samples\SimpleTransform\SimpleTransform.java
      5      download Xalan-Java from http://xml.apache.org/xalan-j free of charge
      6    Jesse M. Heines, UMass Lowell Computer Science, heines@cs.uml.edu
      7    Copyright (c) 2003 by Jesse M. Heines.  All rights reserved, but may be freely
      8      copied or extracted from for educational purposes with credit to the author.
      9    updated by JMH on June 18, 2003 at 09:23 PM
     10  -->
     11  
     12  <%@ page import="java.io.*" %>                    <!-- for StringWriter                    -->
     13  <%@ page import="javax.xml.transform.*" %>        <!-- for Transformer, TransformerFactory -->
     14                                                    <!--    and TransformerException         -->
     15  <%@ page import="javax.xml.transform.stream.*" %> <!-- for StreamSource and StreamResult   -->
     16  
     17  <head>
     18  <%!
     19    /** Apply an XSL String to an XML file and return the results as a String.
     20     *  @param  strXMLfile    String containing full URL to the XML file
     21     *  @param  strXSLstring  String XSL to be applied
     22     *  @return String containing the output of the transformation
     23     */
     24    String ApplyXSLstring( String strXMLfile, String strXSLstring )
     25    {
     26      return ApplyXSLstring( strXMLfile, strXSLstring, null ) ;
     27    }
     28  
     29  
     30    /** Apply an XSL String to an XML file and return the results as a String.
     31     *  @param  strXMLfile    String containing full URL to the XML file
     32     *  @param  strXSLstring  String XSL to be applied
     33     *  @param  arrParams     2D array of parameter name and value Strings
     34     *  @return String containing the output of the transformation
     35     */
     36    String ApplyXSLstring( String strXMLfile, String strXSLstring, String[][] arrParams )
     37    {
     38      StringWriter swResult = new StringWriter() ;
     39  
     40      try {
     41        // Use the static TransformerFactory.newInstance() method to instantiate
     42        // a TransformerFactory.
     43        TransformerFactory tFactory = TransformerFactory.newInstance();
     44  
     45        // Use the TransformerFactory to instantiate a Transformer that will work
     46        // with the stylesheet you specify.
     47        Transformer transformer =
     48            tFactory.newTransformer( new StreamSource( new StringReader( strXSLstring ) ) ) ;
     49  
     50        // Set parameters to pass to the top level of the XSL file
     51        if ( arrParams != null )
     52          for ( int k = 0 ; k < arrParams.length ; k++ )
     53            transformer.setParameter( arrParams[k][0], arrParams[k][1] ) ;
     54  
     55        // Use the Transformer to apply the associated Templates object to an XML
     56        // document (foo.xml) and write the output to a file (foo.out).
     57        transformer.transform( new StreamSource( strXMLfile ), 
     58                               new StreamResult( swResult ) ) ;
     59  
     60        // Return the result
     61        return swResult.toString() ;
     62  
     63      } catch ( TransformerConfigurationException tfce ) {
     64        return tfce.toString() ;
     65  
     66      } catch ( TransformerException tfe ) {
     67        return tfe.toString() ;
     68      }
     69    }
     70  %>
     71  </head>
     72  
     73  <body>
     74  <%
     75    // show date and time from server side to verify that page has loaded
     76    out.println( "<p><i>Server Side Time Stamp:</i>  " +
     77                 ( new java.util.Date() ) + "</p>" ) ;
     78  
     79    // This code assumes that the XML and XSL files reside in the same directory
     80    // as this JSP.  Those file names are hard-code here, but they could be passed
     81    // as parameters from an HTML form or via some other such technique.
     82    String strXMLfilename = "tutorialRoster.xml" ;  // replace with your XML file name
     83  
     84    // We need to construct a full URL to the XML and XSL files, including the
     85    // "http://" protocol specification, server name, and server port number (if
     86    // it's not the default of 80).  The following code accomplishes this.
     87    String strFullPath = "http://" + request.getServerName() ;
     88    if ( request.getServerPort() != 80 )
     89      strFullPath += ":" + request.getServerPort() ;
     90  
     91    // We then add the full path to this JSP and finally strip off this JSP's file
     92    // name and extension that follow the last forward slash (/).
     93    strFullPath += request.getRequestURI() ;
     94    strFullPath = strFullPath.substring( 0, strFullPath.lastIndexOf( "/" ) + 1 ) ;
     95  
     96    // construct the XSL file as a string
     97    // note that single quotes can be used to quote attributes inside the double quotes
     98    //    that delimit the Java String constants
     99    String strXSLstring =
    100        "<?xml version='1.0' ?>" +
    101        "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
    102        "  <xsl:template match='/'>" +
    103        // replace the next statement with one appropriate to your own XML file
    104        "    <xsl:value-of select='tutorialRoster/particulars/location' />" +
    105        "  </xsl:template>" +
    106        "</xsl:stylesheet>" ;
    107  
    108    // We append the XML file name to the full path to pass it to our ApplyXSLstring
    109    // method, which applies the XSL String to the XML file and returns the result as 
    110    // a String.  Printing that String shows the result in the browser.
    111    out.println( "<p><i>XSL Result:</i>  " +
    112                 ApplyXSLstring( strFullPath + strXMLfilename, strXSLstring ) ) ;
    113  %>
    114  </body>
    115  </html>
    

    Run this code -- right-click this link and select “Save Target As...” from the popup menu to download this code



    JavaServer Page and Auxiliary Functions to Dynamically Retrieve Specified Data from an XML File Using XPath for Activity 6

    [ top ]

    xsl_query.jsp

    Replace the lines in bold red type with ones appropriate to your own XML file

      9  <html>
     10  <!--
     11    XSL Query Starter Code for Final 91.513 Assignment
     12    Jesse M. Heines, UMass Lowell Computer Science, heines@cs.uml.edu
     13    updated by JMH on June 20, 2003 at 09:56 AM
     14  -->
     15  <head>
     16    <title>XSL Query Starter Code</title>
     17    
     18  <%!
     19    /** name of XML file to process on the server */
     20    String strXMLFileName ;
     21    
     22    /** full path to the XML file to process on the server */
     23    String strRealXMLFilePath ;
     24  %>
     25    
     26    <%-- include XSL functions defined in an external file --%>
     27    <%@ include file="xsl_functions.jsp" %>
     28  </head>
     29  
     30  <body>
     31  <%
     32    // set main variables here so that they are reinitialized in each independent run
     33    strXMLFileName = "tutorialRoster.xml" ;  // replace with your XML file name
     34    strRealXMLFilePath = getRealPath( application, request ) + strXMLFileName ;
     35    
     36    // extract a single piece of data from the XML file
     37    String strTutorialTitle =     // replace with an XPath appropriate to your XML file
     38        getElementContentFromXML( strRealXMLFilePath, 
     39                                  "tutorialRoster/particulars/title" ) ;
     40    
     41    // extract another single piece of data from the XML file
     42    String strTutorialLocation =  // replace with an XPath appropriate to your XML file
     43        getElementContentFromXML( strRealXMLFilePath, 
     44                                  "tutorialRoster/particulars/location" ) ;
     45    
     46    // extract multiple pieces of data from the XML file
     47    String strXPath = "//participant/name/@last[starts-with( . , 'P' )]" ;  // replace
     48    String[] arrStudents = 
     49        getMultipleElementContentFromXML( strRealXMLFilePath, strXPath ) ;
     50  %>
     51    
     52    <h2>  <!-- copy document title to page header -->
     53      <script type="text/javascript"><!--
     54        document.writeln( document.title ) ;
     55      --></script>
     56    </h2>
     57  
     58    <!-- show time stamps to verify reloading -->
     59    <%
     60      // show date and time from server side to verify that page has loaded
     61      out.println( "<p><i>Server Side Time Stamp:</i>  " + ( new java.util.Date() ) + "<br/>" ) ;
     62    %>
     63    <script type="text/javascript"><!--
     64      // show date and time from client side to verify that page has loaded
     65      document.writeln( "<i>Client Side Time Stamp:</i>  " + new Date() + "</p>" ) ;
     66    --></script>
     67    
     68    <!-- show the full path to the XML file -->
     69    <p>The full path to the XML file on the server is:<br/>
     70       <b><%= strRealXMLFilePath %></b></p>
     71    
     72    <!-- show single data items extracted from the XML file -->
     73    <p>The XML file indicates that the title and location of this tutorial are:<br/>
     74       <b><%= strTutorialTitle %><br/>
     75       <%= strTutorialLocation %></b></p>
     76  
     77    <!-- show multiple data items extracted from the XML file -->
     78    <p>Querying the course roster with the XPath:</p>
     79    <blockquote>
     80      <code><b><%= strXPath %></b></code>
     81    </blockquote>
     82    <p>returns:<br/>
     83      <ol>
     84        <%
     85          for ( int k = 0 ; k < arrStudents.length ; k++ )
     86            out.println( "<li>" + arrStudents[ k ] + "</li>" ) ;
     87        %>
     88      </ol>
     89    </p>
     90  
     91    <p><a href="xsl_query_jsp-listing.htm">View Source</a></p>
     92    
     93    <p>XML File Listing:</p>
     94    
     95    <%= getXMLListing( strRealXMLFilePath ) %>
     96  
     97  </body>
     98  </html>

    Run this code -- right-click this link and select “Save Target As...” from the popup menu to download this code

    To download file the included file xsl_functions.jsp (see below), right-click HERE and select “Save Target As...” from the popup menu


    xsl_functions.jsp

    106  <%--
    107    XSL Helper Functions for Applying XSL Strings to XML Files
    108    Jesse M. Heines, UMass Lowell Computer Science, heines@cs.uml.edu
    109    updated by JMH on June 18, 2003 at 09:12 PM
    110  --%>
    111  
    112  <%@ page import="java.io.*" %>                      <%-- for StringWriter and File    --%>
    113  <%@ page import="java.util.*" %>                    <%-- for StringTokenizer          --%>
    114  <%@ page import="javax.xml.transform.*" %>          <%-- for Transformer classes      --%>
    115  <%@ page import="javax.xml.transform.stream.*" %>   <%-- for some XSL transformations --%>
    116  <%@ page import="org.apache.xml.serialize.*" %>     <%-- for OutputFormat             --%>
    117  <%@ page import="org.w3c.dom.*" %>                  <%-- for Document                 --%>
    118  <%@ page import="org.apache.xerces.parsers.*" %>    <%-- for DOMParser and SAXParser  --%>
    119  <%@ page import="java.awt.*, javax.swing.*" %>      <%-- for debugging windows        --%>
    120  
    121  <%!
    122    /** This function can be used for debugging to display messages in a simple dialog box.
    123     *  Note that it only works on a Windows-based server, not a Unix-based one.
    124     *  @param  str  string to display
    125     */
    126    public void show( String str )
    127    {
    128      JOptionPane.showMessageDialog( null, str,
    129          "Debugging Information", JOptionPane.INFORMATION_MESSAGE ) ;
    130    }
    131  
    132    
    133    /** This function returns the real path to the directory containing currently running JSP.
    134     *  @param  application  the standard application object
    135     *  @param  request      the standard request object
    136     *  @return String containing the real path in the current OS's format with a "/" appended
    137     */
    138    public String getRealPath(
    139        ServletContext application,   // the standard application object
    140        HttpServletRequest request    // the standard request object
    141      )
    142    {
    143      // use request and application objects to get the real path on the server
    144      String strRealPath = request.getServletPath() ;
    145      strRealPath = strRealPath.substring( 0, strRealPath.lastIndexOf( "/" ) ) ;
    146      strRealPath = application.getRealPath( strRealPath ) ;
    147  
    148      // append the approprate slash for the server's operating system
    149      strRealPath += System.getProperty( "file.separator" ) ;
    150      
    151      // return the result
    152      return strRealPath ;
    153    }
    154  
    155  
    156    /** Apply an XPath String to an XML file and return the results as a String.
    157     *  @param  strXMLfile    String containing full URL to the XML file 
    158     *  @param  strXSLstring  String XSL to be applied
    159     *  @return String containing the output of the transformation
    160     */
    161    String ApplyXSLstring( String strXMLfile, String strXSLstring )
    162    {
    163      return ApplyXSLstring( strXMLfile, strXSLstring, null ) ;
    164    }
    165  
    166  
    167    /** Apply an XSL String to an XML file and return the results as a String.
    168     *  @param  strXMLfile    String containing full URL to the XML file 
    169     *  @param  strXSLstring  String XSL to be applied
    170     *  @param  arrParams     2D array of parameter name and value Strings
    171     *  @return String containing the output of the transformation
    172     */
    173    String ApplyXSLstring( String strXMLfile, String strXSLstring, String[][] arrParams )
    174    {
    175      StringWriter swResult = new StringWriter() ;
    176      
    177      try {
    178        // Use the static TransformerFactory.newInstance() method to get a reference to 
    179        // a TransformerFactory
    180        TransformerFactory tFactory = TransformerFactory.newInstance();
    181    
    182        // Use the TransformerFactory to instantiate a Transformer that will work
    183        // with the stylesheet you specify
    184        Transformer transformer = 
    185            tFactory.newTransformer( new StreamSource( new StringReader( strXSLstring ) ) ) ;
    186    
    187        // Set parameters to pass to the top level of the XSL file
    188        if ( arrParams != null )
    189          for ( int k = 0 ; k < arrParams.length ; k++ )
    190            transformer.setParameter( arrParams[k][0], arrParams[k][1] ) ;
    191  
    192        // Use the Transformer to apply the associated XSL file to an XML document and write 
    193        // the output to an output stream
    194        transformer.transform( new StreamSource( strXMLfile ),
    195                               new StreamResult( swResult ) ) ;
    196  
    197        // Return the result
    198        return swResult.toString() ;
    199  
    200      } catch ( TransformerConfigurationException tfce ) {
    201        return tfce.toString() ;
    202  
    203      } catch ( TransformerException tfe ) {
    204        return tfe.toString() ;
    205      }
    206    }
    207  
    208  
    209    /** Extract element content from a specified XML file given an XPath.
    210     *  @param  strXMLFile  name of XML file from which to extract data
    211     *  @param  strXPath    XPath to data to extract
    212     *  @return String element content
    213     */
    214    String getElementContentFromXML( String strXMLFile, String strXPath )
    215    {
    216      // convert single quotes to double quotes to allow both to be in XPath filters
    217      strXPath = strXPath.replaceAll( "'", "\"" ) ;
    218      
    219      // query result to be returned to calling function
    220      String strResult = ApplyXSLstring( strXMLFile, 
    221          "<?xml version='1.0' ?>" +
    222          "<xsl:stylesheet version='1.0' " +
    223          "         xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
    224          "  <xsl:template match='/'>" +
    225          "    <xsl:value-of select='" + strXPath + "' />" +
    226          "  </xsl:template>" +
    227          "</xsl:stylesheet>" ) ;
    228  
    229      // remove initial directive (ending with ">") and remove leading and trailing white space
    230      strResult = strResult.substring( strResult.indexOf( ">" ) + 1 ).trim() ;
    231      
    232      return strResult ;  // return final result
    233    }
    234  
    235  
    236    /** Extract content from multiple elements from an XML file given an XPath.
    237     *  @param  strXMLFile    name of XML file from which to extract data
    238     *  @param  strXPath      XPath to data to extract
    239     *  @return String array containing multiple element content
    240     */
    241    String[] getMultipleElementContentFromXML( String strXMLFile, String strXPath )
    242    {
    243      // convert single quotes to double quotes to allow both to be in XPath filters
    244      strXPath = strXPath.replaceAll( "'", "\"" ) ;
    245      
    246      // string to delimit multiple results for subsequent tokenizing
    247      String strDelimiter = "|" ;
    248  
    249      // query result to be returned to calling function
    250      String strResult = ApplyXSLstring( strXMLFile, 
    251          "<?xml version='1.0' ?>\n" +
    252          "<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>\n" +
    253          "  <xsl:template match='/'>\n" +
    254          "    <xsl:apply-templates select='" + strXPath + "' />\n" +
    255          "  </xsl:template>\n" +
    256          "  <xsl:template match='" + strXPath + "'>\n" +
    257          "    " + strDelimiter + "<xsl:value-of select='.' />" + 
    258          "  </xsl:template>\n" +
    259          "</xsl:stylesheet>\n" ) ;
    260          
    261      // remove initial directive (ending with ">") and remove leading and trailing white space
    262      strResult = strResult.substring( strResult.indexOf( ">" ) + 1 ).trim() ;
    263      
    264      // break result into tokens with which to populate array to be returned
    265      StringTokenizer st = new StringTokenizer( strResult, strDelimiter ) ;
    266  
    267      // populate array to be returned with the results found
    268      String[] strArrayResult = new String[ st.countTokens() ] ;
    269      for ( int k = 0 ; st.hasMoreTokens() ; k++ )
    270        strArrayResult[ k ] = st.nextToken().trim() ;
    271        
    272      return strArrayResult ;  // return final result
    273    }
    274  
    275  
    276    /** Return a String containing an XML file in serialized form.
    277     *  @param  strXMLFile    name of XML file from which to extract data
    278     *  @return String the XML file in serialized form
    279     */
    280    String getXMLListing( String strXMLFile )
    281    {
    282      // open XML file
    283      Document doc = null ;                     // the XML document in the specified file
    284      File fileXML = new File( strXMLFile ) ;   // the File object for the XML file to open
    285      if ( ! fileXML.exists() )
    286        return "File " + strXMLFile + " does not exist." ;
    287      else
    288      {
    289        // instantiate the XML parser
    290        DOMParser parser = new DOMParser() ;
    291    
    292        try {      // inherited from class XMLParser
    293          parser.parse( strXMLFile ) ;
    294        } catch ( IOException e ) {
    295            return "<p>XML File Load Error:  " + e.toString() + "</p>" ;
    296        } catch ( org.xml.sax.SAXException e ) {
    297            return "<p>XML File Parsing Error:  " + e.toString() + "</p>" ;
    298        } catch ( Exception e ) {
    299            return "<p>Undetermined Error:  " + e.toString() + "</p>" ;
    300        }
    301        
    302        doc = parser.getDocument() ;
    303      }
    304  
    305      // make a serializable version of the XML Document object
    306      // reference:  www-106.ibm.com/developerworks/xml/library/x-injava2/?dwzone=xml
    307      OutputFormat of = new OutputFormat( doc ) ;
    308      of.setIndenting( true ) ;
    309      of.setIndent( 2 ) ;
    310      of.setPreserveSpace( true ) ;
    311      StringWriter sw = new StringWriter() ;
    312        // use a StringWriter instead of serializing directly to the 
    313        // ObjectOutputStream because serializing directly yields a 
    314        // java.io.OptionalDataException when reading the data with 
    315        // ObjectInputStream.readObject()
    316      XMLSerializer xmlser = new XMLSerializer( sw, of ) ;
    317      try {
    318        xmlser.serialize( doc ) ;
    319      } catch ( IOException ioe ) {
    320         return "<p>IOException in getXMLListing:<br/>   " + ioe.toString() ;
    321      }
    322      
    323      // format the string for HTML output
    324      String strDoc = sw.toString().replaceAll( "&", "&amp;" ) ;
    325      return "<pre>\n" + strDoc.replaceAll( "<", "&lt;" ) + "\n</pre>" ;
    326    }
    327  %>

    To download this file (it cannot be run on its own), right-click HERE and select “Save Target As...” from the popup menu



       
    [ top ]