This example application uses what we know about beans to query a database and write out its result set as an XML file. You can then transform the resulting XML file for presentation to a WAP client or an HTTP client.
To run this application, you need to download the Xalan XML parser from http://xml.apache.org. Once you've got it, install it in Tomcat's WEB-INF/lib directory, and restart Tomcat to make it available to the application.
[View full width]<%--File: writeNews.jsp Purpose: call the writeNewsXMLBean, which does a query to get News events and writes out the result as an XML file. --%> <jsp:useBean id="newsQ2xml" class = "javaforcf.writeXMLNewsBean" /> <% newsQ2xml.writeXMLNews(); %> <h1>The files were written.</h1>
The purpose of writeNews.jsp is to call the writeNewsBean bean to handle all the work of the application.
/* Purpose: query a database and write out an XML document representing the dataset. This can then be read into a Flash movie, or consumed by any other kind of client. */ package javaforcf; import java.io.*; import java.sql.*; import java.util.*; public class writeXMLNewsBean { public void writeXMLNews() { // delete old file File oldFile = new File("/usr/tomcat4/webapps/ javaforcf/xmlout/news.xml"); boolean fileDeleted = oldFile.delete(); if (fileDeleted) { // declare a file output object FileOutputStream out; // declare a print stream object PrintStream p; // holds News items from db int cols; String thexml, url, sql, colName, path; try { // connect to the database url = "jdbc:mysql:/// cybertrailscomdb?user=eben&password=secret"; // query sql = "SELECT itemName, itemText from items WHERE isCurrent = 1"; // use mysql database Class.forName("org.gjt.mm.mysql.Driver"); Connection conn = DriverManager.getConnection(url, "", ""); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(sql); ResultSetMetaData rsmd = rset.getMetaData(); cols = rsmd.getColumnCount(); // set the query into an xml string thexml = "<?xml version=\"1.0\"?>"; thexml += "<dataset>"; while (rset.next()) { thexml += "<row>"; for(int i=1; i<=cols; i++) { colName = rsmd.getColumnLabel(i); thexml += "<" +colName.toLowerCase()+">" + cleanseData(rset.getString(i)) + "</" + colName.toLowerCase() +">"; } thexml += "</row>"; } thexml += "</dataset>"; // Create a new file output stream // connect path = "/usr/tomcat4/webapps/javaforcf/xmlout/news.xml"; out = new FileOutputStream( path ); // Connect print stream to the output stream p = new PrintStream( out ); // write the file data p.println (thexml); // close the connection p.close(); } catch (Exception e) { System.err.println ("Error writing to file"); } } } public String cleanseData(String data) { //String to hold the cleansed text String cleantext = ""; /* Object to break down the string into tokens delimited by < and > */ StringTokenizer breakdown = new StringTokenizer(data, "<>"); //Stop holds the original amount of tokens int stop = breakdown.countTokens(); /* Loop to go over the tokens, discarding the 'br' which is in the middle of < and > so that only the text gets taken into the cleantext variable and written out to xml */ for(int x = 0; breakdown.hasMoreTokens(); x++) { cleantext = cleantext + breakdown.nextToken(); /* stop/2 + 1 is the last time the loop will run so that only 1 token will be taken the last time so that the tokenizer never throws an exception */ if(x != stop - (stop/2 + 1)) { breakdown.nextToken(); } } return cleantext; } }
First the bean hits the database, then it deletes a file that might exist and writes out a new XML file containing elements corresponding to the column names .
Below is the XML file that is produced by the bean. If the file already exists, it is overwritten:
[View full width]<?xml version="1.0"?> <dataset> <row> <itemname>My Special Headline</itemname> <itemtext>This is the text from the database. This is an important article. blah blah blah. </itemtext> </row> </dataset> <dataset> <row> <itemname>Some Other Title</itemname> <itemtext>Another bit of text. This could go on for a while. Yadda yadda yadda. </itemtext> </row> </dataset>
One thing to note about the above XML file is that it has been reformatted here; when the bean writes out the file, it will be all on one line. You can add a line break, but it is not necessary and may make it more difficult to parse. Unless humans are going to read your XML file, there's probably little benefit to adding breaks.
A good reason to write out your data to XML in this manner is so that you can pass it into another application, a Flash client, a WAP client, or transform it using XSLT.
Note
If you are very interested in this kind of flexibility, ColdFusion has made working with XML much easier with CFMX's <cfxml> tag. But XML parsing is also native to the JDK 1.4, and you can find numerous extensions for XML to use in conjunction with Java. One such application that is still rather new but popular is Cocoon. Cocoon, XML parsers, XSL transformers , and many other fine applications are available for download from http://xml.apache.org.
Top |