Bringing It All Together
Next is the JSP that will bring everything together. This JSP will connect to a database and execute a statement that will produce a ResultSet. After that, the ResultSet will be passed into the newly created RStoXML and used to obtain a JDOM representation. This will then be transformed with a stylesheet, and the results output.
The TableSort.xsl stylesheet will create an HTML table whose label cells are links. Each of these links will provide the column number in the query string, so that when the string is followed, the JSP will obtain this parameter from the URL. Once obtained, that value will be passed into the stylesheet to result in the appropriate sort.
After parsing the import statements, DBtoXML.jsp parses the query string to find the column number to sort on. If this parse results in an error, the default defined in the JSP will be used:
<% // 1. get parameters from url int sort_by; try{ sort_by = Integer.parseInt(request.getParameter("sort")); } catch(NumberFormatException e){ //if invalid or nonexistent parameter, sort by RCD_lname sort_by = 1; }
The page then initializes the variables that will be used throughout the rest of the page. These variables include those for database processing, such as the query statement and the XSLT stylesheet filename.
After this, the page will connect to the database, execute the SQL statement, return a ResultSet, and release the resources used. These statements have been explained previously, and will not be re-explained here.
After the ResultSet has been obtained, the process of conversion to a JDOM representation is started through the creation of an RStoXML object:
// create a resultsetbuilder to transform resultset to XML RStoXML rsb = new RStoXML(rs, "ROOT", "RECORD");
Two constructors exist for RStoXML. One uses all the defaults of the class, and therefore only requires the ResultSet parameter. The other, shown here, takes a ResultSet and two Strings as parameters. The first String parameter sets the root element name of the resulting JDOM representation, and the other sets the name of the elements that will each represent one record:
//create the XML from resultset org.jdom.Document jdomdoc = rsb.build(); rs = null;
The build() method is then invoked upon the object that will cause the creation of the JDOM representation, and the resources used in the ResultSet are released.
If any properties are to be set, such as setAllAttribute(), the setter methods must be called before the build() method is invoked. Otherwise, all the class defaults are used.
Now that the JDOM representation is available, it's time to create the Transformer object to do the transformation. This Transformer is created with the stylesheet previously defined by the variable xsl:
//create transformer Transformer transformer = TransformerFactory.newInstance() .newTransformer(new StreamSource(xsl));
With the help of the newly created Transformer, the two parameters that exist at the root level of the XSL stylesheet are set as shown below. The first is the column number that the resulting table will be sorted on, and the second is the name of the page that the linked table labels should be directed to. The presence of this parameter enables the stylesheet to be completely generic and not bound to any dataset, column names, or page names.
transformer.setParameter("Sort", new Integer(sort_by)); transformer.setParameter("Page", "DBtoXML.jsp");
With the parameters set, the stylesheet is ready to transform the JDOM representation. Before this occurs, a JDOMResult object is created to hold the results of the transformation. It is now time to transform() the JDOM representation of the ResultSet with the stylesheet using the Transformer object. Again, we release the resources used by the jdomdoc source object after it is no longer useful:
JDOMResult jdomresults = new JDOMResult(); transformer.transform(new JDOMSource(jdomdoc), jdomresults); jdomdoc = null;
The results of the transformation are now in jdomresults and need to be output. An easy way of doing this is through the use of the XMLOutputter class found in the org.jdom.output package. This class will format the JDOM document into a stream through which it can be output to the user through the output of the JSP. The Document of the transformation results are obtained and output:
//create outputter to output results XMLOutputter output = new XMLOutputter(" ", true); //output the results Document docResults = jdomresults.getDocument(); output.output(docResults, out);
Notice that the constructor used here for XMLOutputter takes two parameters. These parameters determine the indentation, and whether new lines will be included in the output. Through the use of these parameters, the tidiness of the output HTML can be altered. The settings chosen here will cause the output HTML to be formatted in a readable form.
After handling some possible exceptions that might occur, the page is complete. DBtoXML.jsp can be found in its entirety in Listing 11.5.
Listing 11.5 Complete DBtoXML.jsp File
<%@page import = "java.sql.*, org.jdom.*, org.jdom.output.*, javax.xml.transform.*, javax.xml.transform.stream.*, org.jdom.transform.*, xmlbook.chapter11.*" %> <html> <head><title>DB to XML and XSL</title></head> <body> <div> <% // 1. get parameters from url int sort_by; try{ sort_by = Integer.parseInt(request.getParameter("sort")); } catch(NumberFormatException e){ //if invalid or nonexistent parameter, sort by RCD_lname sort_by = 1; } // 2. Initialize other variables String final_status = ""; String db_query = "select RCD_lname, RCD_fname, "; db_query +="DATE_FORMAT(RCD_dob, '%Y-%m-%d') as RCD_dob , "; db_query +="RCD_clinic, RCD_color from reportclientdata"; String db_location = "jdbc:mysql://localhost/xmlbook"; String db_driver = "org.gjt.mm.mysql.Driver"; String stylesheet = "TableSort.xsl"; // 3. Make a database connection Connection db_connection = null; Statement db_statement = null; ResultSet rs = null; try{ Class.forName(db_driver); db_connection = DriverManager.getConnection(db_location); db_statement = db_connection.createStatement(); //get a resultset rs = db_statement.executeQuery(db_query); } catch (ClassNotFoundException e){ final_status = "Error: Unable to create database drive class."; final_status += " <br />" + e.toString(); } catch(SQLException e){ final_status = "Error: Unable to make database connection"; final_status += "or execute statement."; final_status += " <br />" + e.toString(); } finally { /* We must close the database connection now */ try { if (db_connection != null) { db_connection.close(); } } catch (SQLException e) { final_status = "Error: Unable to close database connection."; final_status += " <br />" + e.toString(); } } try{ // create a resultsetbuilder to transform resultset to XML RStoXML rsxml = new RStoXML(rs, "ROOT", "RECORD"); //create the XML from recordset org.jdom.Document jdomdoc = rsxml.build(); rs = null; //get the stylesheet String path = request.getServletPath(); path = path.substring(0,path.indexOf("DBtoXML.jsp")) ; String xsl = application.getRealPath(path + stylesheet); //create transformer Transformer transformer = TransformerFactory.newInstance() .newTransformer(new StreamSource(xsl)); transformer.setParameter("Sort", new Integer(sort_by)); transformer.setParameter("Page", "DBtoXML.jsp"); //transformer.setParameter("NFilter", new Integer(nFilter_by)); //transformer.setParameter("CFilter", cFilter_by); JDOMResult jdomresults = new JDOMResult(); transformer.transform(new JDOMSource(jdomdoc), jdomresults); jdomdoc = null; //create outputter to output results XMLOutputter output = new XMLOutputter(" ", true); //output the results Document docResults = jdomresults.getDocument(); output.output(docResults, out); } catch (TransformerFactoryConfigurationError e) { final_status = "Error: Unable to create factory to transform "; final_status = "XSL and XML."; final_status += "<br />" + e.toString(); } catch (TransformerException e) { final_status = "Error: Unable to transform XSL and XML."; final_status += "<br />" + e.toString(); } catch (JDOMException e) { final_status = "Error: Unable to create XML from database query."; final_status += "<br />" + e.toString(); } if(final_status != "") out.print("<br><font color=\"red\"><H2>" + final_status + "</H2></font>"); %> </div> </body> </html>