User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Java section within the Software Development category of DaniWeb, a massive community of 425,860 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,563 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Java advertiser: Lunarpages Java Web Hosting
Feb 9th, 2005
Views: 9,878
The question how to create HTML output to the browser from a Servlet based on XML data often comes up.
Here's a fully functional example on how to achieve this using Jakarta Xalan 2 and Xerces 2.

The system is quite simple, most of the code is concerned with housekeeping chores rather than the actual HTML generation and output.
java Syntax | 4 stars
  1. [code]
  2. package somepackage;
  3.  
  4. import java.io.BufferedInputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.io.PrintWriter;
  9. import java.util.HashMap;
  10.  
  11. import javax.servlet.ServletException;
  12. import javax.servlet.http.HttpServlet;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import javax.xml.transform.Source;
  16. import javax.xml.transform.Transformer;
  17. import javax.xml.transform.TransformerConfigurationException;
  18. import javax.xml.transform.TransformerException;
  19. import javax.xml.transform.TransformerFactory;
  20. import javax.xml.transform.TransformerFactoryConfigurationError;
  21. import javax.xml.transform.dom.DOMSource;
  22. import javax.xml.transform.stream.StreamResult;
  23. import javax.xml.transform.stream.StreamSource;
  24.  
  25. import org.w3c.dom.Document;
  26.  
  27. /**
  28.  * Generate servlet output based on XML input and an XSLT document.
  29.  * filename, XML Document (DOM Object), and an optional contenttype
  30.  * are to be passed in as requestparameters.
  31.  * @author Jeroen Wenting
  32.  */
  33. public class Generator extends HttpServlet
  34. {
  35. public static final String defContentType = "text/html; charset=UTF-8";
  36. public static final String contentTypeHTML = defContentType;
  37. // public static final String contentTypeXML = "text/xml; charset=UTF-8";
  38. // public static final String contentTypeCSV = "application/vnd.ms-excel";
  39. public static final String errorTemplate = "+++ERRORS+++";
  40. private static HashMap cache;
  41. /**
  42. *
  43. */
  44. public Generator()
  45. {
  46. super();
  47. }
  48.  
  49. /**
  50. * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  51. */
  52. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  53. throws ServletException, IOException
  54. {
  55. doPost(request, response);
  56. }
  57.  
  58. /**
  59. * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  60. */
  61. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  62. throws ServletException, IOException
  63. {
  64. String contentType = null;
  65. Document doc = null;
  66. String xsl = null;
  67.  
  68. contentType = (String)request.getAttribute("contenttype");
  69. if (contentType == null) contentType = defContentType;
  70. doc = (Document)request.getAttribute("xml-doc");
  71. xsl = (String)request.getAttribute("xsl-file-name");
  72. String path = getServletContext().getRealPath("/WEB-INF/xsl/");
  73. // Output goes in the response stream.
  74. PrintWriter out = response.getWriter();
  75.  
  76. if (doc == null || xsl == null)
  77. {
  78. String errorMsg = "";
  79. if (doc == null)
  80. errorMsg += "XML document missing from call to OutputGenerator<br />";
  81. if (xsl == null)
  82. errorMsg += "XSL filename missing from call to OutputGenerator<br />";
  83. StringBuffer buf = generateError(errorMsg);
  84. log(errorMsg);
  85. out.write(buf.toString());
  86. return;
  87. }
  88.  
  89. // The servlet returns HTML.
  90. response.setContentType(contentType);
  91. if (cache == null) cache = new HashMap();
  92. Transformer t = null;
  93. // Get the XML input document and the stylesheet.
  94. Source xmlSource = new DOMSource(doc);
  95. // Perform the transformation, sending the output to the response.
  96.  
  97. // XSL processing can be time consuming, but this is mainly due to the overhead
  98. // of compiling the XSL sheet.
  99. // By caching the compiled sheets, the process is speeded up dramatically.
  100. // Time saved on subsequent requests can be 99% or more (hundreds of milliseconds).
  101. try
  102. {
  103. // check if the XSL sheet was found in cache, and use that if available
  104. if (cache.containsKey(xsl)) t = (Transformer)cache.get(xsl);
  105. else
  106. {
  107. // otherwise, load the XSL sheet from disk, compile it and store the compiled
  108. // sheet in the cache
  109. TransformerFactory tFactory = TransformerFactory.newInstance();
  110. Source xslSource = new StreamSource(new File(path, xsl+".xsl"));
  111. t = tFactory.newTransformer(xslSource);
  112. cache.put(xsl, t);
  113. }
  114. // perform the XSL transformation of the XML Document into the servlet outputstream
  115. t.transform(xmlSource, new StreamResult(out));
  116. }
  117. catch (TransformerConfigurationException e)
  118. {
  119. e.printStackTrace();
  120. throw new ServletException(e);
  121. }
  122. catch (TransformerFactoryConfigurationError e)
  123. {
  124. e.printStackTrace();
  125. throw new ServletException(e);
  126. }
  127. catch (TransformerException e)
  128. {
  129. e.printStackTrace();
  130. throw new ServletException(e);
  131. }
  132.  
  133. }
  134.  
  135. private StringBuffer generateError(String error) throws IOException
  136. {
  137.  
  138. String path = getServletContext().getRealPath("/WEB-INF/templates/");
  139. File f = new File(path, "callerror.html");
  140. FileInputStream fs = new FileInputStream(f);
  141. BufferedInputStream bis = new BufferedInputStream(fs);
  142. int numBytes = bis.available();
  143. byte b[] = new byte[numBytes];
  144. // read the template into a StringBuffer (via a byte array)
  145. bis.read(b);
  146. StringBuffer buf = new StringBuffer();
  147. buf.append(b);
  148. int start = buf.indexOf(errorTemplate);
  149. int end = start + errorTemplate.length();
  150. // replace placeholder with errormessage
  151. // (will automatically adjust to take longer or shorter data into account)
  152. buf.replace(start, end, error);
  153. return buf;
  154. }
  155.  
  156. }
  157. [/code]
  158.  
  159. ======================================================
  160. Sample XSLT:
  161.  
  162. [code]
  163. <?xml version="1.0"?>
  164. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  165.  
  166. <xsl:import href="title.xsl" />
  167.  
  168. <xsl:output method="html" indent="yes"/>
  169. <xsl:template match="ehwa-doc">
  170. <html>
  171. <xsl:call-template name="title"/>
  172. <body><xsl:attribute name="onload"><xsl:apply-templates select="focuscontrol"/></xsl:attribute>
  173. <form>
  174. <input type="hidden" value="1" name="runset" id="runset"/>
  175. </form>
  176. <xsl:call-template name="hello"/>
  177. </body>
  178. </html>
  179. </xsl:template>
  180.  
  181. <xsl:template match="focuscontrol">
  182. <xsl:value-of select="."/>
  183. </xsl:template>
  184.  
  185. <xsl:template name="hello">
  186. <xsl:value-of select="data" />
  187. </xsl:template>
  188.  
  189. </xsl:stylesheet>
  190. [/code]
  191. ======================================================
  192. Error HTML template:
  193.  
  194. [code]
  195. <?xml version="1.0"?>
  196. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  197. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  198. <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
  199. <head>
  200. <title></title>
  201. </head>
  202.  
  203. <body>
  204. +++ERRORS+++
  205. </body>
  206. </html>
  207. [/code]
  208.  
  209. ======================================================
  210. Sample servlet to generate the XML and forward to the generator:
  211.  
  212. [code]
  213. package somepackage;
  214.  
  215. import java.io.IOException;
  216.  
  217. import javax.servlet.RequestDispatcher;
  218. import javax.servlet.ServletException;
  219. import javax.servlet.http.HttpServlet;
  220. import javax.servlet.http.HttpServletRequest;
  221. import javax.servlet.http.HttpServletResponse;
  222.  
  223. import org.apache.xerces.dom.DocumentImpl;
  224. import org.w3c.dom.Document;
  225. import org.w3c.dom.Element;
  226.  
  227. /**
  228.  * @author Jeroen Wenting
  229.  */
  230. public class XSLTest extends HttpServlet
  231. {
  232.  
  233. /**
  234. * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  235. */
  236. protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
  237. throws ServletException, IOException
  238. {
  239. doPost(arg0, arg1);
  240. }
  241.  
  242. /**
  243. * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
  244. */
  245. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  246. throws ServletException, IOException
  247. {
  248. String xslFilename = getInitParameter("xslfile-html");
  249. String beanName = getInitParameter("formbean");
  250. String contentType = getInitParameter("contenttype");
  251. request.setAttribute("xsl-file-name", xslFilename);
  252. if (contentType != null) request.setAttribute("contenttype", contentType);
  253. Document doc = new DocumentImpl();
  254.  
  255. Element root = doc.createElement("ehwa-doc");
  256.  
  257. // generate XML for transformation
  258. Element elem = doc.createElement("focuscontrol");
  259. elem.appendChild(doc.createTextNode("alert('loaded')"));
  260. root.appendChild(elem);
  261. elem = doc.createElement("data");
  262. elem.appendChild(doc.createTextNode("Hello World!"));
  263. root.appendChild(elem);
  264.  
  265. doc.appendChild(root);
  266. request.setAttribute("xml-doc", doc);
  267. RequestDispatcher rd = request.getRequestDispatcher("/servlet/generator");
  268. rd.forward(request, response);
  269. }
  270.  
  271.  
  272. }
  273. [/code]
Comments (Newest First)
j_abdou_a51 | Newbie Poster | Jun 14th, 2008
hot work !!!
majestic0110 | Veteran Poster | Apr 3rd, 2008
Very nice, constructed a similar project myself (in C# as opposed to Java) the main difficulty I encountered was achieving the transformation on a specific XML(user specified) file. This involved uploading that file (via file upload - ASP.NET) to a server, then transforming that to a HTML file (on server) then removing the uploaded (and no longer needed) XML file on the server. From here, the user could download the newly transformed HTML file. These things have to be considered though lol.... Love the Snippet!
sreeraj4u | Newbie Poster | May 30th, 2007
this is very good
sreeraj4u | Newbie Poster | May 30th, 2007
Post Comment

Only community members can submit or comment on code snippets. You must register or log in to contribute.

DaniWeb Marketplace (Sponsored Links)
All times are GMT -4. The time now is 5:45 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC