Calling Java applets from JavaScript

I ran in to a situation recently where I had a big mess of code written in Java that I really wanted to call from a client-side web application. I could wrap said code up in a servlet, but that would be a lot of work. As it turns out, you can call methods on Applets directly from JavaScript, so all I have to do is wrap my code in one of those. Bonus!

Here’s a brief example

DoublerApplet.java

package org.obfuscated.example;

import java.applet.Applet;

public class DoublerApplet extends Applet {
    public double f(double x) {
        return x + x;
    }
}

Nothing special there. Note that I’ve not yet tried passing classes or the like to an applet. I imagine that they might be trouble.

index.html

<html>
  <head>
    <title>Applet Test</title>
    <script src="prototype.js"></script>
    <script src="doubleit.js"></script>
  </head>
  <body>
    <object id="doubler"
       classid="java:org.obfuscated.example.DoublerApplet.class" 
       type="application/x-java-applet"
       archive="DoublerApplet.jar" 
       height="1" width="1" >
      <param name="scriptable" value="true"/>
    </object>

    <b>Double me!</b>
    <br/>
    2 * <input size="5" type="text" id="x"/> = <span id="answer">???</span>
    <br/>
    <input type="submit" id="go"/>
  </body>
</html>

The important part is the “scriptable” parameter. It tells the applet to listen to the JavaScript.

doubleit.js

var init = function() {
    Event.observe('go', 'click', function() {
        var x = Number($('x').value);
        var applet = $('doubler');
        $('answer').innerHTML = applet.f(x);
        return false;
    });
};

Event.observe(window, 'load', init);

The “$” magic that makes the JavaScript code quite so terse is Prototype, which I can’t quite recommend enough.

Anyway, I’m quite pleased that I’m able to use this technique, as dragging out Tomcat, keeping it running, etc., would be a whole lot of work just to be able to call one function. (Which is all I need to do in this particular case.) I’m sure the server-based solution would be more correct if I needed to do more in Java-land, but for quick and dirty things or one-off’s, JavaScript to Applet communication is nice.

Leave a Reply


This is a free Wordpress template provided by Mathew Browne | Web Design | SEO