下面例子中,我们通过javax.script包ScriptEngine.put()方法设置JS脚本中的变量,JS把所有在线用户输出。
代码语言:javascript复制 1package ajava.code.javase;
2import javax.script.ScriptEngineManager;
3import javax.script.ScriptEngine;
4import javax.script.ScriptException;
5import java.util.Date;
6
7public class AjavaAccessJavaObjectFromScript {
8 public static void main(String[] args) {
9 //创建用户数组,共5个用户
10 String[] users = {"mark", "道长", "笨笨", "13810", "way"};
11 Date now = new Date();
12 //脚本代码,输出所有在线用户及当前时间
13 String script =
14 "var index; "
15 "var users = userArray; "
16 "for (index in users) { "
17 " println(users[index]); "
18 "}"
19 "println('----------'); "
20 "println('当前时间 (' date ')'); ";
21 //获得JS脚本引擎
22 ScriptEngineManager manager = new ScriptEngineManager();
23 ScriptEngine engine = manager.getEngineByExtension("js");
24 //设置JS脚本中的userArray、date变量
25 engine.put("userArray", users);
26 engine.put("date", now);
27 try {
28 engine.eval(script);//执行JS脚本
29 } catch (ScriptException e) {
30 e.printStackTrace();
31 }
32 }
33}
运行结果:
代码语言:javascript复制1mark
2道长
3笨笨
413810
5way
6----------
7当前时间 (Tue Apr 03 14:35:13 CST 2012)