zoukankan      html  css  js  c++  java
  • java中使用Rhino执行js文件中的function

    参考资料

    Mozilla Rhino首页:
    http://www.mozilla.org/rhino/

    Rhino 下载
    Rhino 官方文档

    test.js

    function Transfer(content, baseurl)
    {
     //TODO
     var result = "";
     if(content.indexOf('<body>') > -1 && content.indexOf('</body>') > -1)
     {
         result = content.substring(content.indexOf('<body>') + 6,content.indexOf('</body>'));
     }
     return result;
    }

    java code

    @Test
     public void ExecuteJavascriptByRhino() throws BSFException, FileNotFoundException, IOException
     {
      
      String jsPath = "c:\\test.js";
            String jsFunction = "Transfer";
            String content = "<html><head><title>测试测试</title></head><body><div>aaaa</div>html body ,hahahaha ,垃圾</body></html>";
            String baseurl = "http://www.edzh.com";
           
            //开始调用javascript函数
            Context cx = Context.enter();
            try {
                Scriptable scope = cx.initStandardObjects();
                cx.evaluateReader(scope, new java.io.FileReader(jsPath), "<cmd>", 1, null);

                Object fObj = scope.get(jsFunction, scope);
                if (!(fObj instanceof Function)) {
                    System.out.println("找不到方法" +jsFunction);
                } else {
                    Object functionArgs[] = { content, baseurl};
                    Function f = (Function)fObj;
                    Object result = f.call(cx, scope, scope, functionArgs);
                    System.out.println("返回结果:"+Context.toString(result));
                }
            } finally {
                Context.exit();
            }
     }

  • 相关阅读:
    nano编辑器__vi常用命令
    pyCharm最新2018激活方式(记录)
    一、centos7.4安装docker
    C#备份及还原数据库的实现
    System.Drawing.image 与ImageSource 互转
    Socket 异步通信
    图片与base64的互转
    程序中编写log日志
    SQLHelper
    Cond
  • 原文地址:https://www.cnblogs.com/yesun/p/1134041.html
Copyright © 2011-2022 走看看