- Rhino is a java library for java script native object and script handling for java developer.
- In java version 6 is embedded implicitly as a default script engine. For java version less then 6 must download the rhino library from the following download location :-
Project Structure:-
Rhino Script Object & Context:-
- org.mozilla.javascript.Context is the class for entering the script context . It generally used for saving call stack.It is necessary to create a context for executing script.
RhinoJavaScriptDemo.java ,
package com.sandeep.rhino.js;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
public class RhinoJavaScriptDemo {
public static void main(String[] args) {
Context mozillaJsContext = Context.enter();
Scriptable scope = mozillaJsContext.initStandardObjects();
/*A Javascript JSON Object*/
String source = "{a :{5+6}}";
Script scriptjs = mozillaJsContext.compileString(source, "sandeepDemoScript", 1, null);
/*Result is a Javascript Object*/
Object jsObjectResult = scriptjs.exec(mozillaJsContext, scope);
String result = Context.toString(jsObjectResult);
System.out.println("After Evaluating JS Object value is: "+result);
}
}
Output:-
After Evaluating JS Object value is: 11
Rhino Script Engine and External Script File:-
- javax.script.ScriptEngine & javax.script.ScriptEngineManager are two classes to execute and manage script.
- Let the external java script file is demoJavaScriptFile.js .
demoJavaScriptFile.js ,
function add(num1,num2){
var sum = num1+num2;
print('Sum of the parameters passed By Java : '+sum);
}
JavaScriptEngineDemo.java ,
package com.sandeep.rhino.js;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JavaScriptEngineDemo {
public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
File jsFile = new File("./demoJavaScriptFile.js");
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine jsEngine = factory.getEngineByName("javascript");
jsEngine.put("out", System.out);
Reader reader = new FileReader(jsFile);
jsEngine.eval(reader);
Invocable invocableEngine = (Invocable) jsEngine;
invocableEngine.invokeFunction("add",5,6);
}
}
Output :-
Sum of the parameters passed By Java : 11