2016-03-04 26 views
0

我需要做什麼才能在瀏覽器上呈現此代碼?下面的代碼目前在Eclipse Console上工作並呈現。我需要將這些代碼與Tomcat等服務器一起使用,並使用localhost將其顯示在瀏覽器上。請指教。Web瀏覽器上的Java ReactJs代碼的服務器端渲染

import javax.script.ScriptEngine; 
import javax.script.ScriptEngineManager; 
import java.io.FileReader; 
public class Test { 
    private ScriptEngine se; 
    // Constructor, sets up React and the Component 
    public Test() throws Throwable { 
     ScriptEngineManager sem = new ScriptEngineManager(); 
     se = sem.getEngineByName("nashorn"); 
     // React depends on the "global" variable 
     se.eval("var global = this"); 
     // eval react.js 
     se.eval(new FileReader("../react-0.14.7/build/react.js")); 
     // This would also be an external JS file 
     String component = 
      "var MyComponent = React.createClass({" + 
      " render: function() {" + 
      "  return React.DOM.div(null, this.props.text)" + 
      " }" + 
      "});"; 
     se.eval(component); 
    } 
    // Render the component, which can be called multiple times 
    public void render(String text) throws Throwable { 
     String render = 
      "React.renderToString(React.createFactory(MyComponent)({" + 
      // using JSONObject here would be cleaner obviously 
      " text: '" + text + "'" + 
      "}))"; 
     System.out.println(se.eval(render)); 
    } 
    public static void main(String... args) throws Throwable { 
     Test test = new Test(); 
     test.render("I want to Display"); 
     test.render("This on a Browser like google chrome, using Tomcat server with Eclipse, currently it displays on Console in Eclipse."); 
    } 
} 
+0

從哪裏java進入這張照片。請解釋。您可以在後端使用java來生成/處理Json格式的數據。 – WitVault

+0

我在Eclipse IDE上運行該代碼。 這裏是我在Eclipse控制檯上運行上述代碼的結果

I want to Display
This on a Browser like google chrome, using Tomcat server with Eclipse, currently it displays on Console in Eclipse.
mayorsanmayor

回答

1

有許多可能性。一個相當常用的將是去REST服務。您可以使用JAX-RS或Spring REST支持託管REST服務。把你的網頁作爲一個簡單的html頁面。一旦這個頁面被加載,它將進行REST調用,將獲取數據並將其顯示給用戶。

+0

這完全回答了我的問題,我個人認爲這是正確的路要走。謝謝@Akshay – mayorsanmayor

0

您可以使用JSP來做到這一點..

創建一個JSP頁面。導入測試類。

您可以檢查http://www.tutorialspoint.com/articles/run-your-first-jsp-program-in-apache-tomcat-server以瞭解如何使用JSP。

+0

謝謝,但我不想使用JSP,由於ReactJs用於頁面呈現,JSP是舊的並且在DOM操作和頁面呈現方面有限, ReactJs已經有助於無縫操作HTML DOM。在瀏覽器上顯示的方法是我正在尋找的解決方案。 ReactJs + Java + Tomcat + HTML + Bootstrap CSS看起來像是一個可行或可行的解決方案,但是如何?我想我必須搜索更多。 – mayorsanmayor

+1

僅用於測試目的還是在生產中運行?您可以使用Jetty/Glassfish。在這兩種情況下,您都應該擁有Java EE特性。 https://blog.idrsolutions.com/2015/04/top-10-open-source-java-and-javaee-application-servers/ – Vivasaayi