如何加载javascript文件并在java中运行javascript方法

How to load a javascript file and run a javascript method in java?

本文关键字:javascript java 运行 方法 文件 加载 何加载      更新时间:2023-09-26

我在客户端使用标记将markdown代码呈现为html。

但现在我需要在Java服务器端做同样的事情。为了获得完全相同的html代码,我必须使用标记的其他java标记库。

如何在java中加载"marked.js"文件并运行javascript代码?

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

2个选项:

  1. 请参阅Rhino教程
  2. 然后参考下面复制的RunScript示例,并自己嵌入Rhino
  3. 然后根据您的需要进行编辑

或:

在JavaSE6及更高版本中直接使用内部ScriptEngine,它与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)加载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。