js|在java代码中调用js里的方法

package com.dlb.controller; import java.io.FileReader; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; public class ScriptEngineTest { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); String jsFileName = "WebRoot/js/expression.js"; // 读取js文件FileReader reader = new FileReader(jsFileName); // 执行指定脚本 engine.eval(reader); if(engine instanceof Invocable) { Invocable invoke = (Invocable)engine; // 调用merge方法,并传入两个参数// c = merge(2, 3); Double c = (Double)invoke.invokeFunction("merge", 2, 3); System.out.println("c = " + c); }reader.close(); } }

以上代码可直接使用
String jsFileName = "WebRoot/js/expression.js"; // 读取js文件

这一句写的绝对路径,否则查找不到js文件
下面是js代码

function merge(a, b) { c = a * b; return c; }






    推荐阅读