Using XSLT in Java Applications

As you saw yesterday, JAXP provides a javax.xml.transform.Transformer class that is used to transform XML documents using XSLT. A javax.xml.transform.TransformerFactory is used to create a Transformer object. A new TransformerFactory object is created by the static newInstance() method in the factory class.

The following code creates a new TransformerFactory:

TransformerFactory factory = TransformerFactory.newInstance();

A Transformer object is created by a newTransformer() method in the factory object and optionally takes an XSLT stylesheet as a parameter to the method. The XSLT stylesheet must be accessed using a javax.xml.transform.stream.Source object. A StreamSource object can be constructed from a java.io.InputStream (or a File or Reader object).

The following code constructs a transformer from the XSLT stylesheet file called simple.xsl:

Source xsl = new StreamSource(new FileInputStream("simple.xsl"));
Transformer transformer = factory.newTransformer(xsl);

A Transformer object uses properties to configure information; these properties override properties set in the stylesheet itself. The Tranformer class provides suitable default properties but assumes the output document will be another XML document. If you want to change the output document type, you must define the method property of the Transformer object. Standard values for this property include html, xml, and text, but a particular XSLT implementation might support additional methods (such as xhtml). Transformer properties are defined in the javax.xml.transform.OutputKeys class. The following will configure a Transformer to output HTML rather than XML:

transformer.setOutputProperty(OutputKeys.METHOD,"html");

The Transformer.transform() method is used to transform an XML document using the XSLT stylesheet. The transform() method takes two parameters—a Source defining the XML document and a javax.xml.transform.stream.Result for the output file. A Result can be constructed from a java.io.OutputStream (or a File or Writer object).

The following lines will copy the XML document jobs.xml (shown in Listing 17.3 and provided on the Web site in the Day17/examples/JSP/examples directory) sending the output to the screen.

Source xml = new StreamSource(new FileReader("jobs.xml"));
transformer.transform(xml, new StreamResult(System.out));

In this case no transformation will take place.

Listing 17.3. jobs.xml
<?xml version="1.0"?>
<jobSummary>
 <job customer="winston" reference="Cigar Trimmer">
  <location>London</location>
  <description>Must like to talk and smoke</description>
  <!-- skills list for winston -->
  <skill>Cigar maker</skill>
  <skill>Critic</skill>
 </job>
 <job customer="george" reference="Tree pruner">
  <location>Washington</location>
  <description>Must be honest</description>
  <!-- skills list for george -->
  <skill>Tree surgeon</skill>
 </job>
</jobSummary>

A more useful servlet, which applies a user-selected XSLT stylesheet to a user-selected XML document, is shown in Listing 17.4. This servlet uses context.getResourceAsStream to access the XML and XSL files included in the Web Application.

Listing 17.4. Full Text of ApplyXSLT.java
import java.util.*;
import javax.xml.transform.*;
import javax.xml.transform.stream.*;

public class ApplyXSLT extends HttpServlet {

  public void doGet (HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException, java.net.MalformedURLException
  {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
      if (request.getParameter("show") != null) {
        RequestDispatcher rd =
          getServletContext().getRequestDispatcher("/showXSLT");
        rd.forward(request,response);
      }
      String source = request.getParameter("source");
      int ix = source.lastIndexOf('/'),
      String xmlDoc = source.substring(0,ix);
      String xslDoc = source.substring(ix);
      TransformerFactory factory = TransformerFactory.newInstance();

      ServletContext context = getServletContext();
      Source xsl = new StreamSource(context.getResourceAsStream(xslDoc));
      Transformer transformer = factory.newTransformer(xsl);
      transformer.setOutputProperty(OutputKeys.METHOD,"html");

      out.println("<H2>Transformed Document</H2>");
      Source xml = new StreamSource(context.getResourceAsStream(xmlDoc));
      transformer.transform(xml, new StreamResult(out));

    }
    catch (Exception ex) {
      out.println(ex);
      ex.printStackTrace(out);
    }
    out.close();
  }
}

The ApplyXSLT servlet works in conjunction with a ShowXSLT servlet (not shown here but is included with the example code for Day 17 on the Web site accompanying this book). The ApplyXSLT servlet applies the stylesheet while the ShowXSLT servlet simply outputs the original XML document and XSLT stylesheet. To control which servlet is to be used a request parameter called “show” or “apply” is provided with the HTTP request. The first task of either servlet is to forward the request to the other servlet if appropriate using the RequestDispatcher object. A suitable form for use with this servlet is shown in Listing 17.5.

Listing 17.5. Full Text of xsltForm.jsp
<HTML>
<HEAD><TITLE>XLST Transformations</TITLE></HEAD>
<BODY>
  <FORM action="applyXSLT">
    <P>Select an XML document/XSL stylesheet to transform:
    <SELECT name="source">
      <OPTION>/jobs.xml/simple.xsl
      <OPTION>/jobs.xml/basicHTML.xsl
      <OPTION>/jobs.xml/comment.xsl
      <OPTION>/jobs.xml/simpleLine.xsl
      <OPTION>/jobs.xml/simpleStrip.xsl
      <OPTION>/jobs.xml/tableCount.xsl
      <OPTION>/jobs.xml/tableStyle.xsl
      <OPTION>/jobs.xml/textHTML.xsl
      <OPTION>/jobs.xml/table.xsl
      <OPTION>/dd.xml/session.xsl
    </SELECT></P>
    <P><INPUT type="submit" name="apply" value="Transform Document"></P>
    <P><INPUT type="submit" name="show"
              value="Show Document/XSLT Stylesheet"></P>
  </FORM>
</BODY>
</HTML>

After determining the nature of the HTTP request the ApplyXSLT servlet in listing 17.4 reads a request parameter that defines the XML source file and the XSLT stylesheet file, which must be defined in the same Web application as the servlet. To simplify the parameter parsing the two filenames are passed as a single parameter called source, each filename being preceded by a forward slash (/). The servlet displays the transformed document.

You will be able to use this form and servlet to examine the example transformations shown today.

To run this demonstration servlet, use the supplied asant build files to run the following command from the Day17/examples directory:

asant build deploy

You can access the HTML form as the welcome page for the XLST Web application using the URL

http://localhost:8000/examples

Select the XML document and XSLT stylesheet pair you want to view and click the “Submit” button. Your screen will look similar to the one shown in Figure 17.1.

Figure 17.1. Viewing the simple XML transformation.


So far, you have seen a very simple XLST transformation. You will now look in more detail at XSLT and its capabilities.

If you do not want to use the ApplyXSLT servlet, the code on the accompanying Web site includes a simple command line application that accepts a command line of the form

Transform stylesheet source [ destination ]

from the Day17/examples directory you can apply the simple.xsl XSLT stylesheet to the sample jobs.xml document using the command

> java -classpath classes Transform JSP/examples/simple.xsl JSP/examples/jobs.xml

Alternatively, use the supplied asant build files and enter

> asant Transform

and supply the parameters when prompted.

All of the example XSLT stylesheets and XML documents are provided in the Day17/examples/JSP/examples sub-directory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.66.128