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

javascript脚本怎么运行(js脚本编写教程)

程序员文章站 2023-11-24 21:25:22
1 概述本文介绍在 java 环境中执行 javascript 脚本的简单使用,具体包含以下内容java 8 中的内置 nashorn javascript 引擎介绍rhino javascript...

1 概述

本文介绍在 java 环境中执行 javascript 脚本的简单使用,具体包含以下内容

  1. java 8 中的内置 nashorn javascript 引擎介绍
  2. rhino javascript 引擎介绍以及对 xml 的处理介绍

2 java 8 中的内置 nashorn javascript 引擎介绍

nashorn 是 java 8 中内置的 javascript 引擎,无需加入任何依赖。

nashorn 基本使用步骤如下

  1. new 出 scriptenginemanager 对象
  2. 通过 scriptenginemanager 对象中的 getenginebyname 方法获取指定的 javascript 引擎,返回 scriptengine 对象
  3. java 8 中的默认的 javascript 引擎包括:[nashorn, nashorn, js, js, javascript, javascript, ecmascript, ecmascript]
  4. 通过 scriptengine 对象的 eval 方法来执行 javascript 脚本。

2.1 通过 printwriter 对象获取脚本中的 print 输出

javascript 脚本中没有函数,没有返回值,通过 print 输出内容,这时需要通过 printwriter 获取读取脚本中的 print 输出,具体如下

@test
    public void test_nashorn() {
        try {
            scriptengine engine = new scriptenginemanager().getenginebyname("nashorn");
            scriptcontext scriptcontext = engine.getcontext();
            stringwriter stringwriter = new stringwriter();
            printwriter printwriter = new printwriter(stringwriter);
            scriptcontext.setwriter(printwriter);

            string jsstring = "var obj=json.parse('{\\\"data\\\":\\\"7155\\\",\\\"sign\\\":\\\"success\\\",\\\"message\\\":null}');print(obj.sign==\"success\");";

            stringwriter = new stringwriter();
            printwriter = new printwriter(stringwriter);
            scriptcontext.setwriter(printwriter);
            engine.eval(jsstring);
            system.out.println(string.format("1 result = %s",stringwriter.tostring()));

            jsstring = "var obj=json.parse('{\\\"data\\\":\\\"7157\\\",\\\"sign\\\":\\\"success\\\",\\\"message\\\":null}');print((function getdata() {  return obj.data;})())";
            stringwriter = new stringwriter();
            printwriter = new printwriter(stringwriter);
            scriptcontext.setwriter(printwriter);
            engine.eval(jsstring);
            system.out.println(string.format("2 result = %s",stringwriter.tostring()));

            jsstring = "var obj=json.parse('{\\\"data\\\":\\\"7157\\\",\\\"sign\\\":\\\"success\\\",\\\"message\\\":null}');print((function getdata() {  return obj.data;})())";
            stringwriter = new stringwriter();
            printwriter = new printwriter(stringwriter);
            scriptcontext.setwriter(printwriter);
            engine.eval(jsstring);
            system.out.println(string.format("3 result = %s",stringwriter.tostring()));
        } catch (exception e) {
            e.printstacktrace();
        }
    }

2.2 获取匿名函数的返回值

javascript 脚本是一个匿名函数并且有返回值,通过 eval 函数可以直接

@test
public void test_js_function_return() {
    try {
        scriptengine engine = new scriptenginemanager().getenginebyname("nashorn");
        string jsfunction = "(function(){var obj=json.parse('{\\\"data\\\":\\\"7155\\\",\\\"sign\\\":\\\"success\\\",\\\"message\\\":null}');return obj.sign==\"success\"})();";
        boolean result = (boolean) engine.eval(jsfunction);
        system.out.println(result);
    } catch (exception e) {
        e.printstacktrace();
    }
}

2.3 调用 javascript 脚本中指定的函数

javascript 脚本中有变量,有多个函数,具体如下

@test
public void test_invoke_js_function() {
    try {
        scriptengine engine = new scriptenginemanager().getenginebyname("nashorn");
        /*
        var obj = json.parse('{\"data\":\"7155\",\"sign\":\"success\",\"message\":null}');
        function checksign() {
            return obj.sign == 'success'
        }
        function getdata() {
            return obj.data
        }
        function calculate(a, b) {
            return a + b
        }
         */
        string jsfunction = "var obj=json.parse('{\\\"data\\\":\\\"7155\\\",\\\"sign\\\":\\\"success\\\",\\\"message\\\":null}');function checksign(){return obj.sign=='success'}function getdata(){return obj.data}function calculate(a,b){return a+b}";

        engine.eval(jsfunction);
        invocable invocable = (invocable) engine;

        object result = invocable.invokefunction("checksign", null);
        system.out.println(result);

        result = invocable.invokefunction("getdata", null);
        system.out.println(result);

        result = invocable.invokefunction("calculate", 2, 5);
        system.out.println(result);
    } catch (exception e) {
        e.printstacktrace();
    }
}
  • 输出如下
true
7155
7.0

2.4 读取 javascript 文件并执行

这种情况是读取 javascript 文件,并执行,具体如下

  • src/test/resources/test.js
@test
public void test_invoke_js_file() {
    try {
        scriptengine engine = new scriptenginemanager().getenginebyname("nashorn");
        engine.eval(new filereader(testjsengine.class.getresource("/test.js").getpath()));
        invocable invocable = (invocable) engine;

        object result = invocable.invokefunction("checksign", null);
        system.out.println(result);

        result = invocable.invokefunction("getdata", null);
        system.out.println(result);

        result = invocable.invokefunction("calculate", 2, 5);
        system.out.println(result);
    } catch (exception e) {
        e.printstacktrace();
    }
}

文件内容和上面一样。

3 rhino javascript 引擎介绍

默认的 nashorn 引擎是无法解析 xml 的,像 domparser 这样的对象是浏览器内置的组件。

这里可以通过 maven 依赖 rhino 引擎来处理 xml。

  • rhino maven 依赖如下
<dependency>
  <groupid>cat.inspiracio</groupid>
  <artifactid>rhino-js-engine</artifactid>
  <version>1.7.10</version>
</dependency>

使用的步骤和其他 javascript 引擎一样,引擎的名称为 rhino.

3.1 rhino 对 xml 的解析

这里通过读取文件的方式来加载和解析 javascript 脚本,脚本中是对一段 xml 的解析的过程。

  • src/test/resources/xml.js 文件内容如下
print("----------------------------------------");
var e = new xml('<employees> <employee id="1"><name>joe</name><age>20</age></employee> <employee id="2"><name>sue</name><age>30</age></employee>  </employees>');
// 获取所有的员工
print("获取所有的员工:\n" + e..name);
// 名字叫 joe 的员工
print("名字叫 joe 的员工:\n" + e.employee.(name == "joe"));
// 员工的id 为 1 和 2
print("员工的id 为 1 和 2:\n" + e.employee.(@id == 1 || @id == 2));
// 员工的id 为 1
print("员工的id 为 1: " + e.employee.(@id == 1).name);
print("----------------------------------------");
  • 执行如下
@test
public void test_rhino_file_js() {
    try {
        scriptengine engine = new scriptenginemanager().getenginebyname("rhino");

        scriptcontext scriptcontext = engine.getcontext();

        stringwriter stringwriter = new stringwriter();
        printwriter printwriter = new printwriter(stringwriter);
        scriptcontext.setwriter(printwriter);
        engine.eval(new filereader(testjsengine.class.getresource("/xml.js").getpath()));

        system.out.println(string.format("xml result = %s",stringwriter.tostring() ));

    } catch (exception e) {
        e.printstacktrace();
    }
}
  • 输出如下
xml result = ----------------------------------------
all the employee names are:
<name>joe</name>
<name>sue</name>
the employee named joe is:
<employee id="1">
  <name>joe</name>
  <age>20</age>
</employee>
employees with ids 1 & 2:
<employee id="1">
  <name>joe</name>
  <age>20</age>
</employee>
<employee id="2">
  <name>sue</name>
  <age>30</age>
</employee>
name of the the employee with id=1: joe
----------------------------------------

3.2 测试

  • xml 内容如下
<ccardprocesssyncresponse>
    <retcode>0</retcode>
    <message>操作成功!</message>
    <refundcycle />
    <epayrefundcyclemin>1</epayrefundcyclemin>
    <epayrefundcyclemax>7</epayrefundcyclemax>
    <epayrefundcycleunitf />
</ccardprocesssyncresponse>
  • 具体测试如下
@test
public void test_rhino() {
    try {
        scriptengine engine = new scriptenginemanager().getenginebyname("rhino");

        string jsstring = jsstring = "var obj=new xml('<ccardprocesssyncresponse>    <retcode>0</retcode>    <message>操作成功!</message>    <refundcycle />    <epayrefundcyclemin>1</epayrefundcyclemin>    <epayrefundcyclemax>7</epayrefundcyclemax>    <epayrefundcycleunitf />  </ccardprocesssyncresponse>');print(obj.message == '操作成功!');";
        scriptcontext scriptcontext = engine.getcontext();

        stringwriter stringwriter = new stringwriter();
        printwriter printwriter = new printwriter(stringwriter);
        scriptcontext.setwriter(printwriter);
        engine.eval(jsstring);

        system.out.println(string.format("xml result = %s",stringwriter.tostring() ));

    } catch (exception e) {
        e.printstacktrace();
    }
}

上面的输出结果如下

xml result = true