JSP XML JSTL.

JSP XML JSTL

  • The JSP Standard Tag Library (JSTL) adds essential features to JSP that enable JSP programming without the need for embedded Java code.
  • It is a collection of standard JSP tags that perform several common tasks.
  • This frees us from having to develop custom tags for these tasks, or from using a mix of tags from several organizations to do our work.
  • The XML JSTL contains tags for interacting with XML data. This includes flow control based on XPath expression, parsing of XML data, and transforming XML data using XSLT stylesheet.
  • Before using the XML JSTL, the following directive needs to be added to the JSP page:
  • <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
  • The equivalent XML syntax used in tag files for this directive is:
  • <jsp:directive.taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" />

Here is a summary of all XML JSTL tags

  • Tag Description
    choose This tag enables you to provide handling for a set of mutually exclusive conditions, instead of just one.
    forEach Iterates over collections based on XPath expressions.
    if Provides conditional operation based on XPath expressions.
    otherwise This tag may appear only once within a choose action to provide handling of remaining alternatives. This tag must only appear as a subtag of the choose tag.
    out This tag is used to output the result of an expression.
    param Used along with the transform tag to add a parameter to the XML transformer.
    parse Parses XML content.
    set Evaluates an XPath expression and sets the value of an attribute to it.
    transform Applies an XSLT stylesheet to XML data.
    when Unlimited tags of this may exist within a choose action to provide handling for a wide range of conditions. This ia a subtag of the choose tag.

    You will find an example that includes several JSTL XML tags here.

The following is a detail presentation of each XML JSTL tag

  • choose, when and otherwise

    The <x:choose> action enables you to provide handling for a set of mutually exclusive conditions, instead of just one.
    The syntax is as follows:
    <x:choose>
      <x:when select="XPath expression">
        JSP body 
      </x:when>
    ...
      <x:otherwise>
        JSP body
      </x:otherwise>
    </x:choose>

    Unlimited <x:when> actions may exist within a <x:choose> action to provide handling for a wide range of conditions. The <x:otherwise> action may appear only once because it covers all remaining alternatives and must therefore appear after all <x:when> actions.

    <x:when> tag attribute(s):
    Attribute Required Description
    select Yes If the test is true, it processes the tags body.
    Example:
    <x:choose>
      <x:when select="author = 'Solan'"
        Book is written by Solan.
      </x:when>
      <x:when select="author = 'Willcox'"
        Book is written by Willcox.
      </x:when>
      <x:otherwise>
        The book writer is unknown.
      </x:otherwise>
    </x:choose>
  • forEach

    The <x:forEach> tag is used for iterating over collections based on XPath expressions.
    The syntax is as follows:
    <x:forEach select="XPath expression"
      [begin="begin index"]
      [end="end index"]
      [step="step size"]
      [var="variable name"]
      [varStatus="status variable name"]>
    JSP body content
    </x:forEach>
    Attribute(s):
    Attribute Required Description
    select Yes The XPath expression to be evaluated.
    begin No The start index for the iteration.
    end No The end index for the iteration.
    step No The size of the index increment while iterating over the collection. The iteration will process every step item of the collection, starting from the begin index (or first item, if begin is not specified). For example, if step is 5, the index is incremented by 5 every iteration.
    var No The name of the variable in which the current item in the iteration is stored.
    varStatus No The name of the variable in which the status of the iteration is stored. Possible status to retrieve:
    • current => Retrieves the current item in the iteration.
    • index => Retrieves the index of the current round of the iteration.
    • count => Retrieves the "count" of the current round of the iteration..
    • first => Returns true for the first item in the iteration.
    • last => Returns true for the last item in the iteration.
    • begin => Returns the value of the 'begin' attribute for the associated tag, or null if no 'begin' attribute was specified.
    • end => Returns the value of the 'end' attribute for the associated tag, or null if no 'end' attribute was specified.
    • step => Returns the value of the 'step' attribute for the associated tag, or null if no 'step' attribute was specified.
    Example:
    <ul>
      <x:forEach select="${list}" var="item">
        <li><x:out value="${item}"/></li>
      </x:forEach>
    </ul>
  • if

    The <x:if> tag evaluates a test condition. If it is true, it processes its body else the body is ignored.
    The syntax is as follows:
    <x:if select="XPath expression"
      [var="variable name"]
      [scope="page|request|session|application"]>
    JSP body content
    </x:if>
    Attribute(s):
    Attribute Required Description
    select Yes If the test condition is true, it processes its body else the body is ignored
    var No Variable that holds the result (true or false) of the test condition evaluation. This variable can be used for future test conditions (depending on the scope of the variable), thus avoiding reevaluation of the test condition.
    scope No (default=page) Scope of the variable specified in the var attribute. This can be page, request, session, or application.
    Example:
    <x:if select="author = 'Solan'"
      Book is written by Solan.
    </x:if>
    <x:if select="author = 'Willcox'"
      Book is written by Willcox.
    </x:if>
  • out

    The <x:out> tag is used to output the result of an expression. It functions similarly to the <%= ... => JSP syntax.
    The syntax is as follows:
    <x:out select="XPath expression"
    [escapeXml="true|false"] />
    Attribute(s):
    Attribute Required Description
    select Yes The XPath expression to be evaluated. The result of the expression is output to the page.
    escapeXml No (default=true) Determines whether the <, >, " and ' characters in the resultant string should be converted to their corresponding character entity codes.
    Example:
    <x:forEach select="$doc/customers/customer" >
      <x:out select="firstName" />
    </x:forEach>
  • param

    The <x:param> tag is used along with the transform tag to add a parameter to the transformer.
    The syntax is as follows:
    <x:param name="parameter name"  
        [value="parameter value"]>
      JSP body content
    </x:param>
    Attribute(s):
    Attribute Required Description
    name Yes The name of the parameter.
    value No The value for the parameter.
    Example:
    <x:transform xml="${doc}" xslt="${styleSheet}">
      <param name="id" value="${idvalue}" />
    </x:transform>
  • parse

    The <x:parse> tag is used to parse XML data specified either via an attribute or in the tag body.
    The syntax is as follows:
    <x:parse [var="variable name"]
      [varDom="variable name"]
      [scope="page|request|session|application"]
      [scopeDom="page|request|session|application"]
      [doc="XML document"]
      [systemId="system identifier URI"]
      [filter="filter"]>
    JSP body content
    </x:parse>
    Attribute(s):
    Attribute Required Description
    var No A variable that contains the parsed XML data. The type of this data is implementation dependant. Use this or varDom.
    varDom No variable that contains the parsed XML data. The type of this data is org.w3c.dom.Document. Use this or var.
    scope No Scope of the variable specified in the var attribute. This can be page, request, session, or application, and defaults to page if not specified.
    scopeDom No Scope of the variable specified in the varDom attribute. This can be page, request, session, or application, and defaults to page if not specified.
    doc Yes XML document to be parsed.
    systemId No The system identifier URI for parsing the document.
    filter No The filter to be applied to the source document.
    Example:
      <c:import url="customers.xml" var="xml" />
      <x:parse doc="${xml}" var="doc" />
  • set

    The <x:set> tag sets a variable or a property to the value of an expression.
    The syntax is as follows:
    <x:set [var="variable name"]
      [value="expression"]
      [target="JavaBean or Map object name"]
      [property="target property name"]
      [scope="page|request|session|application"] >
      JSP body
    </x:set>
    Attribute(s):
    Attribute Required Description
    var No (default=body content) The variable that is set to the value of the expression.
    value No The expression to be evaluated.
    target Yes The target object (JavaBean or Map object) whose property will be set.
    property No Name of the property to be set in the target attribute.
    scope No (default=page) Scope of the variable specified in the var attribute. This can be page, request, session, or application.
    Example:
    <x:set var="counter" value="${counter + 1}" /> 
  • transform

    The <x:transform> tag conducts a transformation given a source XML document and an XSLT stylesheet .
    The syntax is as follows:
    <x:transform [var="variable name"]
      [scope="page|request|session|application"]
      [result=""]
      [xml=""]
      [doc=""]
      [xmlSystemId=""]
      [docSystemId=""]
      [xslt=""]
      [xsltSystemId=""]>
      JSP body content
    </x:transform>
    Attribute(s):
    Attribute Required Description
    var No Name of the exported scoped variable for the transformed XML document. The type of the scoped variable is org.w3c.dom.Document.
    scope No (default=page) Scope of the variable specified in the var attribute. This can be page, request, session, or application.
    result No Result Object that captures or processes the transformation result.
    xml No Deprecated. Use attribute 'doc' instead.
    doc No Source XML document to be transformed. (If exported by <x:set>, it must correspond to a well-formed XML document, not a partial document.)
    xmlSystemId No Deprecated. Use attribute 'docSystemId' instead.
    docSystemId No The system identifier (URI) for parsing the XML document.
    xslt No javax.xml.transform.Source Transformation stylesheet as a String, Reader, or Source object.
    xsltSystemId No The system identifier (URI) for parsing the XSLT stylesheet.
    Example:
    <x:transform xml="${books}" xslt="${xslt}"/>

Example of using core JSTL element.

In the example we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is XMLJSTL).

In this example, we will add two files, header.jsp and footer.jsp.

  • It is customary to place all include files, which are used several times in the WEB-INF folder. Some would also like the include files should have the extension .jspf, but this is not a requirement.
    Here is the file we want to include at the top of all pages:
    <h1>JSTL XML demo</h1>
    <hr>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Header.jsp and folder should be WEB-INF).

    Here is the file we want to include at the bottom of all pages:
    <hr>
    Status on <%= (new java.util.Date()).toString() %>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Footer.jsp and folder should be WEB-INF).

In this example, we will add two XML files, customers.xml and customerstyle.xsl.

  • We need a XML file with information about customers to use in our example.
    Here is the customers.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <customers>
      <customer>
        <firstName>Karl</firstName>
        <lastName>Smith</lastName>
        <email>karls@nonexistent.org</email>
      </customer>
      <customer>
        <firstName>Jenny</firstName>
        <lastName>Conte</lastName>
        <email>jenny@notreal.com</email>
      </customer>
      <customer>
        <firstName>Rhonda</firstName>
        <lastName>Benedict</lastName>
      </customer>
    </customers>

    For those who participate in the review: create a XML file in Netbeans and replace the code in the XML file with that shown above (the XML file name is customer and folder should be web).

  • We need a XSLT stylesheet file to demonstrate the <x:transform> tag.
    Here is the customerstyle.xsl:
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      <xsl:output method = "html" indent = "yes"/>
      <xsl:template match = "/">
        <html>
          <body>
            <xsl:apply-templates/>
          </body>
        </html>
      </xsl:template>
    
      <xsl:template match = "customers">
        <table  width="100%">
          <tr class="gradientdown">
            <td>First Name</td>
            <td>Last Name</td>
            <td>Email</td>
          </tr>
          <xsl:for-each select = "customer">
            <tr class="data">
              <td>
                <xsl:value-of select = "firstName"/> 
              </td>
              <td>
                <xsl:value-of select = "lastName"/> 
              </td>
              <td>
                <xsl:value-of select = "email"/>
              </td>
            </tr>
          </xsl:for-each>
        </table>
      </xsl:template>
    
    </xsl:stylesheet>

    For those who participate in the review: create a XSLT stylesheet in Netbeans and replace the code for the XSLT stylesheet file with that shown above (the XSLT stylesheet file name is customerstyle and folder should be stl).

At last we need a JSP file(s) to demonstrate how we use the JSTL XML tags.

  • Here is the main JSP file:
    <%@ page language="java" contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSTL SQL demo</title>
        <style>
          .gradientdown {
            background:  #e0e6ff;
            background:  -webkit-linear-gradient(top, #e0e6ff 0%,#eeeeee 100%); /* Chrome10+, Safari5.1+ */
            background:  -o-linear-gradient(#e0e6ff, #eeeeee); /* For Opera 11.1 to 12.0 */
            background:  -moz-linear-gradient(top, #e0e6ff, #eeeeee); /* For Firefox 3.6 to 15 */
            background:  linear-gradient(top, #e0e6ff 0%,#eeeeee 100%); /* W3C Standard syntax (must be last) */
            font-weight: bold;
          }
          table tr.data:nth-of-type(odd) { 
            background: #eeeeee; 
          }
          td {
            vertical-align: top;
          }
          h1 {
            color: blue;
            font-size: 22px;
            margin:  16px 0px 0px 0px;
          }      
          h2 {
            color: blue;
            font-size: 18px;
            margin:  16px 0px 0px 0px;
          }
          h3 {
            color: green;
            font-size: 16px;
            margin: 0px 0px 0px 0px;
          }
          div >span {
            color: blue;
          }
        </style>
      </head>
      <c:import url="customers.xml" var="xml" />
      <x:parse doc="${xml}" var="doc" />
      <body>
        <div style="width:560px; margin-left: 40px;  padding: 10px;">
          <c:import url="/WEB-INF/header.jsp" />
          <h2><x:parse> and <x:out> Demo</h2>
          <textarea rows="14" cols="65"><x:out select="$doc" /></textarea>       
          <h2><x:parse>, <x:forEach>, <x:choose>, <x:out> and <x:when> Demo</h2>
          <table  width="100%">
            <tr class="gradientdown">
              <td>First Name</td>
              <td>Last Name</td>
              <td>Email</td>
            </tr>
            <x:forEach select="$doc/customers/customer" >
              <tr class="data">
                <td><x:out select="firstName" /></td>
                <td><x:out select="lastName" /> </td>
                <td><x:choose >
                    <x:when select="email" >
                      <x:out select="email" />
                    </x:when>
                    <x:otherwise >
                      <c:out value="n/a" />
                    </x:otherwise>
                  </x:choose></td>
              </tr>
            </x:forEach>
          </table>
          <h2><x:parse>, <x:forEach> <x:if> and <x:out>  Demo</h2>  
          <table  width="100%">
            <tr class="gradientdown">
              <td>First Name</td>
              <td>Last Name</td>
              <td>Email</td>
            </tr>
            <x:forEach select="$doc/customers/customer" >
              <x:if select="email[contains(.,'.com')]">
                <tr class="data">
                  <td><x:out select="firstName" /> </td>
                  <td><x:out select="lastName" /> </td>
                  <td><x:out select="email" /></td>
                </tr>
              </x:if>
            </x:forEach>
          </table>
          <h2><x:transform> with xslt file Demo</h2>        
          <c:import url = "WEB-INF/classes/stl/customerstyle.xsl" var = "xslt"/>
          <x:transform doc="${xml}" xslt="${xslt}"/>
          <c:import url="/WEB-INF/footer.jsp" />
        </div>
      </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is index).

Creating Deployment descriptor.

  • To run this JSP you have to deploy it to a web-server or a Application server. To deploy means to install the JSP with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
      <servlet>
        <servlet-name>XMLJSP</servlet-name>
        <jsp-file>/index.jsp</jsp-file>
      </servlet>
      <servlet-mapping>
        <servlet-name>XMLJSP</servlet-name>
        <url-pattern>/XMLJSP</url-pattern>
      </servlet-mapping>
      <session-config>
        <session-timeout>
          30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>XMLJSP</welcome-file>
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a JSP file.
  • With a servlet tag we give the JSP file a servlet name, which is used in the servlet-mapping tag to specify a url for the JSP file.
  • In this way we can have many urls for the same JSP file.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file with url XMLJSP. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /XMLJSTL) for the application will in most cases be specified by a server vendor deployment descriptor.
    The browser will display:
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.