参考资料
test.js
function Transfer(content, baseurl)
{
//TODO
var result = "";
if(content.indexOf('
') > -1 && content.indexOf('') > -1){
result = content.substring(content.indexOf('
') + 6,content.indexOf(''));}
return result;
}
java code
@Test
public void ExecuteJavascriptByRhino() throws BSFException, FileNotFoundException, IOException
{
String jsPath = "c:\\test.js";
String jsFunction = "Transfer";
String content = "
测试测试String baseurl = "http://www.edzh.com";
//开始调用javascript函数
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
cx.evaluateReader(scope, new java.io.FileReader(jsPath), "", 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();
}
}