Java Applets, - Can You Play Together?

By Sowmya Kannan, February 2010  

Is your web application platform based on technology? Would you like to leverage the Java platform's ubiquity to provide a rich user experience when users visit your web site? You can develop secure rich Internet applications (RIAs - applets and Java Web Start applications) by using the Java or the JavaFX language. Java client technology integrates seamlessly with technology. In this article, we will explore various mechanisms by which Java applets can interact with web pages.

View Applet - Interaction

Here is a short screencast (about two and half minutes) that shows how an applet can interact with an page. View this screencast to better understand the context for the rest of this article.

Deploying an Applet in an Page

Use the Deployment Toolkit script to deploy an applet in an page as shown in the following code snippet:


    <script src=""></script>
        var attributes = { width:675, height:300} ;
        var parameters = { jnlp_href: 'applet/map-applet.jnlp'};
        deployJava.runApplet(attributes, parameters, '1.6');
</body>, We Need To Talk

An applet (running on the client) can interact with an page (running on the server) by using the following mechanisms:

  • Cookies – An applet can set and retrieve cookies set by pages.
  • Updating HTML elements and controls – An applet can update the values of HTML elements and controls in the parent web page by using the LiveConnect feature.
  • Directly invoking an page – An applet can use the class to invoke an page, pass parameters to the page, and retrieve a response.
Modes of Interaction


Cookies can be used to share data between an applet and an page. An applet can retrieve cookies set by an page. By the same token, an page can also retrieve cookies set by an applet.

In the code snippet shown next, the MapApplet class uses the class to retrieve the userName cookie set by the applet's parent web page. The text "Hello <user name>" is displayed on the top left corner of the applet.

private void getUserNameFromCookie() {
    try {
        // get the cookies that are applicable for this applet's parent web page
        URL docBaseUrl = this.getDocumentBase();
                     CookieHandler cookieHandler = CookieHandler.getDefault();         java.util.Map<String, List<String>> headers =                         cookieHandler.get(docBaseUrl.toURI(),                                         new HashMap<String,List<String>>());
        if (headers.isEmpty()) {
                  System.out.println("No cookies found!");
        } else {
    } catch(Exception e) {

private void getUserNameFromHeader(java.util.Map<String, List<String>> headers) {
   for (String key : headers.keySet()) {
       for (String value : headers.get(key)) {
           if (key.equals("Cookie") && value.startsWith("userName")) {
               userName = value.split("=")[1];


Note: You will need to sign your applet when using the API. If you do not wish to sign your applet, you can retrieve the value of a cookie by using JavaScript code in the ASP .net page. This value can be accessed by the applet in one of the following ways:

Updating Page With LiveConnect

An applet can interact with the JavaScript code in its parent web page by using the LiveConnect feature. The applet can invoke JavaScript functions and access JavaScript variables to update the contents of its parent web page. JavaScript code in the web page can also invoke applet methods.

In the following code snippet, the MapApplet class uses an instance of the netscape.javascript.JSObject class to update the contents of the asp:TextBox ID="addresses" control.

public void updateWebPage(String street, String city, String state) {
    char result = invokeAspPage(street, city, state);
    if (result == '1') {"writeAddressOnPage", new Object[] {street, city, state});


    <script type="text/javascript" language="javascript">
                     writeAddressOnPage(street, city, state) {
            var address = street + ", " + city + ", " + state;
            var form = document.getElementById("addrForm");
            var prevValue = form.elements["addresses"].value;
            form.elements["addresses"].value = prevValue + "\n" + address;

    <form id="addrForm" runat="server">
        <p>Addresses saved to your address book:</p>
                     asp:TextBox ID="addresses" TextMode="MultiLine" Rows="6"
                            Columns="60" runat="server" ></asp:TextBox>

When a form is posted, form field values become available to the next page through the Request object. You might also choose to update hidden form fields with the applet's data.

Invoking an Page

An applet can invoke an page by using the class. In the following code snippet, the MapApplet class opens a connection to the FileWriter.aspx page, passes parameters by using the connection's output stream, and receives a result by reading the connection's input stream.

public char invokeAspPage(String street, String city, String state) {
    char [] result = {'0'};
    String urlString = baseUrl + "FileWriter.aspx";
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    // send parameter to url connection
    OutputStreamWriter out = new OutputStreamWriter(
    out.write("addresses=" + URLEncoder.encode(address, "UTF-8"));
    // read response from url connection
    BufferedReader in = new BufferedReader(
                            new InputStreamReader(
    return result[0];

The FileWriter.aspx page writes the given address information to the userData/addresses.txt text file on the server. The page returns a character value of '1' if the address is written successfully.

As shown in this article, there are a number of ways by which an applet can interact with an page. Choose the option that works best for your application. We would love to hear feedback about this article! If you are using other creative ways to get applets to play well with pages, share your insights with the community!

Source Code

Download the project and the Java code (Netbeans project) to experiment further! Click on the following links to view individual source files:

Java Source Code ( zip file) Source Code ( zip file)

Rate This Article
Terms of Use