簡體   English   中英

如何加載javascript文件並在java中運行javascript方法?

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

我在客戶端使用標記來將標記代碼渲染為html。

但是現在我需要在Java服務器端做同樣的事情。 為了獲得完全相同的html代碼,我必須使用標記以外的其他java markdown庫。

如何在java中加載“marked.js”文件並運行javascript代碼?

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

2個選項:

  1. 看看Rhino 教程
  2. 然后參考下面轉載的RunScript示例並自己嵌入Rhino。
  3. 然后編輯它以滿足您的需求

要么:

直接使用Java SE 6及更高版本中的內部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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM