The
jdk6.0 supports mutual invocation between Java and JavaScript, and the following example demonstrates several Java code calls to execute JavaScript code.
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 {//Invoke the direct JavaScript statement se.eval ("println (' 111 ');"); String tmpstr = "Test string"; Se.eval ("println (' + tmpstr + ');"); Invoke the Parameterless method JavaScript function Se.eval ("function SayHello () {" + "print (' Hello ' +strname+ '! '); Return ' I name is ' +strname ' + '} '; Invocable invocableengine = (invocable) se; Se.put ("strname", "testname"); String callbackvalue= (String) invocableengine.invokefunction ("SayHello"); System.out.println (Callbackvalue); Invokes the parameter JavaScript function se.eval ("function SayHello2 (strname2) {" + "print (' Hello ' +strname+ '! '); Return ' I 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 ();}} }
After the execution, the output results are as follows:
111
Test string
Hello testname!my name is testname
Hello testname!my name is testname2
Javax.script package provides us with a lot of use of classes and methods, so that calls to increase the interaction between the front and back, JavaScript functions can be written in the foreground page, the implementation of changes in the background without impact, without recompiling, publishing can take effect.