Notes on Java Applets and AJAX
Down and Dirty Developer Documentation
I compiled the following notes while working on the JHotDrawPlugin
. I wanted to be able to perform an AJAX request from a Java appplet - sounds simple, but there is a dearth of reliable information on java applets on the web. A lot of the information that is out there relates to older versions of Java and browsers, more is apocryphal or just plain wrong. Even documentation on java.sun.com has to be treated with caution.
First off let me make it clear that it's easy to use URLConnection to make an AJAX request from a Java applet. The pain doesn't start until you have to work with cookies.
Foswiki requires cookies to validate a request. The relevant cookies are FOSWIKISTRIKEONE and FOSWIKISID. The first of these has to be used to compose a validation key for the request, and the second is required to authenticate the request. The FOSWIKISID is flagged as HttpOnly
, making it unreadable from JS.
This is a plain cookie that is combined with a plain key passed in the HTML to create a validation key for the request.
The obvious approach is to pass the HTML validation key to the applet, and have the applet read the cookie and compose the validation key. However I found it impossible to reliably read the browser cookies from Java, following the instructions on the web. The function appears to be highly sensitive to security settings, and more often than not fails silently. Note that none of the test sites I found on the web worked either.
URLConnection is supposed to send the browser cookies by default with a request, but after careful inspection with a packet sniffer you can see that it does not
to the applet, but this has the same limitation. This impacts Foswiki severely because the FOSWIKISID is marked as HttpOnly). I was unable to find a way to pass this cookie with a URLConnection without rewriting it as a non-HttpOnly cookie, which compromises security.
The documented way to call JS functions from Java is using the
class. I was unable to get this to work reliably on all browsers; the browser would not find the requisite class, or the call was sometimes rejected with a security exception. This leads me to think this is too sensitive to setup to be useful. My experience with the
classes was similar; browser support is patchy.
The one thing I found easy and reliable was calling Java from JS. The approach I ended up with instead was to poll the applet from JS, to flag when a save event was ready, and have JS call a method in the applet to get the parameters for the event. The polling period has to be chosen carefully - too frequent, and the performance suffers noticeably, too rare and the user performance suffers.
- 04 Oct 2009