Sometimes, we want to call the js method in Java, instead of being triggered like an event on the page. How can we do this? This afternoon, I have nothing to do. I want to share with you. No, I hope you can correct it and make progress together!
/* <Br/> * load the script engine and call the js method in Java <br/> */<br/> Public void Test2 () <br/>{< br/> scriptenginemanager manager = new scriptenginemanager (); </P> <p> scriptengine engine = manager. getenginebyname ("JavaScript"); <br/> try {<br/> string STR = "2 & 1"; <br/> double D = (double) engine. eval (STR); <br/> integer I = D. intvalue (); <br/> system. out. println (I); <br/>} catch (scriptexception ex) {<br/> ex. printstacktrace (); <br/>}</P> <p>}
/* <Br/> * Call Js in Java. jdk1.6 loads the JS engine class and then calls the js method. <Br/> * assign a value to the form parameter in the script method through the JDK platform <br/> */<br/> Public void test (string name) <br/>{< br/> scriptenginemanager SEM = new scriptenginemanager (); <br/>/* <br/> * SEM. the getenginebyextension (string extension) parameter is JS <br/> SEM. the getenginebymimetype (string mimetype) parameter is application/JavaScript or text/JavaScript <br/> SEM. the getenginebyname (string shortname) parameter is JS, JavaScript, or Javascript <br/> */<br/> scriptengine Se = SEM. getenginebyname ("JS"); <br/> try <br/> {<br/> string script = "function say () {return 'hello, '"+ name +" ;}"; <br/> Se. eval (SCRIPT); <br/> invocable inv2 = (invocable) se; <br/> string res = (string) inv2.invokefunction ("say", name ); <br/> system. out. println (RES); <br/>}< br/> catch (exception e) <br/>{< br/> E. printstacktrace (); <br/>}</P> <p>}
/* <Br/> * demonstrate how to use an object in Java as a global variable in JS, assign the file class to the script language, and obtain its attributes. <Br/> */<br/> Public void testscriptvariables () <br/> {<br/> scriptenginemanager SEM = new scriptenginemanager (); <br/> scriptengine engine = SEM. getenginebyname ("JS"); <br/> file = new file ("C: // 1.txt"); <br/> engine. put ("F", file); <br/> try {<br/> engine. eval ("println ('path: '+ F. getpath () "); // The alert method cannot be used <br/>} catch (scriptexception e) {<br/> E. printstacktrace (); <br/>}</P> <p>}
/* <Br/> * demonstrate how to use a thread to start a js method in Java <br/> */<br/> Public void testscriptinterface () throws scriptexception <br/>{< br/> scriptenginemanager SEM = new scriptenginemanager (); <br/> scriptengine engine = SEM. getenginebyname ("JS"); <br/> string script = "Var OBJ = new object (); obj. run = function () {println ('test thread')} "; <br/> engine. eval (SCRIPT); <br/> Object OBJ = engine. get ("OBJ"); // get the object in JS <br/> invocable inv = (invocable) engine; <br/> runnable r = Inv. getinterface (OBJ, runnable. class); <br/> thread t = new thread (r); <br/> T. start (); </P> <p>}
In this way, Java can execute the dynamic language, but note that it is in JDK 1.6 ~