1. 程式人生 > 實用技巧 >java呼叫javascript

java呼叫javascript

介紹

jdk1.6提供了對JavaScript的支援,使用的js引擎為Rhino,jdk1.8替換成了Nashorn。

使用

public class Client {
  public static void main(String[] args) throws IOException,
      ScriptException, NoSuchMethodException {
//獲取javascript引擎
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine scriptEngine = engineManager.getEngineByName("javascript");
    System.out.println(scriptEngine);
    invokeJsWithString(scriptEngine);
  }

  private static void invokeJsWithString(ScriptEngine scriptEngine)
      throws ScriptException, NoSuchMethodException {
    String code = "12 + 34";
//執行javascript語句
    Object result = scriptEngine.eval(code);
    System.out.println(result);
//繫結變數
    Bindings bindings = scriptEngine.createBindings();
    bindings.put("name", "lisi");
    scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
//name為外部變數
    code = "function print(num1,num2) { return num1 + num2 + name; }";
    scriptEngine.eval(code);
//執行javascript函式
    result = ((Invocable) scriptEngine).invokeFunction("print", 4, 5);
    System.out.println(result);
  }
}

輸出結果為

jdk.nashorn.api.scripting.NashornScriptEngine@61f8bee4
46
9lisi

spring對java中的API進行了一些簡單的封裝

public class Client {
  public static void main(String[] args) {
    StandardScriptEvaluator evaluator = new StandardScriptEvaluator();
    evaluator.setLanguage("javascript");
    Object result = evaluator.evaluate(new StaticScriptSource("12 + 34"));
    System.out.println(result);
  }
}
46