19 July 2011

Add JavaScript to your application with Rhino

By Andrew Clifford

The Rhino JavaScript engine lets you add the flexibility of JavaScript to your Java application.

Most people are familiar with JavaScript running in web browsers, where it is used to improve the appearance and usability of web pages. JavaScript can also be used outside of a browser, for example running on a server. One powerful use of JavaScript is to embed JavaScript in a server-based application to let users (or at least power users) extend the functionality of the application.

Within our MA2 product, we use the Rhino JavaScript engine to do just that.

We knew we needed some user-defined capabilities, particularly for calculations for derived data. Rather than write this ourselves, we decided to use JavaScript, as this is widely-known and easy to use. We selected the Rhino JavaScript engine from Mozilla. It is written in Java, and so can integrate into our Java-based software. As well as being a leading implementation of JavaScript, it is open-source software which we can include in our product for free.

We have integrated JavaScript deeply within MA2, to provide a consistent mechanism for user-defined capabilities throughout the product. We use it for for data validation, calculating derived data, data triggers, and as a general scripting language including writing new web services. We also use it for user interface customisation, running JavaScript on the server to create web pages to send to the browser.

At its simplest, integrating Rhino into an application involves only a few lines of code. However, our requirements are relatively complicated:

We found that Rhino is capable of supporting these more complicated requirements, and is very stable and performs well.

We had originally intended to use JavaScript for user-defined calculations for derived data. However, the JavaScript support is so effective that we have ended up writing much of MA2's capability in JavaScript. Although I would be cautious of using it for performance-critical processing, it is perfectly adequate for "user speed" activities such as validating data entry. It works very well alongside the general-purpose data structure and user interface of MA2, letting us build new solutions very quickly.

Most business applications do not need the level of JavaScript integration that we have built into MA2. However, JavaScript is a good way of adding the sort of user-defined capabilities that many business applications do need, such as user-defined calculations. Embedding a JavaScript engine such as Rhino into your application is a much better option than attempting to write your own extension mechanism.

If you have a Java-based application, and need to add user-defined capabilities to it, look at Rhino.