2012-07-12 82 views
3

我在客戶端使用marked將markdown代碼呈現爲html。如何加載JavaScript文件並在java中運行javascript方法?

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

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

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

回答

4

2個選擇:

  1. 看一看的Rhinotutorial
  2. 然後參考RunScript示例,下面轉載並自己嵌入Rhino。
  3. 然後對其進行編輯,以滿足您的需求

OR:

直接使用內部的ScriptEngine在Java SE 6和更高版本中,自帶的犀牛捆綁你。請參閱下面的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's answer,我會寫一模一樣(除了我加載的lib直接與Files.toString(File)使用Google Guava)。請參考他的答案(如果你發現他的答案有幫助,請給他點數)。

0

您可以使用rhino在運行java的服務器上運行JavaScript。

2
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(); 
} 
+0

+1因爲我要爲我的答案的第二部分寫出類似的內容,而且您已經做得非常好。 – haylem 2012-07-12 04:39:26