您的位置:首页 > Web前端 > JavaScript

Use Rhino to write SSJS(Server side javascript)

2012-06-28 15:44 525 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息