Java/JSP/XML

Материал из Java эксперт
Версия от 18:01, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Deal With XML In JSP

JSP and SAX

<%@ 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<br>");      
    }
    catch (IOException e) 
    {
      throw new SAXException(e);
    }    
  } // end of startDocument()
  public void endDocument() throws SAXException
  {
    try 
    {
      out.write(++stepCount + ". End of document<p>");
      out.write("The total of all ages in the XML document is <b><i>"
                + totalAge + "</i></b>");
    }
    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: <b>" + qName + "</b>");
      int numberOfAttributes = attrs.getLength();
      if ( numberOfAttributes > 0 ) 
      {
        out.write(". Attributes: <ul>");
      } // end of if ()
      else 
        out.write("<br>");
      
      for ( int i=0; i<numberOfAttributes; i++) 
      {
        out.write("<li>" + attrs.getQName(i) + " = "
                  + attrs.getValue(i) + "</li>");
      } // end of for ()
        
      if ( numberOfAttributes > 0 ) 
      {
        out.write("</ul>");
      }
    }
    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 <b>" + qName + "</b><br>");      
    }
    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("<b>" + content + "</b><br>");
    }
    catch (IOException e) 
    {
      throw new SAXException(e);
    } // end of try-catch
    
  } // end of characters()
} // end of class MyHandler





JSP Displaying a Subset in XML

/*
<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:
    <ul>
      <x:forEach select="$parsedDoc/people/person/name[../age > 45]"
                 var="currentName" >
        <li><x:out select="." />
      </x:forEach>
    </ul>
  </body>
</html>





JSP in pure XML generating conforming XHTML

/*
 * 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"/>
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
&gt;
<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>
<h1>Hello</h1>
<p>Here on our farm <font color="green">
it is now <jsp:expression> new java.util.Date() </jsp:expression>.</font>
</p>
</body>
</html>
</jsp:root>





JSP List of data in the XML document

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="people">
    <h1>List of people in the XML document</h1>
    <table border="1">
      <th>Name</th><th>Age</th>
      <xsl:apply-templates />
    </table>
  </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>





JSP Parsing using JDOM

/*
<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"
%>
<!-- remember to change the url of the xml file-->
<%
  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>
    <h1>List of people</h1>
    <table border="1">
      <tr><th>Name</th><th>Age</th></tr>
      <%
        while (iter.hasNext()) // for each "person" node
        {
          Element  currentItem = (Element) iter.next();     // each "person"
          List     nameAndAge  = currentItem.getChildren();
          Iterator nameAgeIter = nameAndAge.iterator();
      %>
      <tr>
      <%
          while ( nameAgeIter.hasNext() )
          {
            Element child = (Element) nameAgeIter.next(); // "name" or "age"
      %>       
        <td><%= child.getText() %></td>
      <%
          }
        }
      %>
      </tr>
    </table>
  </body>
</html>





JSP Parsing using the DOM

/*
<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");
    %>
    <h1>List of people</h1>
    <table border="1">
      <tr><th>Name</th><th>Age</th></tr>
        
    <%
      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
    %>
    <tr>
    <%
        for (int j=0; j<nameAndAge.getLength(); j++ )
        {
          Node currentItem = nameAndAge.item(j);
          if ( isTextNode(currentItem)) 
            continue;
    %>
      <td><%= currentItem.getFirstChild().getNodeValue() %></td>
    <%
        } // end of name & age loop
    %>
    </tr>
    <%
      } // end person loop
    %>
    </table>
  </body>
</html>





JSP Parsing using the DOM and JSTL

/*
<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" />
    <h1>List of people</h1>
    <table border="1">
      <tr><th>Name</th><th>Age</th></tr>
      <x:forEach select="$parsedXml/people/person" var="currentPerson">
      <tr>
        <x:forEach select="*">
          <td><x:out select="." /></td>
        </x:forEach>
      </tr>
      </x:forEach>
    </table>
  </body>
</html>





JSP XML and XSLT transform

/*
<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">
    <h1>List of people in the XML document</h1>
    <table border="1">
      <th>Name</th><th>Age</th>
      <xsl:apply-templates />
    </table>
  </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">
    <!-- <xsl:param name="ageParam" /> -->
    <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>





Performing XSL Transformations

 

<%@ 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>
    <h1>Customer Orders</h1>
      <%! 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>





Using the Core XML tags

<%@ 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>
<h2>Here are the context-params and servlets from the XML file</h2>
<c:import url="http://localhost:8080/home/web.xml" var="webXml" />
<x:parse xml="${webXml}" var="doc" />
<h3>First the context params...</h3>
<x:forEach select="$doc//context-param">
    <x:out select="param-name"/>: <x:out select="param-value"/>
</x:forEach>
<h3>Now the servlet info...</h3>
<x:forEach select="$doc//servlet>
    <x:out select="servlet-name"/><br />
  <x:out select="servlet-class"/><br /><br />
</x:forEach>

</body>
</html>





XML transformation

<%@ 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"><h2>Build.xml targets</h2>
    <xsl:apply-templates />
    </body></html>
</xsl:template>
<xsl:template match="/project">
<dl>
    <xsl:for-each select="./target">
    <dt><b><xsl:value-of select="@name" /></b>&#xA0;</dt>
            <xsl:if test="@depends">
            <dd>depends=<xsl:value-of select="@depends" />&#xA0;</dd></xsl:if>        
    </xsl:for-each><!--end for-each contact -->
</dl>
</xsl:template>
        
<xsl:template match="text()">
    <xsl:value-of select="normalize-space()" />
</xsl:template>
    
    
</xsl:stylesheet>





XSLT In JSP

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

<HTML>
<H1> Enter card Info</H1>
<FORM NAME="CARDINFO" ACTION="/test/svgcard/process.jsp" TARGET="VIEWCARD">
<TABLE BORDER="0" CELLPADDING="4" CELLSPACING="2">
<TR><TD>Card To:</TD><TD><INPUT TYPE="TEXT" SIZE="20" NAME="cardto"></TD></TR>
<TR><TD>Card From:</TD><TD><INPUT TYPE="TEXT" SIZE="20" NAME="cardfrom"></TD></TR>
<TR><TD>Message:</TD><TD><INPUT TYPE="TEXT" SIZE="60" NAME="message"></TD></TR>
<TR><TD COLSPAN="2">&nbsp;</TD></TR>
<TR><TD><INPUT TYPE="SUBMIT" VALUE="PREVIEW"></TD><TD>&nbsp;</TD>
</TABLE>
</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>





XSLT in JSP 2

/*
  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>