JDK6.0支持JAVA与JAVASCRIPT之间的互相调用,下面的实例将演示几种JAVA代码调用执行JAVASCRIPT代码的方法。
view plaincopy to clipboardprint?
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("javascript");
try {
//调用直接JAVASCRIPT语句
se.eval("println('111');");
String tmpstr = "test string";
se.eval(("println('" + tmpstr + "');"));
//调用无参数方法JAVASCRIPT函数
se.eval("function sayHello() {"
+ " print('Hello '+strname+'!');return 'my name is '+strname;" + "}");
Invocable invocableEngine = (Invocable) se;
se.put("strname", "testname");
String callbackvalue=(String) invocableEngine.invokeFunction("sayHello");
System.out.println(callbackvalue);
//调用有参数JAVASCRIPT函数
se.eval("function sayHello2(strname2) {"
+ " print('Hello '+strname+'!');return 'my name is '+strname2;" + "}");
callbackvalue=(String)invocableEngine.invokeFunction("sayHello2", "testname2");
System.out.println(callbackvalue);
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("javascript");
try {
//调用直接JAVASCRIPT语句
se.eval("println('111');");
String tmpstr = "test string";
se.eval(("println('" + tmpstr + "');"));
//调用无参数方法JAVASCRIPT函数
se.eval("function sayHello() {"
+ " print('Hello '+strname+'!');return 'my name is '+strname;" + "}");
Invocable invocableEngine = (Invocable) se;
se.put("strname", "testname");
String callbackvalue=(String) invocableEngine.invokeFunction("sayHello");
System.out.println(callbackvalue);
//调用有参数JAVASCRIPT函数
se.eval("function sayHello2(strname2) {"
+ " print('Hello '+strname+'!');return 'my name is '+strname2;" + "}");
callbackvalue=(String)invocableEngine.invokeFunction("sayHello2", "testname2");
System.out.println(callbackvalue);
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
执行后,输出结果如下:
111
test string
Hello testname!my name is testname
Hello testname!my name is testname2
javax.script包为我们提供了不少用得上的类和方法,这样调用增加了前、后台之间的交互性,JAVASCRIPT函数可写在前台页面中,实现内容的变更对后台无影响,不用重新编译、发布即可生效。