当前位置: 代码迷 >> JavaScript >> 在Java中运作Javascript
  详细解决方案

在Java中运作Javascript

热度:181   发布时间:2012-10-08 19:54:56.0
在Java中运行Javascript
Java SE 6 开始支持各种脚本语言如PHP、Ruby、JavaScript、Python等。Java 6 默认支持执行Javascript,它是通过js引擎Mozilla Rhino来实现的。如:
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("js");
		System.out.println(engine.getClass());
		engine.put("age", 21);
		engine.eval("if (age >= 18){ " 
				  + "  print('Old enough to vote!'); "
				  + "} else {" 
				  + "  print ('Back to school!');" 
				  + "}");

输出:
class com.sun.script.javascript.RhinoScriptEngine
Old enough to vote!


    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    engine.put("a", 1);
    engine.put("b", 5);

    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    Object a = bindings.get("a");
    Object b = bindings.get("b");
    System.out.println("a = " + a);
    System.out.println("b = " + b);

    Object result = engine.eval("c = a + b;");
    System.out.println("a + b = " + result);

输出:
a = 1
b = 5
a + b = 6.0


  相关解决方案