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