Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

When to use applets instead of HTML forms: Three easy techniques

Using applets for web page menus and database interactions

  • Print
  • Feedback

Page 5 of 7

Using JavaScript to pass data from web server to applet

JavaScript has the capability of calling public methods in your applet. First, make sure that you specify an ID for the applet when you deploy it. As shown in Listing 7, I’ve set the Applet’s id to URLEncoder. To call an applet's methods from JavaScript, just preface it with document.AppletID, for example:

document.URLEncoder.methodName(parameters…)

Figure 3 depicts the complete sequence:

Figure 3. Applet to JSP and Back Data Flow (click to enlarge)

The sequence works as follows:

  1. The applet is deployed from an HTML page that contains an IFRAME for the applet’s output, as shown in Listing 7.
  2. The applet retrieves and encodes all the user input using URLEncoder.
  3. The complete link is built and issued using the showDocument method of the AppletContext, where an internal frame is specified as the target (see Listing 8).
  4. The web server receives the request and generates output that is sent back to the browser for display in the internal frame (see Listing 9).
  5. The output contains JavaScript-to-applet method calls that pass the data to the applet (see Listing 10).

In the following HTML code, the applet is given an ID of URLEncoder and an internal frame with a name of AppletOutput is added as a place to receive the JSP page results. These results consist of JavaScript calls to the applet’s methods; the frame is hidden because the results have nothing that user needs to see.

Listing 7. HTML page holding the applet

<%@page contentType="text/html" target="_blank" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>URL Encoding Demo</title>
        <script src="http://www.java.com/js/deployJava.js"></script>
    </head>
    <body>
       <table>
            <tr>
            <td>
              <script>
               var attributes = {id: "URLEncoder",
                      code: "applets.DatabaseApplet.class",
                      archive: "Applet.jar",
                      width:"800", height:"400" };
               var parameters = {param1:16, param2:22};
               var version = '1.6';
               deployJava.runApplet(attributes, parameters, version);

           </script>
             </td>
            </tr>
            <tr>
            <td>
             <iframe name="AppletOutput" width="700" height="25" hidden="true" /></IFRAME>
            </td>
         </tr>
         </table>

    </body>
</html>

The findCustomer method in Listing 8 retrieves the last name entered by the user, encodes it with UTF-8, and then invokes the findCustomer.jsp page with a target frame of AppletOutput. AppletOutput will receive the results from the findCustomer.jsp, which consists of calls to the addToResultTable and setMessageLabel methods. The argument sent to AddToResultTable is composed of a comma-delimited string containing the data for one Customer record. addToResultTable splits the string, then adds it to the JTable for the user to see.

Listing 8. Processing the Find Customer button and JavaScript callback methods

/**
 *
 *  Find customers based on partial last name entered by the user
 * @param evt
 */
    private void findCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {
    try{
      String lastName = URLEncoder.encode(searchField.getText(), "UTF-8");
      URL link = new URL(getCodeBase()+"findCustomer.jsp?"+ "lastName="+lastName);
      clearResults();
      setMessageLabel("Processing request ...");
      getAppletContext().showDocument(link,"AppletOutput");
    }
    catch(UnsupportedEncodingException | MalformedURLException ex)
    {
      setMessageLabel("Error processing request");
    }
   }

    /**
     * add a row to the result table,  columns are separated by commas
     * @param row row to be added, csv format
     */
    public void addToResultTable(String row)
    {
      DefaultTableModel tm = (DefaultTableModel)resultsTable.getModel();
      Object[] data = row.split(","); // split the fields
      if(data.length <= tm.getColumnCount()) // make sure there aren't too many columns
          tm.addRow(data);
    }
/**
 * setMessageLabel
 *
 * changes the text in the message label at the bottom of the applet.
 *
 * @param msg String to be placed in the message label
 */
    public void setMessageLabel(String msg)
    {
      messageLabel.setText(msg);
    }

In Listing 9, findCustomer.jsp connects to a MS SQLServer database and issues a SQL Select statement to retrieve the desired records. As it processes the ResultSet, it builds comma-delimited strings containing the customer data. These strings are then embedded into JavaScript calls to the applet's addToResultTable method. Calls to the applet setMessageLabel method are also added to report the total number of records found and any exceptions. Listing 10 shows the output of this JSP.

Listing 9. Searching the Customer table for matching records

<%@page contentType="text/html" target="_blank" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@page import="java.sql.*"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Find Customer</title>
    </head>
    <body>
     <script>
      <%
         int count = 0;
         try{
            String lastName = request.getParameter("lastName");
            if(lastName == null)
                lastName = "";  // default to all

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  // load the driver
            Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=Customer;user=AppletTest;password=AppletTest;");
            PreparedStatement find = con.prepareStatement("select * from Customers where Last_Name like ?");
            find.setString(1, lastName+"%");
            ResultSet rs = find.executeQuery();
            while(rs.next())
            {
              String row = "'"+rs.getString(1)+","+rs.getString(2)+","+rs.getString(3)+","+rs.getString(4) +
                        ","+rs.getString(5) +","+rs.getString(6) +","+rs.getString(7) +","+rs.getString(8) +","+rs.getString(9)+"'";
             %>
            window.parent.document.URLEncoder.addToResultTable(<%= row %>);
             <%
             count++;
            }
            rs.close();
            find.close();
            con.close();
            %>
             window.parent.document.URLEncoder.setMessageLabel(<%= count+" " %>+" records found");
            <%
         }
         catch(Exception ex)
         {
            String msg = "Unable to perform search, error : "+ex.getMessage();
             %>
              window.parent.document.URLEncoder.setMessageLabel("<%= msg%>" );
             <%
         }

      %>
     </script>
    </body>
</html>

Listing 10. Output of findCustmer.jsp

<!DOCTYPE html>

<html>
  <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Find Customer</title>
  </head>
  <body>
   <script>

    window.parent.document.URLEncoder.addToResultTable('1,Jane,Doe,123 N Main,Apt 303,Cleveland,OH ,12345,111-222-4444');
    window.parent.document.URLEncoder.addToResultTable('3,Hank,Armstrong,3434 Maple Ave,Suite A,Tampa,FL,44444,333-333-3333');
    window.parent.document.URLEncoder.addToResultTable('4,Sally,Fields,123 South 4th Place,Penthouse,HollyWood,CA - California,33333-3333,(222) 222-2222');
    window.parent.document.URLEncoder.addToResultTable('5,Holmes,Karen,123 Sunset Blvd,Suite 444,Los Angeles,CA,44444-4444,(222) 222-2222');

    window.parent.document.URLEncoder.setMessageLabel(4 +" records found");

  </script>
 </body>
 </html>

Note that because this output is placed into an IFrame and the applet is contained in the parent of the IFrame, the call to the applet’s methods must be prefaced with window.parent.

Figure 4 shows the returned results from a customer search.

Figure 4. A search panel displaying results passed from JavaScript (click to enlarge)

With this technique we can contain an entire application in one applet. Applet controls trigger server-side JSP pages which access the database and return results via JavaScript method calls. The applet shown in Figure 4 consists of a JTabbedPane and its included forms. The Customer Search tab has a JTable to display the results. The user fills in all or part of a last name and presses the Find button. The results are displayed back into the JTable without leaving the current web page. Users can sort and resize the columns of the JTable. Other tabs have forms for adding and updating customer records. The entire application is contained in two NetBeans projects (one for the applet, the other for the web application) in the URLEncoding folder of the attached code. Note that this application does not require any special privileges and does not need to be signed.

  • Print
  • Feedback

Resources