如何在Java中加载JavaScript文件并运行JavaScript方法?

3

我正在客户端使用marked来将Markdown代码渲染为HTML。

但现在我需要在Java的服务器端实现同样的功能。为了得到完全相同的HTML代码,我必须使用marked而不是其他Java Markdown库。

我该如何加载"marked.js"文件并运行其中的Javascript代码?

marked.parser(marked.lexer("**hello,world**"));
3个回答

4

有两个选项:

  1. 查看Rhino教程
  2. 参考RunScript示例,并自行嵌入Rhino。
  3. 然后根据您的需求进行编辑。

或者:

直接使用Java SE 6及更高版本中附带的内部脚本引擎,该引擎已为您捆绑了Rhino。请参见下面适应您需求的RunMarked示例。


RunScript.java

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

RunMarked.java

我注意到了Freewind的回答,实际上我会写同样的内容(除了我会使用Google Guava直接Files.toString(File)加载库)。如果你发现他的回答有帮助,请参考他的回答并给他点赞。


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

+1 因为我正要写类似于我的答案的第二部分,而你已经出色地完成了它。 - haylem

1

您可以使用犀牛在运行Java的服务器上运行JavaScript。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接