Rhino-用纯Java写成的JavaScript的开放源代码实现

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

//http://www.cnblogs.com/cczw/archive/2012/07/16/2593957.html
//http://www.oschina.net/p/rhino/
//Rhino是用纯Java写成的JavaScript的开放源代码实现。它最常被用于嵌入Java应用程序,以便为终端用户提供脚本的能力。	
//开源下载:https://github.com/downloads/mozilla/rhino/rhino1_7R4.zip
//http://www.iteye.com/topic/87423
//http://blog.csdn.net/szwangdf/article/details/25376415
//http://blog.csdn.net/ycyangcai/article/details/6452143
public class TestJs {

	public static void main(String[] args) {
		Context ctx = Context.enter();
		Scriptable scope = ctx.initStandardObjects();

		String jsStr = "100*20/10";
		Object result = ctx.evaluateString(scope, jsStr, null, 0, null);
		System.out.println("result=" + result);
		ctx.exit();
		test001();
		test002();
		test003();
	}

	private static void test003() {
		try {
			ScriptEngineManager factory = new ScriptEngineManager();
			ScriptEngine engine = factory.getEngineByName("JavaScript");
			engine.eval("print('Hello World')");
		} catch (ScriptException e) {
			e.printStackTrace();
		}

	}

	private static void test002() {
		Context ctx = Context.enter(); // 获取环境设置
		Scriptable scope = ctx.initStandardObjects(); // 初始化本地对象
		scope.put("x", scope, new Integer(20)); // 输入参数设置
		scope.put("y", scope, new Integer(30));
		try {
			ctx.evaluateString(scope, "var result=x+y", "", 1, null); // 执行
			System.out.println(scope.get("result", scope)); // 结果输出
		} finally {
			Context.exit();
		}

	}

	private static void test001() {

		Context cx = Context.enter();
		try {
			String s = "var c = 100 + 200";
			Scriptable so = cx.initStandardObjects();
			cx.evaluateString(so, s, "ex-1", 1, null);
			System.out.println("result=" + so.get("c", so));
		} finally {
			cx.exit();
		}

	}

}

你可能感兴趣的:(Rhino-用纯Java写成的JavaScript的开放源代码实现)