SCOUG Logo


Next Meeting: Sat, TBD
Meeting Directions


Be a Member
Join SCOUG

Navigation:


Help with Searching

20 Most Recent Documents
Search Archives
Index by date, title, author, category.


Features:

Mr. Know-It-All
Ink
Download!










SCOUG:

Home

Email Lists

SIGs (Internet, General Interest, Programming, Network, more..)

Online Chats

Business

Past Presentations

Credits

Submissions

Contact SCOUG

Copyright SCOUG



warp expowest
Pictures from Sept. 1999

The views expressed in articles on this site are those of their authors.

warptech
SCOUG was there!


Copyright 1998-2024, Southern California OS/2 User Group. ALL RIGHTS RESERVED.

SCOUG, Warp Expo West, and Warpfest are trademarks of the Southern California OS/2 User Group. OS/2, Workplace Shell, and IBM are registered trademarks of International Business Machines Corporation. All other trademarks remain the property of their respective owners.

The Southern California OS/2 User Group
USA

SCOUG OS/2 For You - March 1998


Programming for the Net: Clientside Java

by Terry Warren

In previous articles we have seen how web-browsers interact with web-servers using the HTTP transaction protocol and how to provide user interfaces with both HTML forms controls and JavaScript. On the server side, the basics of CGI programming can be used to support client requests. In this article we will examine how the Java language can be used both for a more robust user interface and as a CGI front-end.

OS/2 Warp 4 provides a convenient platform for developing and testing Java applications since it comes with built-in Java support; the downloadable Netscape browser also contains a compatible Java runtime. Most of the sample code described in this article can be entered using the OS/2 editor, EPM, compiled and executed. Requirements are the current Netscape OS/2 browser and OS/2 JDK 1.0.2 or higher. Java application code can also be entered and tested directly in the VisualAge for Java development environment.

Additional sample programs for the topics covered in this article can be downloaded from the SCOUG programming SIG webpage (go to the download area and look for "Programming for the Net - Java" link).

Java Programming Language

Although it is not the intent of this article to be a Java progamming tutorial, a review of Java fundamentals is appropriate. The language itself is patterned after C/C++; if you are familiar with either of those languages you will have no problem reading Java code.

Java is class-based and fully object oriented. The standard class library is contained in the Java Development Kit (JDK) which also includes development tools: compiler, interpreter and applet viewer. The classes are grouped into functional categories (called "packages"); a package can be referenced within a source program using the "import" statement (somewhat similar to a C "include"). In this way, all of the package classes can be conveniently referenced.

A Java program can be created by editing (or using a suitable IDE) the source statements into a file with .java extension; the name of the file must correspond to the class being defined, EG Sample1.java.

The structure of the source is:

public class Sample1 extends ... { ...body of class file }

If the class is an extension of another class, the "extends classname" clause must be included; if omitted then the class is assumed to be an extension of Object. The body contains definitions for the class variables and methods. The source file may contain more than one class definition; however, the additional ones cannot be defined as public.

The source file can then be compiled via the Java compiler (javac). The compilation process creates one file, with .class extension, for each defined class in the source file. The .class file corresponding to the public class (in our example this would be Sample1.class) can be executed in one of two ways:

  1. If it contains a method named "main" which is defined as: public static void main(String args[]) it can be directly executed via the Java interpreter (eg, java Sample1).
  2. If it is an extension of the Applet class, then it can be referenced via HTML and invoked from a browser environment (more on this below) or the applet viewer.

If it satisfies both of the conditions, it can be executed either way although its execution environment is different.

Java also provides another type of class definition known as an interface. This is simply a list of required methods. A class can then implement this interface provided its definition includes all of the required methods. For example:

public interface myInterface { public void method1(String s); public String method2(); } and: public class myClass extends Applet implements myInterface { ... public void method1(String s) { ... } public String method2() { ... } ... }

Simple Applet

The JDK includes a class designed to be used in a browser environment: the Applet class. To create an applet, a java source file (.java extension) defining the class is coded and compiled. A simple example (Sample1.java) to display a line of text in a window is shown below:

import java.applet.*; import java.util.*; import java.awt.*; public class Sample1 extends Applet { public void init() { add (new Label("Hello World")); show(); } }

The basic requirements are:

  1. the public class defined in the source file must be an extension of the Applet class.
  2. there should be an init() method to create the UI controls (in this case simply a text label).

Note that the import statements are optional, but if not provided, then each class reference must be fully qualified such that the Applet would need to be coded as java.applet.Applet and the Label would need to be java.awt.Label.

If you have entered this code into a source file, you can compile it by using the command

javac Sample1.java which will produce the class file Sample1.class.

This type of class file can only be executed via an html file. The HTML language has an extension, the applet tag, which causes an applet to be dynamically executed from the browser (if the browser has Java support enabled). This tag has several attributes including:

code
(required) names the class file to be invoked
width, height
(optional) the default dimensions of the window in which the applet output is presented
name
(optional) a name can be associated with the applet and then used in interapplet and Javascript integration

To execute our Sample1 applet, the following HTML would suffice:

<applet code="Sample1.class" name="myApplet" height=50 width=100> </applet>

If these two lines have been entered into a source file, samp1.html, the applet can be executed in one of two ways:

  1. reference the html file in the Netscape browser; or
  2. from an OS/2 command line, enter the command: applet samp1.html
The second method utilizes the appletviewer program, included in the JDK, for providing the same java runtime environment (or at least a similar one, in terms of security, class loading and execution restrictions) that would be provided by the browser itself.

It is possible to affect the applet's execution by supplying parameters in the applet tag which can be accessed by the applet code. For example if we wanted to display a line of text defined in the HTML other than "Hello World", the HTML file could be modified to:

<applet code="Sample1.class" height=50 width=100> <param name="text1" value="Different Text"> </applet>

The init() method in the java source file can obtain the value of the parameter by using the applet's getParameter() method:

... public void init() { private String textString = "Hello World"; //default value if (getParameter("text1") != null) //use parameter textString = getParameter("text1"); // if present add(new Label(textString)); }

In this case, whatever text string is defined in the value field of the text1 parameter will be displayed; if the parameter is not defined then "Hello World" will be displayed.

Additional Applet Capabilities

Of course an applet that merely displays a line of text is not particularly impressive and the advantage of using Java is that you can easily create a more sophisticated UI which will be properly rendered in any Java-enabled browser.

As with all UI designs, there are three areas of concern - user controls definition and layout, event handling, and procedural code for processing data input/output - which we'll look at in turn.

Control definition and layout

The JDK contains a specific package (java.awt) which has classes defined for a number of typical controls (buttons, lists, text-fields, etc). In addition there are classes for specifying colors, fonts, displaying images and other graphics support. While this collection of classes is not as robust as the platform specific PM controls available in the OS/2 APIs, it does compare favorably to other browser-based alternatives such as HTML and Javascript. In addition to the awt package, the next major JDK release (1.2) will contain significant enhancements in the UI control area.

Controls are added to the applet viewing area by using its add(...) method (as seen in our simple example above). By default, controls are arranged left to right, top to bottom in the applet window. If the window is resized, they are automatically adjusted accordingly. This default behavior (which is consistent with normal HTML content rendering) is known as "flow" layout. Java provides four other types of layouts: border, card, grid and gridbag. Each layout is an example of a LayoutMangager class and provides different arrangement capabilities. To use one of the layouts, first create it and then attach it to the applet.

BorderLayout myLayout = new BorderLayout(); setLayout(myLayout); Then add controls to the layout: myLayout.add("North", new Label("this is the north")); ...

More complex arrangements can be created in which additional viewing areas (class Panel) are defined. Each Panel can have its own layoutmanager and set of controls.

In all cases, the layoutmanager itself performs placement, sizing and spacing operations based on the constraints requested when you add the controls. If none of the provided managers is suitable for your application you can create your own layoutmanager class (In VisualAge IDE, when you create an Applet, by default you are not using any of the JDK layoutmanagers.)

Event Handling

Having provided a set of UI controls, you also want to provide code to be executed when the user interacts with these controls such as "pushing" a button or selecting a listbox item. Java generates event objects for common UI events such as mouse movement, mouse buttons, keyboard keys as well as component based events such as those listed above.

In JDK 1.0, each component has built-in event handling methods. To define the event code you want, simply override the method. If the component is nested within another component, the inner one's event handler will be invoked first. If it returns "false", then the (next) outer component's handler will be invoked. Thus, if a button is defined in an Applet, the button's method will be called first and then (conditionally) the Applet's. The following sample code shows how to process either of two buttons (at the Applet level):

import java.awt.*; import java.applet.*; public class App2 extends Applet { Button b1 = new Button("Button1"); Button b2 = new Button("Button2"); ... add(b1); add(b2); ... public boolean action(Event e, Object o) { if (e.target == b1) { ... code for button1... return true; //indicate the event has been processed } if (e.target == b2) { ...code for button2 ... return true; //indicate the event has been processed } return false; //indicate the event has not been processed } } // end of applet code

In JDK1.1, event handling is completely different. A new package, awt.event, has been added. It contains classes for different categories of events. There is no implicit event notification; instead, an object must request notification by registering itself with the component producing the event. The event object it receives can be used to direct further processing. The example coded above would be:

import java.awt.*; import java.applet.*; import java.awt.event.*; public class App2 extends Applet implements ActionListener { Button b1 = new Button("Button1"); Button b2 = new Button("Button2"); ... add(b1); add(b2); b1.addActionListener(this); //add my applet to the actionevent b2.addActionListener(this); // list for the button controls ... public void actionPerformed(ActionEvent e) { if (e.getSource() == b1) { ... code for button1... } if (e.getSource() == b2) { ...code for button2 ... } } } // end of applet code

Webserver Interaction

With the additional UI capabilities provided by Java, it would be nice if the applets could be used in place of HTML forms and be able to interact with CGI programs on the webserver. This can be accomplished using the principles outlined in our earlier articles on HTTP and CGI.

The JDK java.net package contains the necessary classes; in particular, the URLConnection class can be used to establish a connection with the server, send data to it and receive output. The class handles all of the tcpip layer for you and also the majority of http layer including headers.

The mechanics of communication are as follows:

  1. First you must create a URL object: this object identifies the actual location and process to which you want to connect. There are several constructors but basically you supply a URL. For example: try { URL myUrl = new URL("http://www.website.com/cgi-bin/prog1"); ... } catch (Exception ex) { ... } (If your applet is running inside a browser, you can use the getCodeBase() method to obtain the URL object which initiated your applet. This can then be used as a base for your connection so that it will work properly from any source.)
  2. Next you would open a connection to the URL (all of the following code should be within the try..catch block): URLConnection conn = myUrl.openConnection();
  3. To send data to the process, you need to specify that output is allowed and then create an appropriate stream io object. In JDK 1.0, the printStream works; in JDK 1.1, printWriter is preferred. After writing data, the stream must be closed. Sample (1.0) code: conn.setDoOutput(true); //allow output to the connection PrintStream ps = new PrintStream(conn.getOutputStream()); ps.println(sData); //or whatever data you wish to send ps.close();
  4. An input stream, such as DataInputStream can then be opened on the connection and data can be read and processed: dis = new DataInputStream(conn.getInputStream()); ... code to read lines of input and process ... dis.close();
  5. If you need to look at headers associated with the connection, the URLConnection class contains several appropriate methods such as getHeaderField() and getHeaderFieldKey().
  6. If you are connecting to a standard CGI program, the data you send must be formatted as the request stream that would be sent via the HTML form. For example, if the form contained three user input fields, Name, Address and Phone, the form output would be: Name=John Smith&Address=11 N. Main&Phone=555-3333 So if you replace the form with a Java applet, the data you send must look like the above. One complication is that the browser will encode the data values as described before (spaces become + and special characters become %xx). Your code should do this also (it is a necessity if the value can include "&" characters). The simplest way (although not politically correct) is to use a static method of URLEncoder class, encode. So, for example, if your applet's variables for the fields were varNamme, varAddress and varPhone the data string could be constructed as: String cgiIn = "Name=" + URLEncoder.encode(varName) + "&Address=" + URLEncoder.encode(varAddress) + "&Phone=" + URLEncoder.encode(varPhone);
  7. If you are dealing with an existing CGI process, you must also do extra work in processing its output since that output consists of actual HTML; ie you must parse the HTML tags, etc to extract just the data of interest to your applet. A better approach, if feasible, is to modify the CGI program so that it produces abbreviated output that is more easily managed by the Java code if invoked by Java code (this can be designated by adding a special CGI variable that is not part of the form). Another, similar approach, is to simply have two CGI programs; one for forms and one for Java.

An added benefit of using Java applets is that they can run outside of a browser environment and still work correctly. The main constraint is that you need to supply the entire URL string to the applet (or have it "hard" coded) since the getCodeBase() method will not be able to return a valid URL object.

Browser Integration

The Netscape browser provides several features related to integration of Java applets and the browser environment (unfortunately these are mostly at the 3.x and 4.x level and so are not available in the current OS/2 version):

  1. The applet context provides access to all of the applet objects executing in the same frame. Your applet can obtain an enumeration of these objects by using: Enumeration enum = getAppletContext().getApplets(); or obtain a specific object: Applet yourApp = getAppletContext().getApplet("App2"); When you have an applet, you can access any of its (public) methods or variables directly. For example, if App2 has a method, showMessage(String msg), you could invoke it by: yourApp.showMessage("message from my app");
  2. The JavaScript environment also has access to Java Applets and their public methods and variables. There are several ways of doing this:

    Javascript code can "create" class objects by using the "new" operator as in:

    var myDate = new java.util.Date() and then reference this object's methods (in this case, myDate.getTime()).

    If an applet is defined in the HTML, Javascript can invoke the Applet's methods and variables. The applet can be referenced by name (if its applet tag included a "name" property). For example, if our sample applet defined above, Sample1, contained a public method setText(String s) to reset its text string, this method could be invoked from Javascript as:

    document.myApplet.setText("new string")

    The Java/Javascript interface also provides for controlling Netscape plugins which are implemented in Java. This is done by using the "embeds" array to access the plugin, or its name if it has one.

  3. It is also possible (although more cumbersome) for the Java applet to reference JavaScript objects. The package netscape.javascript (included in the versions of the browser which provide this support) contains the necessary class definitions. The primary class, JSObject, has methods for accessing any Javascript object. These are referenced in hierarchical fashion (just as they would be in Javascript).

    For example to access a form named docForm1 on the document, the java code would be:

    import netscape.javascript.*; public class myApplet extends Applet { ... JSObject jsWindow = JSObject.getWindow(this); //javascript window JSObject document = (JSObject) jsWindow.getMember("document"); JSObject form1 = (JSObject) document.getMember("docForm1"); ... }

Summary

There is a lot of functionality included in the Java environment for developing clientside Web applications. All of this functionality is available to OS/2 developers using the current JDK (both 1.0.2 and 1.1.4); IDE support comes from the VisualAge for Java product. The browser integration will be more complete when (and if) an updated Netscape OS/2 product is released.

In the next (and last) article we will look at how Java can be utilized on the Webserver platform.


The Southern California OS/2 User Group
P.O. Box 26904
Santa Ana, CA 92799-6904, USA

Copyright 1998 the Southern California OS/2 User Group. ALL RIGHTS RESERVED.

SCOUG is a trademark of the Southern California OS/2 User Group.
OS/2, Workplace Shell, and IBM are registered trademarks of International Business Machines Corporation.
All other trademarks remain the property of their respective owners.