About us
Contact us
Products
Services
Articles
 Twitter    Bookmark and Share

XML Output JSP Actions - Examples

JSP Tag Library for Generating XML Dynamically

The following JSP examples output XML elements, character data, comments, processing instructions or entire XML documents using

  • Devsphere XML JSP Tag Library (XJTL)
  • Apache/Sun JSP Standard Tag Library (JSTL)
  • Java Server Pages without any tag library (JSP)

You'll find the XJTL actions much easier to use that the JSP or JSTL alternatives because dynamic XML output is one of the two core functions of XJTL. (The other one is XML processing.) This doesn't mean that you can't use the XJTL and JSTL tag libraries together in JSP applications since they complement each other.

We use "c", "x" and "o" as prefixes for the actions of JSTL Core, JSTL XML and XJTL Output, respectively:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
<%@ taglib prefix="o" uri="http://devsphere.com/xml/taglib/output" %>

Element1.jsp

http://localhost:8080/xjtldemo/output/Element1.jsp?a1=v1&a2=v2&a3=v3

This example outputs an element with three attributes whose values are obtained from the URL's request parameters.

<e a1="v1" a2="v2" a3="v3">
...
</e>

XJTL can generate the above XML construct very easily with the <o:element> action. XJTL extracts the names of the three attributes (a1, a2 and a3) from the "param.a1 param.a2 param.a3" string. Then it evaluates ${param.a1}, ${param.a2} and ${param.a3} to obtain the values of the attributes.

JSTL doesn't have a specialized action for generating an XML element. Therefore, you have to use one <c:out> action for each attribute, which leads to an ugly syntax like this <e a1="<c:out value='${param.a1}'/>" ... >

The JSP alternative without any tag library requires more coding because JSP doesn't have a mechanism for escaping &, <, > and ". We use our own DemoUtils.escapeXml() routine.

XJTL
<o:element name="e" attr="param.a1 param.a2 param.a3">
...
</o:element>
JSTL
<e a1="<c:out value='${param.a1}'/>"
   a2="<c:out value='${param.a2}'/>"
   a3="<c:out value='${param.a3}'/>">
...
</e>
JSP
<%
String v1 = DemoUtils.escapeXml(request.getParameter("a1"));
String v2 = DemoUtils.escapeXml(request.getParameter("a2"));
String v3 = DemoUtils.escapeXml(request.getParameter("a3"));
%>
<e a1="<%=v1%>" a2="<%=v2%>" a3="<%=v3%>">
...
</e>

The <o:element> action is much easier to use than the two alternatives because XJTL tokenizes the attr string and takes everything it needs from the obtained tokens. To get an attribute name from a token, XJTL takes all characters after the last dot. In order to obtain the value of the attribute, XJTL evaluates the token after wrapping it with ${ and }.

JSP variables (also known as page/request/session/application attributes), request parameters, initialization parameters and bean properties can be outputted as attributes of an XML element using the expressions that were introduced by JSTL and adopted by JSP 2.0.

JSTL & XJTL JSP 1.x
pageScope.name pageContext.getAttribute("name")
requestScope.name request.getAttribute("name")
sessionScope.name session.getAttribute("name")
applicationScope.name application.getAttribute("name")
param.name request.getParameter("name")
initParam.name application.getInitParameter("name")
bean.name bean.getName()
bean.subBean.name bean.getSubBean().getName()

There are cases when the name of the XML attribute is not the same as the name of a request parameter or a bean property. Sometimes, the expression that must be evaluated in order to obtain the attribute's value doesn't end with the desired attribute name. For such cases, XJTL provides the <o:attributes> and <o:attribute> actions, which let you specify the name and value of each XML attribute separately. The following code fragment generates the same XML element as the previous examples.

<o:attributes var="a">
  <o:attribute name="a1" value="${param['a1']}"/>
  <o:attribute name="a2" value="${param['a2']}"/>
  <o:attribute name="a3" value="${param['a3']}"/>
</o:attributes>
<o:element name="e" attr="${a}">
...
</o:element>

Element2.jsp

http://localhost:8080/xjtldemo/output/Element2.jsp

This second example is very similar to the first one. It generates the same XML element with three attributes, but this time the values of the attributes are obtained from the properties of a JavaBean object.

<e a1="v1" a2="v2" a3="v3">
...
</e>

The JavaBean class is named TestBean and it looks like this:

package com.devsphere.examples.xml.taglib;

public class TestBean {
    private String a1 = "v1";
    private String a2 = "v2";
    private String a3 = "v3";

    public String getA1() { return a1; }
    public String getA2() { return a2; }
    public String getA3() { return a3; }
}

Our JavaBean is instantiated within the JSP page using the standard <jsp:useBean> action.

<jsp:useBean id="b" scope="page" 
    class="com.devsphere.examples.xml.taglib.TestBean"/>

XJTL extracts the names of the three attributes (a1, a2 and a3) from the "b.a1 b.a2 b.a3" string. Then it evaluates ${b.a1}, ${b.a2} and ${b.a3} to obtain the values of the attributes from the bean's properties. With JSTL, you have to include a <c:out> action within the quotes of each XML attribute in order to output its value. In the case of JSP, the &, <, > and " characters must be escaped using a routine like DemoUtils.escapeXml().

XJTL
<o:element name="e" attr="b.a1 b.a2 b.a3">
...
</o:element>
JSTL
<e a1="<c:out value='${b.a1}'/>"
   a2="<c:out value='${b.a2}'/>"
   a3="<c:out value='${b.a3}'/>">
...
</e>
JSP
<%
String v1 = DemoUtils.escapeXml(b.getA1());
String v2 = DemoUtils.escapeXml(b.getA2());
String v3 = DemoUtils.escapeXml(b.getA3());
%>
<e a1="<%=v1%>" a2="<%=v2%>" a3="<%=v3%>">
...
</e>

Data.jsp

http://localhost:8080/xjtldemo/output/Data.jsp?d=data

The <o:data> XJTL action is very similar to the <c:out> JSTL action. Both can be used to output XML character data and know how to escape &, < and >. However, <o:data> also knows how to output CDATA sections as we'll see in CData.jsp. The Data.jsp page just outputs some character data which is given as request parameter.

XJTL
<o:data value="${param.d}"/>
JSTL
<c:out value="${param.d}"/>
JSP
<%= DemoUtils.escapeXml(request.getParameter("d")) %>

CData.jsp

http://localhost:8080/xjtldemo/output/CData.jsp?d=data

The CData.jsp example gets some character data as request parameter and produces a CDATA section.

<![CDATA[data]]>

Unlike the JSTL and JSP equivalents, the XJTL action knows how to generate the <![CDATA[ and ]]> delimiters automatically since <o:data> is an action specialized on XML character data output. In this case, &, < and > must not be escaped.

XJTL
<o:data value="${param.d}" section="true"/>
JSTL
<![CDATA[<c:out value="${param.d}" escapeXml="false"/>]]>
JSP
<![CDATA[<%= request.getParameter("d") %>]]>

Comment.jsp

http://localhost:8080/xjtldemo/output/Comment.jsp?c=comment

The Comment.jsp example takes a request parameter and produces an XML comment.

<!--comment-->

Unlike the JSTL and JSP equivalents, the XJTL action knows how to generate the <!-- and --> delimiters automatically since <o:comment> is an action specialized on outputting XML comments.

XJTL
<o:comment text="${param.c}"/>
JSTL
<!--<c:out value="${param.c}" escapeXml="false"/>-->
JSP
<!--<%= request.getParameter("c") %>-->

PI.jsp

http://localhost:8080/xjtldemo/output/PI.jsp?d=data&t=target

The PI.jsp example outputs an XML processing instruction with the given target and data.

<?target data?>

Unlike the JSTL and JSP equivalents, the XJTL action knows how to generate the <? and ?> delimiters automatically since <o:pi> is an action specialized on outputting XML processing instructions.

XJTL
<o:pi target="${param.t}" data="${param.d}"/>
JSTL
<?<c:out value="${param.t}"/> <c:out value="${param.d}" escapeXml="false"/>?>
JSP
<?<%= request.getParameter("t") %> <%= request.getParameter("d") %>?>

Dynamic.jsp

http://localhost:8080/xjtldemo/output/Dynamic.jsp

This example uses XJTL and JSTL together in order to generate an XML document dynamically.

<?xml version="1.0" encoding="UTF-8"?>
<person id='js890'>
    <name>John Smith</name>
    <email>John.Smith@yahoo.com</email>
    <phone>650-123-4567</phone>
    <address city='Palo Alto' state='CA' zip='94303' country='USA'>
        <line1>JS Information Systems, Inc.</line1>
        <line2>1001 San Antonio Road</line2>
    </address>
</person>

The <o:document> action produces the XML header and initializes the internal mechanisms of XJTL. Then <o:element> and <o:data> generate the XML elements and character data. The <c:set> action of JSTL creates the JSP variables that hold the values of the XML attributes.

<%@ page language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="o" uri="http://devsphere.com/xml/taglib/output" %>

<o:document>
    <c:set var="id" value="js890"/>
    <o:element name="person" attr="id">
        <o:element name="name">
            <o:data>John Smith</o:data>
        </o:element>
        <o:element name="email">
            <o:data>John.Smith@yahoo.com</o:data>
        </o:element>
        <o:element name="phone">
            <o:data>650-123-4567</o:data>
        </o:element>
        <c:set var="city" value="Palo Alto"/>
        <c:set var="state" value="CA"/>
        <c:set var="zip" value="94303"/>
        <c:set var="country" value="USA"/>
        <o:element name="address" attr="city state zip country">
            <o:element name="line1">
                <o:data>JS Information Systems, Inc.</o:data>
            </o:element>
            <o:element name="line2">
                <o:data>1001 San Antonio Road</o:data>
            </o:element>
        </o:element>
    </o:element>
</o:document>

Document.jsp

http://localhost:8080/xjtldemo/output/Document.jsp

This JSP parses an XML file obtaining a DOM tree with the help of JSTL and then it serializes the DOM tree back to XML using XJTL. In other words, this example outputs the content of the XML file going through an intermediary DOM phase. The XML content could have been printed directly to the JSP output, but we want to show how to use the <o:document> action for serializing a DOM tree. This XJTL action is very useful when some Java code produces or modifies a DOM tree that must be returned as XML by a JSP.

The <c:import> JSTL action loads the sample.xml file and stores its content into a JSP variable called xml. The <x:parse> JSTL action parses the XML content and creates a new JSP variable called dom that holds the resulted DOM tree. The <o:document> XJTL action reconstructs the XML content from the DOM tree and outputs that XML content.

<%@ page language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
<%@ taglib prefix="o" uri="http://devsphere.com/xml/taglib/output" %>

<c:import url="sample.xml" var="xml"/>
<x:parse xml="${xml}" varDom="dom"/>
<o:document dom="${dom}"/>

Fragment.jsp

http://localhost:8080/xjtldemo/output/Fragment.jsp

This JSP uses the same JSTL actions to parse an XML document and obtain a DOM tree. Then it uses <o:document> to output an XML header and generates some XML content in the body of this action. The <x:forEach> JSTL action is used to find all fragments of the DOM tree that are identified by the /person/address XPath, i.e. all <address> XML elements within the <person> root element of sample.xml. (There is only one.) Each DOM sub-tree identified by /person/address is outputted with the <o:fragment> XJTL action.

<%@ page language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>
<%@ taglib prefix="o" uri="http://devsphere.com/xml/taglib/output" %>

<c:import url="sample.xml" var="xml"/>
<x:parse xml="${xml}" varDom="dom"/>
<o:document>
    <x:forEach select="$dom/person/address" var="address">
        <o:fragment dom="${address}"/>
    </x:forEach>
</o:document>

Copyright © 2000-2009 Devsphere

About us
Contact us
Products
Services
Articles