欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java中执行javascript案例

程序员文章站 2022-04-14 18:06:42
Nashorn js engine官方文档 https://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/#top java函数输出js的hello world: 调用文件里的js脚本: ......

nashorn js engine官方文档 
 

 

java函数输出js的hello world:

import javax.script.invocable;
import javax.script.scriptengine;
import javax.script.scriptenginefactory;
import javax.script.scriptenginemanager;
import javax.script.scriptexception;
public class maub {
    public static void main(string args[]) throws scriptexception, nosuchmethodexception{
        //引擎管理器
        scriptenginemanager m = new scriptenginemanager();
        //获取引擎
        scriptengine engine = m.getenginebyname("javascript");
        //执行javascript代码
        engine.eval("function hello(name){print('hello '+name)}");
        //javascript实现了invocable调用接口
        invocable inv = (invocable) engine;
        //调用函数hello,传入world
        inv.invokefunction("hello","world");
    }
}

调用文件里的js脚本:

import java.io.filenotfoundexception;
import javax.script.invocable;
import javax.script.scriptengine;
import javax.script.scriptenginefactory;
import javax.script.scriptenginemanager;
import javax.script.scriptexception;
public class maub {
    public static void main(string args[]) throws scriptexception, nosuchmethodexception, filenotfoundexception{//引擎管理器
        scriptenginemanager m = new scriptenginemanager();
        //获取引擎
        scriptengine engine = m.getenginebyname("javascript");
        //执行javascript代码
        engine.eval(new java.io.filereader("e:\\code\\java\\src\\getpwd.js"));
        
        invocable inv = (invocable) engine;
        string arg[] = {"mdwwdqyjkozihvcnaqebbqadkwaw","fot123456"};
        //使用invocable调用脚本函数,传入string参数
        system.out.println(inv.invokefunction("getpwd",arg));
    }
}