While running a web server with servlet support, compile and run the following example to see how the HTMLFormConverter works:
import java.awt.Color; import java.io.IOException; import java.io.PrintWriter; import java.sql.DriverManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Enumeration; import java.util.Hashtable; import javax.servlet.*; import javax.servlet.http.*; import com.ibm.as400.util.html.GridLayoutFormPanel; import com.ibm.as400.util.html.HTMLConstants; import com.ibm.as400.util.html.HTMLForm; import com.ibm.as400.util.html.HTMLTable; import com.ibm.as400.util.html.HTMLTableCaption; import com.ibm.as400.util.html.HTMLText; import com.ibm.as400.util.html.LabelFormElement; import com.ibm.as400.util.html.LineLayoutFormPanel; import com.ibm.as400.util.html.SubmitFormInput; import com.ibm.as400.util.html.TextFormInput; import com.ibm.as400.util.servlet.HTMLFormConverter; import com.ibm.as400.util.servlet.SQLResultSetRowData; import com.ibm.as400.access.AS400; import com.ibm.as400.access.AS400JDBCDriver; /** * An example of using the HTMLFormConverter class in a servlet. */ public class HTMLFormConverterExample extends HttpServlet { private String userId_ = "myUserId"; private String password_ = "myPwd"; private AS400 system_; private Connection databaseConnection_; // Perform cleanup before returning to the main HTML form. public void cleanup() { try { // Close the database connection. if (databaseConnection_ != null) { databaseConnection_.close(); databaseConnection_ = null; } } catch (Exception e) { e.printStackTrace (); } } // Convert the row data to formatted HTML. private HTMLTable[] convertRowData(SQLResultSetRowData rowData) { try { // Create the converter, which will generate HTML from // the result set that comes back from the database query. HTMLFormConverter converter = new HTMLFormConverter(); // Set the form attributes. converter.setBorderWidth(3); converter.setCellPadding(2); converter.setCellSpacing(4); // Convert the row data to HTML. HTMLTable[] htmlTable = converter.convertToForms(rowData); return htmlTable; } catch (Exception e) { e.printStackTrace (); return null; } } // Return the response to the client. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(showHtmlMain()); out.close(); } // Handle the data posted to the form. public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SQLResultSetRowData rowData = new SQLResultSetRowData(); HTMLTable[] htmlTable = null; // Get the current session object or create one if needed. HttpSession session = request.getSession(true); ServletOutputStream out = response.getOutputStream(); response.setContentType("text/html"); Hashtable parameters = getRequestParameters (request); // Retrieve the row data and HTML table values for this session. rowData = (SQLResultSetRowData) session.getValue("sessionRowData"); htmlTable = (HTMLTable[]) session.getValue("sessionHtmlTable"); // if this is the first time through, show first record if (parameters.containsKey("getRecords")) { rowData = getAllRecords(parameters, out); if (rowData != null) { // Set the row data value for this session. session.putValue("sessionRowData", rowData); // Position to the first record. rowData.first(); // Convert the row data to formatted HTML. htmlTable = convertRowData(rowData); if (htmlTable != null) { rowData.first(); session.putValue("sessionHtmlTable", htmlTable); out.println(showHtmlForRecord(htmlTable, 0)); } } } // If the "Return To Main" button was pressed, // go back to the main HTML form else if (parameters.containsKey("returnToMain")) { session.invalidate(); cleanup(); out.println(showHtmlMain()); } // if the "First" button was pressed, show the first record else if (parameters.containsKey("getFirstRecord")) { rowData.first(); out.println(showHtmlForRecord(htmlTable, 0)); } // if the "Previous" button was pressed, show the previous record else if (parameters.containsKey("getPreviousRecord")) { if (!rowData.previous()) { rowData.first(); } out.println(showHtmlForRecord(htmlTable, rowData.getCurrentPosition())); } // if the "Next" button was pressed, show the next record else if (parameters.containsKey("getNextRecord")) { if (!rowData.next()) { rowData.last(); } out.println(showHtmlForRecord(htmlTable, rowData.getCurrentPosition())); } // if the "Last" button was pressed, show the last record else if (parameters.containsKey("getLastRecord")) { rowData.last(); out.println(showHtmlForRecord(htmlTable, rowData.getCurrentPosition())); } // if none of the above, there must have been an error else { out.println(showHtmlForError("Internal error occurred. Unexpected parameters.")); } // Save the row data value for this session so the current position // is updated in the object associated with this session. session.putValue("sessionRowData", rowData); // Close the output stream out.close(); } // Get all the records from the file input by the user. private SQLResultSetRowData getAllRecords(Hashtable parameters, ServletOutputStream out) throws IOException { SQLResultSetRowData records = null; try { // Get the system, library and file name from the parameter list. String sys = ((String) parameters.get("System")).toUpperCase(); String lib = ((String) parameters.get("Library")).toUpperCase(); String file = ((String) parameters.get("File")).toUpperCase(); if ((sys == null || sys.equals("")) || (lib == null || lib.equals("")) || (file == null || file.equals(""))) { out.println(showHtmlForError("Invalid system, file or library name.")); } else { // Get the connection to the server. getDatabaseConnection (sys, out); if (databaseConnection_ != null) { Statement sqlStatement = databaseConnection_.createStatement(); // Query the database to get the result set. String query = "SELECT * FROM " + lib + "." + file; ResultSet rs = sqlStatement.executeQuery (query); boolean rsHasRows = rs.next(); // position cursor to first row // Show error message if the file contains no record; // otherwise, set row data to result set data. if (!rsHasRows) { out.println(showHtmlForError("No records in the file.")); } else { records = new SQLResultSetRowData (rs); } // Don't close the Statement before we're done using // the ResultSet or bad things may happen. sqlStatement.close(); } } } catch (Exception e) { e.printStackTrace (); out.println(showHtmlForError(e.toString())); } return records; } // Establish a database connection. private void getDatabaseConnection (String sysName, ServletOutputStream out) throws IOException { if (databaseConnection_ == null) { try { databaseConnection_ = DriverManager.getConnection("jdbc:as400://sysName,userId_,password_ ); } catch (Exception e) { e.printStackTrace (); out.println(showHtmlForError(e.toString())); } } } // Gets the parameters from an HTTP servlet request. private static Hashtable getRequestParameters (HttpServletRequest request) { Hashtable parameters = new Hashtable (); Enumeration enum = request.getParameterNames(); while (enum.hasMoreElements()) { String key = (String) enum.nextElement(); String value = request.getParameter (key); parameters.put (key, value); } return parameters; } // Get the servlet information. public String getServletInfo() { return "HTMLFormConverterExample"; } // Perform initialization steps. public void init(ServletConfig config) { try { super.init(config); // Register the JDBC driver try { DriverManager.registerDriver(new AS400JDBCDriver()); } catch (Exception e) { System.out.println("JDBC Driver not found"); } } catch (Exception e) { e.printStackTrace(); } } // Set the page header info. private String showHeader(String title) { StringBuffer page = new StringBuffer(); page.append("<html><head><title>" + title + "</title>"); page.append("</head><body bgcolor=\"blanchedalmond\">"); return page.toString (); } // Show the HTML page with the appropriate error information. private String showHtmlForError(String message) { String title = "Error"; StringBuffer page = new StringBuffer(); page.append (showHeader (title)); try { // Create the HTML Form object HTMLForm errorForm = new HTMLForm("HTMLFormConverterExample"); // Set up so that doPost() gets called when the form is submitted. errorForm.setMethod(HTMLForm.METHOD_POST); // Create a single-column panel to which the // HTML elements will be added. GridLayoutFormPanel grid = new GridLayoutFormPanel(); // Create the text element for the error and add it to the panel. HTMLText text = new HTMLText(message); text.setBold(true); text.setColor(Color.red); grid.addElement(text); // Create the button to return to main and add it to the panel. grid.addElement(new SubmitFormInput("returnToMain", "Return to Main")); // Add the panel to the HTML form. errorForm.addElement(grid); page.append(errorForm.toString()); } catch (Exception e) { e.printStackTrace (); } page.append("</body></html>"); return page.toString(); } // Show the HTML form for an individual record. private String showHtmlForRecord(HTMLTable[] htmlTable, int position) { String title = "HTMLFormConverter Example"; StringBuffer page = new StringBuffer(); page.append (showHeader (title)); page.append("<h1>" + title + "</h1>"); try { // Create the HTML Form object HTMLForm recForm = new HTMLForm("HTMLFormConverterExample"); // Set up so that doPost() gets called when the form is submitted. recForm.setMethod(HTMLForm.METHOD_POST); // Set up a single-column panel layout, within which to arrange // the generated HTML elements. GridLayoutFormPanel grid = new GridLayoutFormPanel(); // Create and add a table caption that keeps track // of the current record. HTMLText recNumText = new HTMLText("Record number: " + (position + 1)); recNumText.setBold(true); grid.addElement(recNumText); // Set up a two-column panel layout, within which to arrange // the table and text to comment on the converter output. GridLayoutFormPanel tableGrid = new GridLayoutFormPanel(2); tableGrid.addElement(htmlTable[position]); HTMLText comment = new HTMLText(" <---- Output from the HTMLFormConverter class"); comment.setBold(true); comment.setColor(Color.blue); tableGrid.addElement(comment); // Add the table line to the panel. grid.addElement(tableGrid); // Set up a single-row panel layout, within which to arrange // the buttons for moving through the record list. LineLayoutFormPanel buttonLine = new LineLayoutFormPanel(); buttonLine.addElement(new SubmitFormInput("getFirstRecord", "First")); buttonLine.addElement(new SubmitFormInput("getPreviousRecord", "Previous")); buttonLine.addElement(new SubmitFormInput("getNextRecord", "Next")); buttonLine.addElement(new SubmitFormInput("getLastRecord", "Last")); // Set up another single-row panel layout for the // Return To Main button. LineLayoutFormPanel returnToMainLine = new LineLayoutFormPanel(); returnToMainLine.addElement(new SubmitFormInput("returnToMain", "Return to Main")); // Add the lines containing the buttons to the grid panel. grid.addElement(buttonLine); grid.addElement(returnToMainLine); // Add the panel to the form. recForm.addElement(grid); // Add the form to the HTML page. page.append(recForm.toString()); } catch (Exception e) { e.printStackTrace (); } page.append("</body></html>"); return page.toString(); } // Show the main HTML form (request input for system, file, // and library name). private String showHtmlMain() { String title = "HTMLFormConverter Example"; StringBuffer page = new StringBuffer(); page.append (showHeader (title)); page.append("<h1>" + title + "</h1>"); // Create the HTML Form object HTMLForm mainForm = new HTMLForm("HTMLFormConverterExample"); try { // Set up so that doPost() gets called when the form is submitted. mainForm.setMethod(HTMLForm.METHOD_POST); // Add a brief description to the form. HTMLText desc = new HTMLText("<P>This example uses the HTMLFormConverter class " + "to convert data retrieved from a server " + "file. The converter produces an array of HTML " + "tables. Each entry in the array is a record from " + "the file. " + "Records are displayed one at a time, " + "giving you buttons to move forward or backward " + "through the list of records.</P>"); mainForm.addElement(desc); // Add instructions to the form. HTMLText instr = new HTMLText("<P>Please input the name of the server, " + "and the file and library name for the file you " + "wish to access. Then push the Show Records " + "button to continue.</P>"); mainForm.addElement(instr); // Create a grid layout panel and add the system, file // and library input fields. GridLayoutFormPanel panel = new GridLayoutFormPanel(2); LabelFormElement sysPrompt = new LabelFormElement("Server: "); TextFormInput system = new TextFormInput("System"); system.setSize(10); LabelFormElement filePrompt = new LabelFormElement("File name: "); TextFormInput file = new TextFormInput("File"); file.setSize(10); LabelFormElement libPrompt = new LabelFormElement("Library name: "); TextFormInput library = new TextFormInput("Library"); library.setSize(10); panel.addElement(sysPrompt); panel.addElement(system); panel.addElement(filePrompt); panel.addElement(file); panel.addElement(libPrompt); panel.addElement(library); // Add the panel to the form. mainForm.addElement(panel); // Create the submit button and add it to the form. mainForm.addElement(new SubmitFormInput("getRecords", "Show Records")); } catch (Exception e) { e.printStackTrace (); } page.append(mainForm.toString()); page.append("</body></html>"); return page.toString(); } }
The HTML generated by the above example looks like this:
<table border="0"> <tr> <td><b>Record number: 1</b></td> </tr> <tr> <td><table border="0"> <tr> <td><table border="3" cellpadding="2" cellspacing="4"> <tr> <th>CUSNUM</th> <td>839283</td> </tr> <tr> <th>LSTNAM</th> <td>Jones </td> </tr> <tr> <th>INIT</th> <td>B D</td> </tr> <tr> <th>STREET</th> <td>21B NW 135 St</td> </tr> <tr> <th>CITY</th> <td>Clay </td> </tr> <tr> <th>STATE</th> <td>NY</td> </tr> <tr> <th>ZIPCOD</th> <td>13041</td> </tr> <tr> <th>CDTLMT</th> <td>400</td> </tr> <tr> <th>CHGCOD</th> <td>1</td> </tr> <tr> <th>BALDUE</th> <td>100.00</td> </tr> <tr> <th>CDTDUE</th> <td>0.00</td> </tr> </table> </td> <td><font color="#0000ff"> <b><!-- Output from the HTMLFormConverter class--> </b></font></td> </tr> </table> </td> </tr> <tr> <form> <td><input type="submit" name="getFirstRecord" value="First" /> <input type="submit" name="getPreviousRecord" value="Previous" /> <input type="submit" name="getNextRecord" value="Next" /> <input type="submit" name="getLastRecord" value="Last" /> <br /> </td> </tr> <tr> <td><input type="submit" name="returnToMain" value="Return to Main" /> <br /> </td> </tr> </table> </form>