java调用javascript
介绍
jdk1.6提供了对JavaScript的支持,使用的js引擎为Rhino,jdk1.8替换成了Nashorn。
使用
public class Client {
public static void main(String[] args) throws IOException,
ScriptException, NoSuchMethodException {
//获取javascript引擎
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = engineManager.getEngineByName("javascript");
System.out.println(scriptEngine);
invokeJsWithString(scriptEngine);
}
private static void invokeJsWithString(ScriptEngine scriptEngine)
throws ScriptException, NoSuchMethodException {
String code = "12 + 34";
//执行javascript语句
Object result = scriptEngine.eval(code);
System.out.println(result);
//绑定变量
Bindings bindings = scriptEngine.createBindings();
bindings.put("name", "lisi");
scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
//name为外部变量
code = "function print(num1,num2) { return num1 + num2 + name; }";
scriptEngine.eval(code);
//执行javascript函数
result = ((Invocable) scriptEngine).invokeFunction("print", 4, 5);
System.out.println(result);
}
}
输出结果为
jdk.nashorn.api.scripting.NashornScriptEngine@61f8bee4
46
9lisi
spring对java中的API进行了一些简单的封装
public class Client {
public static void main(String[] args) {
StandardScriptEvaluator evaluator = new StandardScriptEvaluator();
evaluator.setLanguage("javascript");
Object result = evaluator.evaluate(new StaticScriptSource("12 + 34"));
System.out.println(result);
}
}
46