Use Rhino to write SSJS(Server side javascript)

18 篇文章 0 订阅
12 篇文章 0 订阅
package jason.Rhino.study;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.mozilla.js.Context;
import org.mozilla.js.ContextAction;
import org.mozilla.js.ContextFactory;
import org.mozilla.js.ImporterTopLevel;
import org.mozilla.js.Scriptable;

public class ScriptManager {

	private Scriptable scope = null;
	private String beanName = null;

	public ScriptManager(final String beanName, final Object beanObj) {
		this.beanName = beanName;
		ContextFactory.getGlobal().call(new ContextAction() {
			@Override
			public Object run(Context cx) {
				scope = new ImporterTopLevel(cx);
				Scriptable wrapped = Context.toObject(beanObj, scope);
				scope.put(beanName, scope, wrapped);
				return null;
			}
		});
	}

	public Object exec(final String script) {
		ContextFactory.getGlobal().call(new ContextAction() {
			@Override
			public Object run(Context cx) {
				return cx.evaluateString(scope, script, null, 0, null);
			}
		});
		return null;
	}

	public void exec(File scriptFile) throws IOException {
		FileReader in = new FileReader(scriptFile);
		StringBuffer strBuf = new StringBuffer("");
		char[] buf = new char[2048];
		int length = -1;
		while ((length = in.read(buf)) != -1) {
			strBuf.append(buf, 0, length);
		}
		String scriptStr = strBuf.toString();
		in.close();
		in = null;
		strBuf = null;
		buf = null;
		exec(scriptStr);
	}
	
	public void destroyBean()
	{
		scope.delete(this.beanName);
	}
	
	public static void main(String[] args) throws Exception {
		CheckDataTampered check = new CheckDataTampered();
		ScriptManager js = new ScriptManager("check", check);
		File file = new File("./src/jason/Rhino/study/test.js");
		if(file.exists()) {
			js.exec(file);
		}else {
			System.out.println("file not found");
		}
	}

}



package jason.Rhino.study;

import java.util.ArrayList;
import java.util.List;

public class CheckDataTampered {
	private List<String> lsFields = new ArrayList<String>();
	
	public void setProtectedField(String fieldName) {
		lsFields.add(fieldName);
	}
	
	public void printOut() {
		for(String field : lsFields) {
			System.out.println(field);
		}
	}
}

test.js

check.setProtectedField("111111111");
check.setProtectedField("222222222");
check.setProtectedField("333333333");
check.setProtectedField("444444444");
check.setProtectedField("555555555");
check.setProtectedField("666666666");
check.printOut();

js.jar is needed.












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值