ibm-information-center/dist/eclipse/plugins/i5OS.ic.rzahh_5.4.0.1/frmconex.htm

640 lines
21 KiB
HTML
Raw Normal View History

2024-04-02 14:02:31 +00:00
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en-us" xml:lang="en-us">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="security" content="public" />
<meta name="Robots" content="index,follow" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta name="DC.Type" content="reference" />
<meta name="DC.Title" content="Example: Using HTMLFormConverter" />
<meta name="abstract" content="" />
<meta name="description" content="" />
<meta name="copyright" content="(C) Copyright IBM Corporation 2006" />
<meta name="DC.Rights.Owner" content="(C) Copyright IBM Corporation 2006" />
<meta name="DC.Format" content="XHTML" />
<meta name="DC.Identifier" content="frmconex" />
<meta name="DC.Language" content="en-us" />
<!-- All rights reserved. Licensed Materials Property of IBM -->
<!-- US Government Users Restricted Rights -->
<!-- Use, duplication or disclosure restricted by -->
<!-- GSA ADP Schedule Contract with IBM Corp. -->
<link rel="stylesheet" type="text/css" href="./ibmdita.css" />
<link rel="stylesheet" type="text/css" href="./ic.css" />
<title>Example: Using HTMLFormConverter</title>
</head>
<body id="frmconex"><a name="frmconex"><!-- --></a>
<!-- Java sync-link --><script language="Javascript" src="../rzahg/synch.js" type="text/javascript"></script>
<h1 class="topictitle1">Example: Using HTMLFormConverter</h1>
<div><p></p>
<div class="section"><p>While running a web server with servlet support, compile and run
the following example to see how the HTMLFormConverter works: </p>
<pre>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("&lt;html&gt;&lt;head&gt;&lt;title&gt;" + title + "&lt;/title&gt;");
page.append("&lt;/head&gt;&lt;body bgcolor=\"blanchedalmond\"&gt;");
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("&lt;/body&gt;&lt;/html&gt;");
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("&lt;h1&gt;" + title + "&lt;/h1&gt;");
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(" &lt;---- 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("&lt;/body&gt;&lt;/html&gt;");
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("&lt;h1&gt;" + title + "&lt;/h1&gt;");
// 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("&lt;P&gt;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.&lt;/P&gt;");
mainForm.addElement(desc);
// Add instructions to the form.
HTMLText instr =
new HTMLText("&lt;P&gt;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.&lt;/P&gt;");
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("&lt;/body&gt;&lt;/html&gt;");
return page.toString();
}
}</pre>
<p>The HTML generated by the above example looks like this:</p>
<pre>&lt;table border="0"&gt;
&lt;tr&gt;
&lt;td&gt;&lt;b&gt;Record number: 1&lt;/b&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;table border="0"&gt;
&lt;tr&gt;
&lt;td&gt;&lt;table border="3" cellpadding="2" cellspacing="4"&gt;
&lt;tr&gt;
&lt;th&gt;CUSNUM&lt;/th&gt;
&lt;td&gt;839283&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;LSTNAM&lt;/th&gt;
&lt;td&gt;Jones &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;INIT&lt;/th&gt;
&lt;td&gt;B D&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;STREET&lt;/th&gt;
&lt;td&gt;21B NW 135 St&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;CITY&lt;/th&gt;
&lt;td&gt;Clay &lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;STATE&lt;/th&gt;
&lt;td&gt;NY&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;ZIPCOD&lt;/th&gt;
&lt;td&gt;13041&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;CDTLMT&lt;/th&gt;
&lt;td&gt;400&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;CHGCOD&lt;/th&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;BALDUE&lt;/th&gt;
&lt;td&gt;100.00&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;th&gt;CDTDUE&lt;/th&gt;
&lt;td&gt;0.00&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/td&gt;
&lt;td&gt;&lt;font color="#0000ff"&gt; &lt;b&gt;&lt;!-- Output from the HTMLFormConverter class--&gt;
&lt;/b&gt;&lt;/font&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;form&gt;
&lt;td&gt;&lt;input type="submit" name="getFirstRecord" value="First" /&gt;
&lt;input type="submit" name="getPreviousRecord" value="Previous" /&gt;
&lt;input type="submit" name="getNextRecord" value="Next" /&gt;
&lt;input type="submit" name="getLastRecord" value="Last" /&gt;
&lt;br /&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;input type="submit" name="returnToMain" value="Return to Main" /&gt;
&lt;br /&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/form&gt;</pre>
</div>
</div>
</body>
</html>