Using XSLT with Java Server Pages

Using XSLT with Java Server Pages

I used Microsofts MSXML processor with Active Server Pages, but Java Server Pages need not run on Windows server platforms, so I dont use MSXML with JSP. Instead, I use Xalans Java API to perform the XSLT transformation and send the results to the clients browser.

For example, I can use Xalan to create planets.html as a temporary document on the server (this code assumes planets.xml and planets.xsl are in the same directory as the JSP script) this way:

 <%@ page errorPage="error.jsp" language="java"      contentType="text/html" import="org.apache.xalan.xslt.*;java.io.*" %%>      <%          try          {             XSLTProcessor processor = XSLTProcessorFactory.getProcessor();              processor.process(new XSLTInputSource("planets.xml"),                  new XSLTInputSource("planets.xsl"),                  new XSLTResultTarget("planets.html");          }          catch(Exception e) {}          .          .          . 

Then all I have to do is to open that document and send it back to the client:

Listing 10.13 Server-Based XSLT Using JSP
 <%@ page errorPage="error.jsp" language="java"      contentType="text/html" import="org.apache.xalan.xslt.*;java.io.*" %>      <%          try          {             XSLTProcessor processor = XSLTProcessorFactory.getProcessor();              processor.process(new XSLTInputSource("planets.xml"),                  new XSLTInputSource("planets.xsl"),                  new XSLTResultTarget("planets.html"));          }          catch(Exception e) {}          FileReader filereader = new FileReader("planets.html");          BufferedReader bufferedreader = new BufferedReader(filereader);          String instring;          while((instring = bufferedreader.readLine()) != null) { %>              <%= instring %>      <% }      filereader.close();      pw.close();  %> 

Thats all it takes. You can see the results of this JSP script in Figure 10.6.

Figure 10.6. Using XSLT with JSP.
graphics/10fig06.gif


Inside XSLT
Inside Xslt
ISBN: B0031W8M4K
EAN: N/A
Year: 2005
Pages: 196

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net