Web浏览器上Java,ReactJS代码的服务器端渲染

Server-side rendering of Java, ReactJs code on a web browser

本文关键字:服务器端 代码 ReactJS 浏览器 Java Web      更新时间:2023-09-26

我需要做什么才能在浏览器上呈现它?下面的代码目前在 Eclipse 控制台上工作和渲染。我需要将此代码与像 Tomcat 这样的服务器一起使用,并在带有本地主机的浏览器上显示它。请指教。

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.");
    }
}

有很多可能性。一个非常常用的是使用REST服务。您可以使用 JAX-RS 或 Spring REST 支持来托管 REST 服务。将您的网页作为简单的 html 页面。加载此页面后,它将进行 REST 调用,获取数据并将其显示给用户。

你可以使用 JSP 来做到这一点。

创建一个 JSP 页。导入测试类。

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