Execute JavaScript code directly in a JAVA program (simple invoke instance) __java

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.