下面例子中,我们通过javax.script包ScriptEngine.put()方法设置JS脚本中的变量,JS把所有在线用户输出。
package ajava.code.javase;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.Date;
public class AjavaAccessJavaObjectFromScript {
public static void main(String[] args) {
//创建用户数组,共5个用户
String[] users = {"mark", "道长", "笨笨", "13810", "way"};
Date now = new Date();
//脚本代码,输出所有在线用户及当前时间
String script =
"var index; " +
"var users = userArray; " +
"for (index in users) { " +
" println(users[index]); " +
"}" +
"println('----------'); " +
"println('当前时间 (' + date+')'); ";
//获得JS脚本引擎
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
//设置JS脚本中的userArray、date变量
engine.put("userArray", users);
engine.put("date", now);
try {
engine.eval(script);//执行JS脚本
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
运行结果:
mark
道长
笨笨
13810
way
----------
当前时间 (Tue Apr 03 14:35:13 CST 2012)