我正在客户端使用marked来将Markdown代码渲染为HTML。
但现在我需要在Java的服务器端实现同样的功能。为了得到完全相同的HTML代码,我必须使用marked而不是其他Java Markdown库。
我该如何加载"marked.js"文件并运行其中的Javascript代码?
marked.parser(marked.lexer("**hello,world**"));
我正在客户端使用marked来将Markdown代码渲染为HTML。
但现在我需要在Java的服务器端实现同样的功能。为了得到完全相同的HTML代码,我必须使用marked而不是其他Java Markdown库。
我该如何加载"marked.js"文件并运行其中的Javascript代码?
marked.parser(marked.lexer("**hello,world**"));
有两个选项:
或者:
直接使用Java SE 6及更高版本中附带的内部脚本引擎,该引擎已为您捆绑了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)
加载库)。如果你发现他的回答有帮助,请参考他的回答并给他点赞。
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();
}