81

Mozilla RhinoJS demo project

 5 years ago
source link: https://www.tuicool.com/articles/hit/VbmaUnZ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

When you execute this it will give 10 as the output as we expected before.

A context is like a session environment which holds the execution information per each script. The classes from standard Java API can be used directly through the Javascript sources. For an instance java.lang.System.out.println(“some text”) will display characters in the console with the use of Java API.

Creating a host object

Thereafter, We need to create ConsoleRunner java class because we are going to use ConsoleRunner and its exec method to achieve our goal within our custom Javascript engine. These mapped classes are known as host objects because we are able to directly use them inside our custom environment.

Create ConsoleRunner.java  by extending with the  ScriptableObject class

Here are some important facts about the above source,

jsConstructor is triggered with new ConsoleRunner constructor call from Javascript

jsFunction_exec is triggered by the exec method from Javascript. jsFunction_ prefix should be used in each mapped methods.

–  Overridden getClassName method should always return the current class name.

Let put all the stuff together

We need to modify RhinoExample.java by adding our sample code snippet and also by adding a reference to our host object class.

When you execute above launcher program you will see the version of your Python environment as we expected at the beginning. According to the example, it is very easy to handle things like database connections, threads etc via Javascript using the Rhino engine. Thus. Node-like our own Javascript run-time can be developed. Source code for this simple demo can be found here .

Find Shalitha Suranga on Medium for more tutorials and articles

Happy Coding :man:‍:computer:

References

1. https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Documentation 

2. http://blog.notdot.net/2009/10/Server-side-JavaScript-with-Rhino


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK