Java Applets, ASP.net - Can You Play Together?

   
By Sowmya Kannan, February 2010  

Is your web application platform based on ASP.net 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 ASP.net technology. In this article, we will explore various mechanisms by which Java applets can interact with ASP.net web pages.

View Applet - ASP.net Interaction

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


 
Deploying an Applet in an ASP.net Page

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

Default.aspx

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

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

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

Cookies

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

In the code snippet shown next, the MapApplet class uses the java.net.CookieHandler 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 {
                  getUserNameFromHeader(headers);
        }
    } 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 java.net.CookieHandler 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 ASP.net 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.

MapApplet.java

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

Default.aspx

<body>
    ...
    <script type="text/javascript" language="javascript">
        function  
                     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;
        }
    </script>

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

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

Invoking an ASP.net Page

An applet can invoke an ASP.net page by using the java.net.URLConnection 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.

MapApplet.java

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();
    connection.setDoOutput(true);
    // send parameter to url connection
    OutputStreamWriter out = new OutputStreamWriter(
                          connection.getOutputStream());
    out.write("addresses=" + URLEncoder.encode(address, "UTF-8"));
    out.close();
    // read response from url connection
    BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            connection.getInputStream()));
    in.read(result);
    in.close();
    ...
    return result[0];
}
 

The FileWriter.aspx page writes the given address information to the userData/addresses.txt text file on the ASP.net 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 ASP.net 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 ASP.net pages, share your insights with the community!

Source Code

Download the ASP.net 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)

ASP.net Source Code ( zip file)

 
Resources
Rate This Article
 
 
Comments
Terms of Use