Home > Java > javaTutorial > body text

How Java calls JavaScript scripts

王林
Release: 2023-04-14 23:13:06
forward
1733 people have browsed it

有些情况下,需要java去调用js,groovy等脚本语言,传入参数获取脚本运行的结果。

js脚本例子:

function add(a,b){    return a + b + number; 
}
Copy after login

java代码的例子:

import java.io.FileReader;import java.util.Scanner;  
import javax.script.Bindings;import javax.script.Invocable;import javax.script.ScriptContext;import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;  
public class ExecuJs {    public static void main(String[] args) throws Exception {  
        // 获取JS执行引擎
        ScriptEngine se = new ScriptEngineManager().getEngineByName("javascript");        // 获取变量
        Bindings bindings = se.createBindings();
        bindings.put("number", 3);
        se.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        Scanner sc = new Scanner(System.in);        while (sc.hasNextInt()) {            int a = sc.nextInt();            int b = sc.nextInt();
            System.out.println("输入的参数【" + a + "】 + 【" + b + "】");
            se.eval(new FileReader("D:\\desk\\test.js"));            // 是否可调用
            if (se instanceof Invocable) {
                Invocable in = (Invocable) se;
                Integer result = (Integer) in.invokeFunction("add", a, b);
                System.out.println("获得的结果:" + result);                 
            }  
        }<br>        }
}
Copy after login

出于安全的考虑,最好是把js脚本中的内容先读取出来。判断内容中不能包含文件操作如move,delete等,不能执行activex等。

这里边还有一个小的技巧。

(Integer) in.invokeFunction("add", a, b),这里的add是js脚本的方法名子,a和b是参数。invokeFunction方法第二个参数是可变参数,如果我们写了一个通用方法,参数的个数也是不确定的,是由外部传入的。怎么才能把外部传入的参数作为invokeFunction的可变参数呢?

可变参数本质上就是数组,我们可以把外部传入的参数组成一个object数组,作为invokeFunction的可变参数传入即可。

import java.util.Arrays; 
public class Main { 
    public static void f(int... is ) {
        System.out.println(Arrays.toString(is));
    }     
    public static void g(int[] is) {
        System.out.println(Arrays.toString(is));
    }     
    public static void main(String... args) {        //可以把String[] 变成String...
        int[] a = new int []{1,2,3,4};
        f(1,2,3,4);
        f(a);
        g(a);
    } 
}
Copy after login

运行的结果是一样的。

The above is the detailed content of How Java calls JavaScript scripts. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!