一、前言
基于mozilla的js.jar包中org.mozilla.javascript.Function、org.mozilla.javascript.Context及org.mozilla.javascript.Scriptable定义ScriptTool脚本工具类,进行后端java调用解析指定JAVASCRIPT函数并返回js函数执行结果、执行出入的js串,返回变量值Map等逻辑方法,详情代码示例说明。
二、代码示例
package test;@b@@b@import java.io.IOException;@b@import java.util.HashMap;@b@import java.util.Map;@b@@b@import org.mozilla.javascript.Context;@b@import org.mozilla.javascript.Function;@b@import org.mozilla.javascript.Scriptable;@b@@b@public class ScriptTool {@b@ /**@b@ * @see 执行js函数,返回js函数执行结果@b@ * @param jsFile@b@ * @param funName@b@ * @param args@b@ * @return@b@ */@b@ public static Object callFunction(String jsFile,String funName,Object[] args){@b@ String jsPath = jsFile;@b@ String jsFunction = funName;@b@ Object result=null;@b@ Context cx = Context.enter();@b@ java.io.FileReader fr = null;@b@ try {@b@ Scriptable scope = cx.initStandardObjects();@b@ fr = new java.io.FileReader(jsPath);@b@ cx.evaluateReader(scope, fr, "<cmd>", 1, null);@b@@b@ Object fObj = scope.get(jsFunction, scope);@b@ if (!(fObj instanceof Function)) {@b@ System.out.println("Function not found" +jsFunction);@b@ } else {@b@ Function f = (Function)fObj;@b@ result = f.call(cx, scope, scope, args);@b@ System.out.println("return:"+Context.toString(result));@b@ }@b@ } @b@ catch(Exception e){@b@ e.printStackTrace();@b@ }@b@ finally {@b@ Context.exit();@b@ if(fr != null)@b@ try {@b@ fr.close();@b@ } catch (IOException e) {@b@ e.printStackTrace();@b@ }@b@ }@b@ return result;@b@ }@b@ /**@b@ * @see 执行出入的js串,返回变量值Map@b@ * @param jString@b@ * @param varNames 返回map中变量名称@b@ * @return Map 变量值@b@ */@b@ public static Map eval(String jString,String[] varNames){@b@ Map result=new HashMap();@b@ Context cx = Context.enter();@b@ try {@b@ Scriptable scope = cx.initStandardObjects();@b@ cx.evaluateString(scope, jString, "<cmd>", 1, null);@b@ for(int i=0;i<varNames.length;i++){@b@ result.put(varNames[i],scope.get(varNames[i], scope));@b@ }@b@ @b@ } @b@ catch(Exception e){@b@ e.printStackTrace();@b@ }@b@ finally {@b@ Context.exit();@b@ }@b@ return result;@b@ }@b@ public static void main(String[] args) {@b@ @b@ try {@b@ //执行js函数@b@ String jsFile="c:\\temp\\mactest.js";@b@ String funName="mactest";@b@ Object[] arges={"m1","m2"};@b@ Object result=ScriptTool.callFunction(jsFile, funName, arges);@b@ System.out.println(result);@b@ @b@ //执行js脚本@b@ StringBuffer jString=new StringBuffer();@b@ jString.append("var i=1;");@b@ jString.append("var j=2;");@b@ jString.append("var c=(i+j)*100;");@b@ Map varsMap=ScriptTool.eval(jString.toString(),new String[]{"i","j","c"});@b@ System.out.println(varsMap);@b@ @b@ } catch (Exception e) {@b@ e.printStackTrace();@b@ }@b@ }@b@@b@}
#mactest.js内容@b@function mactest(m1,m2){ @b@ return 'm3'; @b@}
控制台打印结果
return:m3@b@m3@b@{c=300.0, j=2, i=1.0}