JAVA执行js脚本

import jdk.nashorn.api.scripting.ScriptObjectMirror;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;
import java.io.FileReader;
import java.util.Map;
import java.util.TreeMap;

public class JSEngine {
    public static ScriptEngine engine;
    public static String str;

    public static void getValues() throws Exception{
        str = "  var msg='hello';          "
                + "  var number = 123;         "
                + "  var array=['A','B','C'];  "
                + "  var json={                "
                + "      'name':'pd',          "
                + "      'subjson':{           "
                + "           'subname':'spd'  "
                + "           ,'id':123        "
                + "           }                "
                + "      };                    ";
        engine.eval(str);
        str="msg+=' world';number+=5";
        System.out.println(engine.get("msg"));
        System.out.println(engine.get("number"));
        //获取数组
        ScriptObjectMirror array = (ScriptObjectMirror) engine.get("array");
        System.out.println(array.getSlot(0));

        ScriptObjectMirror json = (ScriptObjectMirror) engine.get("json");
        System.out.println(json.get("name"));

        //json嵌套
        ScriptObjectMirror subjson = (ScriptObjectMirror) json.get("subjson");
        System.out.println(subjson.get("subname"));
    }

    public static void getObject() throws Exception{
        str = "  var obj=new Object();     "
                + "  obj.info='hello world';   "
                + "  obj.getInfo=function(){   "
                + "        return this.info;   "
                + "  };                        ";
        engine.eval(str);
        ScriptObjectMirror obj = (ScriptObjectMirror) engine.get("obj");
        System.out.println(obj.get("info"));
        System.out.println(obj.get("getInfo"));
        str = "obj.getInfo()";
        System.out.println(engine.eval(str));
    }

    //给js传递变量
    public static void putValue() throws Exception{
        str = "Math.pow(a,b)";
        Map<String,Object> input = new TreeMap<>();
        input.put("a",2);
        input.put("b",8);
        System.out.println(engine.eval(str,new SimpleBindings(input)));
    }

    //调用js函数
    public static void callJSFunction() throws Exception{
        str = "function add (a, b) {return a+b; }";
        //执行js脚本定义函数
        engine.eval(str);
        Invocable invocable = (Invocable) engine;
        Object res = invocable.invokeFunction("add",new Object[]{2,3});
        System.out.println(res);

    }

    //读取js文件,执行函数;易变业务使用脚本编写,这样即使修改脚本,也不需重新部署java程序
    public static void callJSFunctionFromFile() throws Exception{
        //执行js
        while (true){
            //模拟执行期间add.js被修改
            Thread.sleep(5000);
            engine.eval(new FileReader("e:\\add.js"));
            Invocable invocable = (Invocable) engine;
            Object res = invocable.invokeFunction("add",new Object[]{2,3});
            System.out.println(res);
        }
    }

    public static void main(String[] args) throws Exception{
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        engine = scriptEngineManager.getEngineByName("javascript");
        getValues();
        getObject();
        putValue();
        callJSFunction();
        callJSFunctionFromFile();
    }

}
public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = engine = manager.getEngineByName("JavaScript");
    engine.put("result", null);
    engine.put("value", null);
    String script = "var citys=[\"西安市\",\"北京市\",\"天津市\"];var result=\"\";if(null!=value){for(i=0;i<citys.length;i++){if(value.indexOf(citys[i])!=-1){result=citys[i];}}}";
    try {
        engine.eval(script);
        System.out.println(engine.get("result"));
    } catch (ScriptException e) {
        e.printStackTrace();
    }
}
public static void main(String[] args) {
    try {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
        Compilable compilable = (Compilable) engine;
        Bindings bindings = engine.createBindings();
        String script = "function cityContains(str){citys=[\"西安市\",\"北京市\",\"天津市\"];for(i=0;i<citys.length;i++){if(str.indexOf(citys[i])!=-1){return citys[i];}}return \"\";} cityContains(city)";
        CompiledScript JSFunction = compilable.compile(script); //解析编译脚本函数
        bindings.put("city", "天津市");
        Object result = JSFunction.eval(bindings);
        System.out.println(result); //调用缓存着的脚本函数对象,Bindings作为参数容器传入
    } catch (ScriptException e) {
        log.error("执行JS函数发生异常", e);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值