Using JavaScript script in Java

Posted by jvalarta on Mon, 30 Mar 2020 16:46:52 +0200

About Nashorn

Nashorn is a javascript engine.
Starting from JDK 1.8, nashorn replaced Rhino (JDK 1.6, JDK 1.7) as an embedded JavaScript engine of Java. Nashorn fully supports the ECMAScript 5.1 specification and some extensions.
It uses new language features based on JSR 292, including invokedynamic introduced in JDK 7, to compile JavaScript into Java bytecode.
This results in a performance improvement of 2 to 10 times over the previous Rhino implementation.

Usage mode
  1. Script JavaScript
    Column: the JavaScript method uses the Java object execution method to get the return value.
function scriptFunction(obj){
	var a = 1;
	var b = 2;
	return obj.sum(a,b);
}
scriptFunction(obj);//Call this method

The script variable is defined as String script1;
2. Create JavaScript container user storage script ScirptContainer.java

public class ScirptContainer {
	
	
	public static ScriptEngine engine;//Script engine
	
	static {
		ScriptEngineManager manager = new ScriptEngineManager();//Script engine management
		engine = manager.getEngineByName("nashorn");//Get the nashorn script engine
		engine.getContext().getWriter();//Get body and write
	}
	
	private ConcurrentHashMap<Integer, CompiledScript> scripts = new ConcurrentHashMap<>();//Script storage container
	
	
	public CompiledScript getCompiledScript(String script) throws ScriptException{
		//Determine whether the script is empty
		if(script == null || "".equals(script)){
			throw new ScriptException("JavaScript empty");
		}
		//Get script Hash
		int hashCode = script.hashCode();
		//Get script from container
		CompiledScript compiledScript = scripts.get(hashCode);
		if(compiledScript == null){
			//No script in container to create script object
			Compilable compilable = (Compilable) engine;
			//Compiling JavaScript scripts
			compiledScript = compilable.compile(script);
			//Script object stored in container
			scripts.put(hashCode, compiledScript);
		}
		return compiledScript;
	}
	
}
  1. Java executing JavaScript script
public class ScriptHandler {
	
	//Create container object
	private ScirptContainer scirptContainer = new ScirptContainer();
	
	//Objects to execute
	String js1 = "function scriptFunction(obj){  var a = 1; var b = 2; return obj.sum(a,b); } scriptFunction(obj);";
	
	@Test
	public void test() throws ScriptException{
		//Get script object
		CompiledScript c1 = scirptContainer.getCompiledScript(js1);
		//Create parameter binding
		Bindings bindings = scirptContainer.engine.createBindings();
		//obj parameter binding SumTest class
		bindings.put("obj", new SumTest());
		//Execute JavaScript script and print return value
		System.out.println(c1.eval(bindings));
	}
}

matters needing attention:

  1. scriptFunction(obj) in script; must exist, otherwise method will not be executed
  2. Java objects can be created in the script, and the full class name is required, such as var map = new java.util.HashMap();

Topics: Java Javascript JDK ECMAScript