Java/JSP/XML

Материал из Java эксперт
Перейти к: навигация, поиск

Deal With XML In JSP

JSP and SAX

   <source lang="java">

<%@ page import="javax.xml.parsers.SAXParserFactory,

                javax.xml.parsers.SAXParser,
                com.jexp.MyHandler"%>

<html>

 <head><title>JSP and SAX</title></head>
 <body>
   <%
     SAXParserFactory factory   = SAXParserFactory.newInstance();
     SAXParser        parser    = factory.newSAXParser();
     MyHandler        myHandler = new MyHandler(out);
     parser.parse("http://localhost:8080/chapter10/people.xml",
                  myHandler);
   %>
 </body>

</html>

package com.jexp; import java.io.IOException; import javax.servlet.jsp.JspWriter; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class MyHandler extends DefaultHandler {

 private int       stepCount, totalAge;
 private JspWriter out;
 private boolean   insideAgeElement;
 
 public MyHandler(JspWriter out)
 {
   this.out = out;
 }
 public void startDocument() throws SAXException
 {
   try 
   {
     out.write(++stepCount + ". Start of document
"); } catch (IOException e) { throw new SAXException(e); } } // end of startDocument() public void endDocument() throws SAXException { try {
out.write(++stepCount + ". End of document

"); out.write("The total of all ages in the XML document is " + totalAge + ""); } catch (IOException e) { throw new SAXException(e); } } // end of endDocument() public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) throws SAXException { if ( qName.equals("age")) { insideAgeElement = true; } try { out.write(++stepCount + ". Start of element: " + qName + ""); int numberOfAttributes = attrs.getLength(); if ( numberOfAttributes > 0 ) { out.write(". Attributes:

    "); } // end of if () else out.write("
    "); for ( int i=0; i<numberOfAttributes; i++) { out.write("
  • " + attrs.getQName(i) + " = " + attrs.getValue(i) + "
  • ");
         } // end of for ()
           
         if ( numberOfAttributes > 0 ) 
         {
    
    out.write("
");
     }
   }
   catch (IOException e) 
   {
     throw new SAXException(e);
   }    
 } // end of startElement()
 public void endElement(String namespaceURI, String localName, String qName)
     throws SAXException
 {
   if ( qName.equals("age") ) 
   {
     insideAgeElement = false;
   }
   
   try 
   {
     out.write(++stepCount + ". End of element " + qName + "
"); } catch (IOException e) { throw new SAXException(e); } // end of try-catch } // end of endElement() public void characters(char[] chars, int start, int length) throws SAXException { String content = new String(chars, start, length); if ( insideAgeElement ) { int age = Integer.parseInt(content); totalAge += age; } try { out.write(++stepCount + ". Character content = "); if ( length > 0 ) out.write("" + content + "
"); } catch (IOException e) { throw new SAXException(e); } // end of try-catch } // end of characters()

} // end of class MyHandler


      </source>
   
  
 
  



JSP Displaying a Subset in XML

   <source lang="java">

/* <people>

 <person>
   <name>Peter</name>
   <age>54</age>
 </person>
 <person>
   <name>Patricia</name>
   <age>50</age>
 </person>

</people>

  • /

<%@ taglib uri="http://java.sun.ru/jstl/xml" prefix="x" %> <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <html >

 <head>
   <title>Displaying a Subset</title>
 </head>
 <body>
   <c:import url="http://localhost:8080/chapter02/people.xml"
             var="inputDoc" />
   <x:parse  xml = "${inputDoc}"
             var = "parsedDoc" />
   Here is a list of people over the age of 45:
    <x:forEach select="$parsedDoc/people/person/name[../age > 45]" var="currentName" >
  • <x:out select="." /> </x:forEach>
 </body>

</html>


      </source>
   
  
 
  



JSP in pure XML generating conforming XHTML

   <source lang="java">

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

<?xml version="1.0"?> <jsp:root xmlns:jsp="http://java.sun.ru/JSP/Page" version="1.2"> <jsp:directive.page contentType="text/html"/> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"

> <html> <head>

 <title>JSP in pure XML generating conforming XHTML</title>
 <meta name="version"
   content="$Id: hello-xml.jsp,v 1.3 2003/08/23 01:48:21 ian Exp $" />
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head> <body>

Hello

<p>Here on our farm it is now <jsp:expression> new java.util.Date() </jsp:expression>.

</body> </html> </jsp:root>


      </source>
   
  
 
  



JSP List of data in the XML document

   <source lang="java">

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

 <xsl:template match="people">

List of people in the XML document

     <xsl:apply-templates />
NameAge
 </xsl:template>
 <xsl:template match="person">
   <tr>
     <td><xsl:value-of select="name/text()" /></td>
     <td><xsl:value-of select="age/text()"  /></td>
   </tr>    
 </xsl:template>

</xsl:transform> <%@ taglib uri="http://java.sun.ru/jstl/xml" prefix="x" %> <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <html>

 <head>
   <title>Transforming a Subset</title>
 </head>
 <body>
   <c:import url="http://localhost:8080/chapter12/Multi-Template/people.xml"
             var="inputDoc" />
   <c:import url="http://localhost:8080/chapter12/Multi-Template/transform.xsl"
             var="stylesheet" />
   <x:parse  xml = "${inputDoc}"
             var = "parsedDoc" />
   <x:set    select = "$parsedDoc/people/person/name[../age > 50]"
             var    = "subset" />
    
   <x:transform xml  = "${subset}"
                xslt = "${stylesheet}" />
 </body>

</html>


      </source>
   
  
 
  



JSP Parsing using JDOM

   <source lang="java">

/* <people>

 <person>
   <name>Joe</name>
   <age>30</age>
 </person>
 <person>
   <name>Rob</name>
   <age>29</age>
 </person>

</people>

  • /

<%@ page import="org.jdom.Element,

                org.jdom.Document,
                org.jdom.input.SAXBuilder,
                java.util.List,
                java.util.Iterator"

%>

<%

 SAXBuilder builder  = new SAXBuilder();
 Document   doc      = builder.build("http://localhost:8080/chapter11/people.xml");
 List       children = doc.getRootElement().getChildren(); // 2 person nodes
 Iterator   iter     = children.iterator();

%> <html>

 <head><title>Parsing using JDOM</title></head>
 <body>

List of people

     <%
       while (iter.hasNext()) // for each "person" node
       {
         Element  currentItem = (Element) iter.next();     // each "person"
         List     nameAndAge  = currentItem.getChildren();
         Iterator nameAgeIter = nameAndAge.iterator();
     %>
<% while ( nameAgeIter.hasNext() ) { Element child = (Element) nameAgeIter.next(); // "name" or "age"  %>
     <%
         }
       }
     %>
NameAge
<%= child.getText() %>
 </body>

</html>


      </source>
   
  
 
  



JSP Parsing using the DOM

   <source lang="java">

/* <people>

 <person>
   <name>Joe</name>
   <age>30</age>
 </person>
 <person>
   <name>Rob</name>
   <age>29</age>
 </person>

</people>

  • /

<%@page import="org.w3c.dom.Node, org.w3c.dom.Element, org.w3c.dom.Document, org.w3c.dom.NodeList, javax.xml.parsers.DocumentBuilder, javax.xml.parsers.DocumentBuilderFactory" %> <%!

 public boolean isTextNode(Node n)
 {
   return n.getNodeName().equals("#text");
 }

%> <html>

 <head><title>Parsing using the DOM</title></head>
 <body>
   <%
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     DocumentBuilder        builder = factory.newDocumentBuilder();
     Document doc = builder.parse("http://localhost:8080/chapter02/people.xml");
   %>

List of people

   <%
     Element  root        = doc.getDocumentElement(); // "people" node
     NodeList personNodes = root.getChildNodes();     // 2 "person" nodes
     for (int i=0; i<personNodes.getLength(); i++)
     {
       Node currentPerson = personNodes.item(i);
       if (isTextNode(currentPerson)) // skip whitespace node
         continue;
       NodeList nameAndAge = currentPerson.getChildNodes(); // "name" and "age" nodes
   %>
<% for (int j=0; j<nameAndAge.getLength(); j++ ) { Node currentItem = nameAndAge.item(j); if ( isTextNode(currentItem)) continue;  %>
   <%
       } // end of name & age loop
   %>
<% } // end person loop  %>
NameAge
<%= currentItem.getFirstChild().getNodeValue() %>
 </body>

</html>


      </source>
   
  
 
  



JSP Parsing using the DOM and JSTL

   <source lang="java">

/* <people>

 <person>
   <name>Joe</name>
   <age>30</age>
 </person>
 <person>
   <name>Rob</name>
   <age>29</age>
 </person>

</people>

  • /

<%@ taglib uri="http://java.sun.ru/jstl/xml" prefix="x" %> <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <html>

 <head><title>Parsing using the DOM and JSTL</title></head>
 <body>
   <c:import url="http://localhost:8080/chapter11/people.xml"
             var="personXml" />
   <x:parse xml="${personXml}" varDom="parsedXml" />

List of people

     <x:forEach select="$parsedXml/people/person" var="currentPerson">
<x:forEach select="*">
       </x:forEach>
</x:forEach>
NameAge
<x:out select="." />
 </body>

</html>


      </source>
   
  
 
  



JSP XML and XSLT transform

   <source lang="java">

/* <people>

 <person>
   <name>Peter</name>
   <age>54</age>
 </person>
 <person>
   <name>Patricia</name>
   <age>50</age>
 </person>

</people>

  • /

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

 <xsl:param name="ageParam">60</xsl:param>
 <xsl:template match="people">

List of people in the XML document

     <xsl:apply-templates />
NameAge
 </xsl:template>
 <xsl:template match="person">
   <xsl:call-template name="processPerson">
     <xsl:with-param name="ageParam">
       51
     </xsl:with-param>
   </xsl:call-template>
 </xsl:template>
 <xsl:template name="processPerson">
   
   <tr>
     <td>
       <xsl:value-of select="name/text()" />
     </td>
     <td>
       <xsl:value-of select="age/text()"  />
       <xsl:if test="age/text() > $ageParam">
           (old!)
         </xsl:if>
     </td>
   </tr>    
 </xsl:template>

</xsl:transform>

  • /

<%@ taglib uri="http://java.sun.ru/jstl/xml" prefix="x" %> <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <html >

 <head>
   <title>Using a Named Template with Global Parameters</title>
 </head>
 <body>
   <c:import url="http://localhost:8080/chapter02/people.xml"
             var="inputDoc" />
   <c:import url="http://localhost:8080/chapter02/globalParam.xsl"
             var="stylesheet" />
   <x:transform xml  = "${inputDoc}"
                xslt = "${stylesheet}">
     <x:param name="ageParam"  value="49" />
   </x:transform>
 </body>

</html>


      </source>
   
  
 
  



Performing XSL Transformations

   <source lang="java">

<%@ page language="java" contentType="text/html" %> <%@ page pageEncoding="UTF-8"%> <%@ page import="javax.xml.transform.*"%> <%@ page import="javax.xml.transform.stream.*"%> <html>

 <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>Customer Orders</title>
 </head>
 <body>

Customer Orders

     <%! String FS = System.getProperty("file.separator"); %>
       <%
       String xmlFile = request.getParameter("XML");
       String xslFile = request.getParameter("XSL");
       String ctx = getServletContext().getRealPath("") + FS;
       xslFile = ctx + xslFile;
       xmlFile = ctx + xmlFile;
       TransformerFactory tFactory = TransformerFactory.newInstance();
       Transformer transformer = tFactory.newTransformer(new StreamSource(xslFile));
       transformer.transform(new StreamSource(xmlFile), new StreamResult(out));
       %>
   </body>

</html>

</source>
   
  
 
  



Using the Core XML tags

   <source lang="java">

<%@ taglib uri="http://java.sun.ru/jstl/xml" prefix="x" %> <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <html> <head><title>Using the Core XML tags</title></head> <body>

Here are the context-params and servlets from the XML file

<c:import url="http://localhost:8080/home/web.xml" var="webXml" /> <x:parse xml="${webXml}" var="doc" />

First the context params...

<x:forEach select="$doc//context-param">

   <x:out select="param-name"/>: <x:out select="param-value"/>

</x:forEach>

Now the servlet info...

<x:forEach select="$doc//servlet>

   <x:out select="servlet-name"/>
<x:out select="servlet-class"/>

</x:forEach>

</body> </html>


      </source>
   
  
 
  



XML transformation

   <source lang="java">

<%@ taglib uri="http://java.sun.ru/jstl/xml" prefix="x" %> <%@ taglib uri="http://java.sun.ru/jstl/core" prefix="c" %> <c:import url="http://localhost:8080/home/build.xml" var="buildXml" /> <c:import url="/WEB-INF/xslt/myTrans.xsl" var="xslt" /> <x:transform xml="${buildXml}" xslt="${xslt}" /> //myTrans.xsl

<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html"/> <xsl:template match="/">

   <html><head><title>List of build.xml targets
</title></head><body bgcolor="white">

Build.xml targets

   <xsl:apply-templates />
   </body></html>

</xsl:template> <xsl:template match="/project">

<xsl:for-each select="./target">
<xsl:value-of select="@name" /> 
<xsl:if test="@depends">
depends=<xsl:value-of select="@depends" /> 
</xsl:if> </xsl:for-each>

</xsl:template>

<xsl:template match="text()">

   <xsl:value-of select="normalize-space()" />

</xsl:template>


</xsl:stylesheet>

      </source>
   
  
 
  



XSLT In JSP

   <source lang="java">

/*

 Java, XML, and Web Services Bible
 Mike Jasnowski
 ISBN: 0-7645-4847-6
  • /

<HTML>

Enter card Info

<FORM NAME="CARDINFO" ACTION="/test/svgcard/process.jsp" TARGET="VIEWCARD">

Card To:<INPUT TYPE="TEXT" SIZE="20" NAME="cardto">
Card From:<INPUT TYPE="TEXT" SIZE="20" NAME="cardfrom">
Message:<INPUT TYPE="TEXT" SIZE="60" NAME="message">
 
<INPUT TYPE="SUBMIT" VALUE="PREVIEW"> 

</FORM> </HTML>

<%@ page contentType="image/svg-xml" %> <% String cardTo = request.getParameter("cardto"); String cardFrom = request.getParameter("cardfrom"); String message = request.getParameter("message"); %> <svg width="400" height="200"> <g style="font-family:Arial;font-size:12pt;">

<text x="10" y="20">
   <%= cardTo %>, someone has sent you a message
</text>
<text x="10" y="60">
   <%= cardFrom %> would like to tell you
</text>
<text x="10" y="140">
   <%= message %>
</text>

</g> </svg>

      </source>
   
  
 
  



XSLT in JSP 2

   <source lang="java">

/*

 Java, XML, and Web Services Bible
 Mike Jasnowski
 ISBN: 0-7645-4847-6
  • /

<%@ page contentType="image/svg-xml" %> <%@ page import="org.xml.sax.*" %> <%@ page import="org.apache.xalan.xslt.*" %> <%@ page import="java.io.*" %> <% try {

   XSLTProcessor processor = XSLTProcessorFactory.getProcessor(); 
      
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   
   processor.process(new XSLTInputSource("games.xml"),
                     new XSLTInputSource("games.xsl"),
                   new XSLTResultTarget(bos));
   out.println(bos);
   

} catch (Exception ex) {

   out.println(ex);

} %>

<?xml version="1.0"?> <games>

 <game genre="rpg">XML Invaders</game>
 <game genre="rpg">A Node in the XPath</game>
 <game genre="rpg">XPath Racers</game>

</games> //games.xsl <?xml version="1.0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html"/> <xsl:template match="/"> <svg width="200" height="200"> <g> <xsl:for-each select="games/game"> <text x="10" y="{number(10)*position()}"> <xsl:value-of select="text()"/> </text> </xsl:for-each> </g> </svg> </xsl:template> </xsl:stylesheet>

      </source>