java中使用Rhino执行js文件中的function

本文介绍如何在Java中使用Mozilla Rhino引擎执行JavaScript文件中的函数,并提供了一个具体示例,展示了如何调用名为Transfer的JS函数。
参考资料

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();
        }
 }

posted on 2008-04-02 09:51 夜隼 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/yesun/archive/2008/04/02/1134041.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值