3

クライアント側でmarkedを使用して、マークダウンコードをhtmlにレンダリングしています。

しかし今、私はJavaであるサーバー側で同じことをする必要があります。まったく同じhtmlコードを取得するには、他のJavaマークダウンライブラリ以外のマークを使用する必要があります。

「marked.js」ファイルをJavaでロードし、JavaScriptコードを実行するにはどうすればよいですか?

marked.parser(marked.lexer("**hello,world**"));
4

3 に答える 3

4

2 つのオプション:

  1. チュートリアルをご覧ください。Rhino
  2. 次に、以下に再現されたRunScriptの例を参照して、Rhino を自分で埋め込みます。
  3. 次に、ニーズに合わせて編集します

また:

Rhino にバンドルされている Java SE 6 以降の内部 ScriptEngine を直接使用します。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 の答えに気付き、まったく同じように書いたでしょう ( Files.toString(File)Google Guava を使用して lib を直接ロードすることを除いて)。彼の回答を参照してください (回答が役に立った場合はポイントを与えてください)。

于 2012-07-12T04:13:30.003 に答える
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();
}
于 2012-07-12T04:13:31.657 に答える
1

rhinoを使用して、Java を実行するサーバーで JavaScript を実行できます。

于 2012-07-12T04:13:09.853 に答える