凤凰山笔记

使用java执行javascript脚本

原来java可以执行javascript脚本的,这个可帮了大忙。

以下代码可以执行一个js文件中的某个js方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class RunJs {

public static void main(String[] args) throws FileNotFoundException, ScriptException, NoSuchMethodException {
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine engine = scriptEngineManager.getEngineByExtension("js");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("google_tk.js")));

engine.eval(reader);

Invocable invocable = (Invocable)engine;
//这里参数 第一个是js文件中的js function名字,第二个是funciton接受的参数
Object result = invocable.invokeFunction("VL", "happy new year!");
System.out.println(result);
}

/**
* java调用js
* @param filePath
* @param menthod
* @param parm
* @return
*/
public static String invokeJs(String filePath,String menthod,String parm) throws Exception{

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine engine = scriptEngineManager.getEngineByExtension("js");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));

engine.eval(reader);

Invocable invocable = (Invocable)engine;
Object result = invocable.invokeFunction(menthod,parm);

return result.toString();
}

}

cloudroc wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
很惭愧,只做了些微小的工作,您的支持将鼓励我继续努力创作!