Native XML Data Management with XIS 7 : XML Servlets « XML « Java






Native XML Data Management with XIS 7


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.parsers.*;

public class XsltDomServlet extends HttpServlet {

  private DOMImplementation dom;
  private Transformer transformer;

  public void init () throws ServletException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder db = dbf.newDocumentBuilder();
      dom = db.getDOMImplementation();
    } catch (ParserConfigurationException pce) {
      throw new ServletException (pce);
    }

    // prepare the XSLT transformer
    TransformerFactory tf = TransformerFactory.newInstance();
    StreamSource ss = new StreamSource("/var/www/stylesheets/paramTable.xslt");
    try {
      transformer = tf.newTransformer (ss);
    } catch (TransformerConfigurationException tce) {
      throw new ServletException (tce);
    }
  }

  public void doGet (HttpServletRequest request,
                     HttpServletResponse response)
      throws IOException, ServletException {
  }

  public void doPost (HttpServletRequest request,
                     HttpServletResponse response)
      throws IOException, ServletException {
    Document doc = dom.createDocument("","parameters",null);
    Element parameters = doc.getDocumentElement();

    parameters.setAttribute ("title", "XSLT DOM Servlet");
    Enumeration parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements ()) {
      String parameterName =
          parameterNames.nextElement().toString();
      Element parameter = doc.createElement ("parameter");
      parameters.appendChild (parameter);
      parameter.setAttribute ("name", parameterName);
      parameter.appendChild (doc.createTextNode
          (request.getParameter(parameterName)));
    }

    DOMSource domSource = new DOMSource (doc);
    StreamResult streamResult = new StreamResult (response.getWriter());

    try {
      transformer.transform (domSource, streamResult);
    } catch (TransformerException te) {
      throw new ServletException (te);
    }
  }
}

           
       








Related examples in the same category