Example of Java calling Javascript functions

Source: Internet
Author: User

After Java 7, you can call functions in JavaScript in Java code, see the following example:

 PackageCom.lee;Importjava.io.FileNotFoundException;ImportJava.io.FileReader;ImportJava.util.Scanner;Importjavax.script.Bindings;Importjavax.script.Invocable;ImportJavax.script.ScriptContext;ImportJavax.script.ScriptEngine;ImportJavax.script.ScriptEngineManager;Importjavax.script.ScriptException;/** * * @authorLiyanxue*/ Public classJavainvokejs { Public Static voidMain (string[] args)throwsFileNotFoundException, Scriptexception, nosuchmethodexception {scriptengine engine=NewScriptenginemanager (). Getenginebyname ("JavaScript" ); Bindings Bind=engine.createbindings (); Bind.put ("Factor", 0); Engine.setbindings (Bind, ScriptContext.        Engine_scope); //Input Mode        /*Scanner input = new Scanner (system.in);         while (Input.hasnextint ()) {int first = Input.nextint ();         int second = Input.nextint ();         SYSTEM.OUT.PRINTLN ("Input parameters are:" + First + "," + second);         Engine.eval (New FileReader ("/users/liyanxue/model.js"));         if (engine instanceof invocable) {invocable in = (invocable) engine;         Executes the JS function Double result = (double) in.invokefunction ("formula", first, second);         SYSTEM.OUT.PRINTLN ("The result of the operation is:" + result.intvalue ()); }         }         */        intFirst = 23; intSecond = 7; System. Out.println ("The input parameters are:" + First + "," +second); Engine.eval (NewFileReader ("/users/liyanxue/model.js" )); if(Engineinstanceofinvocable) {invocable in=(invocable) engine; //Execute the JS functionDouble result = (double) in.invokefunction ("formula", first, second); System. Out.println (The result of the operation is: "+Result.intvalue ()); }    }} 

The code in/users/liyanxue/model.js:

function formula (VAR1, var2) {     return var1 + var2 +

Example of Java calling Javascript functions

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.