您的位置:首页 > 编程语言 > Java开发

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

2008-04-02 09:51 531 查看
参考资料
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();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: