[英]How to load a javascript file and run a javascript method in java?
2個選項:
要么:
直接使用Java SE 6及更高版本中的內部ScriptEngine,它與Rhino捆綁在一起。 請參閱下面根據您的需求調整的RunMarked
示例。
/*
* Licensed under MPL 1.1/GPL 2.0
*/
import org.mozilla.javascript.*;
/**
* RunScript: simplest example of controlling execution of Rhino.
*
* Collects its arguments from the command line, executes the
* script, and prints the result.
*
* @author Norris Boyd
*/
public class RunScript {
public static void main(String args[])
{
// Creates and enters a Context. The Context stores information
// about the execution environment of a script.
Context cx = Context.enter();
try {
// Initialize the standard objects (Object, Function, etc.)
// This must be done before scripts can be executed. Returns
// a scope object that we use in later calls.
Scriptable scope = cx.initStandardObjects();
// Collect the arguments into a single string.
String s = "";
for (int i=0; i < args.length; i++) {
s += args[i];
}
// Now evaluate the string we've colected.
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
// Convert the result to a string and print it.
System.err.println(Context.toString(result));
} finally {
// Exit from the context.
Context.exit();
}
}
}
實際上,我注意到了Freewind的答案 ,我寫的完全一樣(除了我使用Google Guava直接用Files.toString(File)
加載lib)。 請參考他的回答(如果你的答案有幫助,請給他分數)。
public static String md2html() throws ScriptException, FileNotFoundException, NoSuchMethodException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
File functionscript = new File("public/lib/marked.js");
Reader reader = new FileReader(functionscript);
engine.eval(reader);
Invocable invocableEngine = (Invocable) engine;
Object marked = engine.get("marked");
Object lexer = invocableEngine.invokeMethod(marked, "lexer", "**hello**");
Object result = invocableEngine.invokeMethod(marked, "parser", lexer);
return result.toString();
}
您可以使用rhino在運行java的服務器上運行JavaScript。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.