java中执行javascript案例

时间:2021-01-14 07:12:16

Nashorn js engine官方文档 
https://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/#top

java函数输出js的hello world:

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Maub {
public static void main(String args[]) throws ScriptException, NoSuchMethodException{
//引擎管理器
ScriptEngineManager m = new ScriptEngineManager();
//获取引擎
ScriptEngine engine = m.getEngineByName("JavaScript");
//执行javascript代码
engine.eval("function hello(name){print('hello '+name)}");
//Javascript实现了invocable调用接口
Invocable inv = (Invocable) engine;
//调用函数hello,传入world
inv.invokeFunction("hello","world");
}
}

调用文件里的js脚本:

import java.io.FileNotFoundException;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Maub {
public static void main(String args[]) throws ScriptException, NoSuchMethodException, FileNotFoundException{//引擎管理器
ScriptEngineManager m = new ScriptEngineManager();
//获取引擎
ScriptEngine engine = m.getEngineByName("JavaScript");
//执行javascript代码
engine.eval(new java.io.FileReader("E:\\Code\\Java\\src\\getpwd.js")); Invocable inv = (Invocable) engine;
String arg[] = {"MDwwDQYJKoZIhvcNAQEBBQADKwAw","fot123456"};
//使用Invocable调用脚本函数,传入String参数
System.out.println(inv.invokeFunction("getpwd",arg));
}
}