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 4 of 7

 

Using applets instead of HTML GET forms

Next I'll show you how to use the showDocument method of the AppletContext to submit URL-encoded data to server-side form processing pages such as JSPs, ASPs, or servlets. In the process you'll trade the limited selection of GUI controls available from HTML forms for the richer set present in Java applets. Java offers numerous controls for getting input and displaying search results, and you can use InputVerifier to ensure form data is valid. Here is a short list of available GUI controls:

  • JTable
  • JTree
  • JPopupMenu
  • JSlider
  • JTabbedPane
  • JSpiltPanes
  • JSpinner
  • JDialog
  • JFormatted fields

Another advantage of using applets in place of HTML forms is that one applet can contain many separate forms, each linked to a different server-side script. This makes it easier to preserve the state of a transaction across multiple forms and the user does not have to worry about about what will happen if he or she presses the Back button.

As with an HTML form, each applet form can have a Submit button (JButton). In a typical web form, you would specify the action, method, target for the form, and provide parameter validation code for processing the onSubmit event. The parameter validation code would usually be a JavaScript function, possibly built using a library like JQuery. The browser would then do the work of retrieving the form values and encoding them in the URL before dispatching to the web server for processing.

Applets do require a little more work than that. As with an HTML implementation, you need to validate form values before sending the form to the server. The applet then uses the URLEncoder class to replace any "unsafe" characters (any that aren't valid in URLS) using an encoding scheme like UTF-8. URLEncoder leaves the alphanumeric characters unchanged, as well as other safe characters such as dots (.), commas (,), en-dashes (-), asterisks (*), and underscores (_). Spaces are converted to plus signs (+) and all other characters are converted to a 3-byte strings beginning with a percentage sign (%) and ending with two hexadecimal digits.

Once all the parameters are encoded they can be appended to the URL using the question-mark and ampersand (? and &) format expected by the web server. Listing 5 shows an example of an applet method that invokes a JSP to add a customer record to a database.

Listing 5. Client side code to process adding a customer

/**
 *
 * Send the add request to the server
 *
 * @param evt
 */
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        try{
            String id = URLEncoder.encode(idField.getText(), "UTF-8");
            String lastName = URLEncoder.encode(lastNameField.getText(), "UTF-8");
            String firstName = URLEncoder.encode(firstNameField.getText(), "UTF-8");
            String addressLine1 = URLEncoder.encode(addressLine1Field.getText(), "UTF-8");
            String addressLine2 = URLEncoder.encode(addressLine2Field.getText(), "UTF-8");
            String city = URLEncoder.encode(cityField.getText(), "UTF-8");
            String state = URLEncoder.encode((String)stateCombo.getSelectedItem(), "UTF-8");
            String zip = URLEncoder.encode(zipField.getText(), "UTF-8");
            String phone = URLEncoder.encode(phoneField.getText(), "UTF-8");

            URL link = new URL(getCodeBase()+"addCustomer.jsp?"+
                "ID="+id+"&" +
                "lastName="+lastName+"&" +
                "firstName="+firstName+"&" +
                "addressLine1="+addressLine1+"&" +
                "addressLine2="+addressLine2+"&" +
                "city="+city+"&" +
                "state="+state+"&" +
                "zip="+zip+"&" +
                "phone="+phone);

            setMessageLabel("Processing request ...");
            getAppletContext().showDocument(link,"AppletOutput");

        }
        catch(UnsupportedEncodingException | MalformedURLException ex)
        {
          setMessageLabel("Unable to process request");
        }

    }


Listing 6 shows the JSP that processes the request.

Listing 6. Server side code to process adding a customer

-----------------------------------------------------------------------------------------------------

<%--
    Document   : addCustomer
    Created on : Feb 25, 2013, 3:52:41 PM
    Author     : Mark Pendergast
--%>

<%@page contentType="text/html" target="_blank" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Add Customer</title>
    </head>
    <body>
 <script>
      <%
         int count = 0;
         try{
            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 add = con.prepareStatement("Insert Into Customers Values (?,?,?,?,?,?,?,?,?)");
            add.setString(1, request.getParameter("ID"));
            add.setString(2, request.getParameter("firstName"));
            add.setString(3, request.getParameter("lastName"));
            add.setString(4, request.getParameter("addressLine1"));
            add.setString(5, request.getParameter("addressLine2"));
            add.setString(6, request.getParameter("city"));
            add.setString(7, request.getParameter("state"));
            add.setString(8, request.getParameter("zip"));
            add.setString(9, request.getParameter("phone"));
            count  = add.executeUpdate();

            add.close();
            con.close();
            %>
             window.parent.document.UrlEncoder.setMessageLabel(<%= count+" " %>+" records added");
            <%
         }
         catch(Exception ex)
         {
            String msg = "Unable to add record, error : "+ex.getMessage();
             %>
              window.parent.document.UrlEncoder.setMessageLabel("<%= msg%>" );
             <%
         }


      %>

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

The resulting form is displayed in Figure 2. Each field of the form has an instance of an InputVerifier to ensure proper data entry. The code for the Add button just needs to access each value, encode them all in UTF-8 format, then build the URL. A question-mark separates the JSP address from the parameter list and an ampersand separates the parameters. In this example the applet and JSP files reside in the same directory on the same server, so the value returned by getCodeBase() is used to designate the location. The showDocument() call also specifies a target frame within the web page called AppletOutput. All output of AddCustomer.jsp will be directed there.

Figure 2.Add Customer form (click to enlarge)

This technique works well to get data from the applet to the web server; but what about going in the other direction? There are two easy ways for the web server to push data back to the applet. The first is by generating output that includes JavaScript calls to methods in the applet, the second is by sending data from applet to servlet and back again using streams. We'll look at both.

  • Print
  • Feedback

Resources