赞
踩
JavaScript操作Java对象的实现:
代码片段1(获取脚本引擎):
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class GetSupportedScriptingEngine {
public static void main(String[] args) {
//创建一个ScriptEngineManager
ScriptEngineManager manager = new ScriptEngineManager();
//取得所有ScriptEngineFactory
List factories = manager.getEngineFactories();
//遍历输出
for (ScriptEngineFactory factory : factories) {
System.out.println("EngineName = " + factory.getEngineName());
System.out.println("EngineVersion = " + factory.getEngineVersion());
System.out.println("LanguageName = " + factory.getLanguageName());
System.out.println("LanguageVersion = " + factory.getLanguageVersion());
System.out.println("Extensions = " + factory.getExtensions());
List names = factory.getNames();
for (String name : names) {
System.out.println("Engine Alias = " + name);
}
//通过factory获取ScriptEngine
ScriptEngine scriptEngine = factory.getScriptEngine() ;
//ScriptEngine scriptEngine1 = manager.getEngineByExtension("js") ;其他方式获取
//ScriptEngine scriptEngine2 = manager.getEngineByName("JavaScript") ;其他方式获取
try {
//脚本引擎执行JavaScript语句
scriptEngine.eval("var arr = new Array() ; arr.push(1); print(arr.pop())") ;
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
}
代码片段2(JS操作Java):
import java.util.ArrayList;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JSModifiedJava {
public void sayHello(String name){
System.out.println("*************Hello***************"+name);
}
public static void main(String[] args) {
//创建 List对象,并添加3个原用户
List us = new ArrayList();
us.add("JLee 1");
us.add("JLee 2");
//获得JS引擎
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
//把List对象加入JS引擎
engine.put("usList", us);
//将要操作的对象法如引擎
engine.put("obj", new JSModifiedJava()) ;
try {
engine.eval(getScript());//通过引擎调用getScript()
//显示所有用户
for (String usname : us) {
System.out.println("所有用户 = " + usname);
}
} catch (ScriptException e) {
e.printStackTrace();
}
//根据JavaScript名获取一个脚本引擎实例
ScriptEngine engine2 = manager.getEngineByName("JavaScript");
try {
engine2.eval("print('Hello JLee ...')");
} catch (ScriptException e) {
e.printStackTrace();
}
}
//获取JavaScript串
private static String getScript() {
//我们在脚本里添加4个新用户
String script =
"var index; " +
"var usname = usList.toArray(); " +
"for (index in usname) { " +
" println('原用户='+usname[index]); " +
"}" +
"usList.add(\"JLee 3\"); " +
"usList.add(\"JLee 4\"); " +
"obj.sayHello('JLee')" ;
return script;
}
}
2
顶
1
踩
分享到:
2012-03-27 14:53
浏览 4646
评论
1 楼
zgpinguo
2012-04-04
dwr就是一种javascript调用java方法的。。。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。