Weitere ähnliche Inhalte
Ähnlich wie Java + React.jsでSever Side Rendering #reactjs_meetup (20)
Mehr von Toshiaki Maki (20)
Java + React.jsでSever Side Rendering #reactjs_meetup
- 6. 私とServer Side Rendering
• SPAでブログ作った!
Backend
API
(Java)
Frontend
SPA
(Backbone.js)
Backend
SPA
(Backbone.js)
REST API
REST API
http://blog.ik.am
https://github.com/making/categolj2-backend
- 16. JavaScript Engine in Java
• ScriptEngine API (JSR-223)
• Java SE 6, 7 … Rhino
• Java SE 8 … Nashorn
- 17. JavaScript Engine in Java
• ScriptEngine API (JSR-223)
• Java SE 6, 7 … Rhino
• Java SE 8 … Nashorn
JavaとJavaScriptの関係は
インドとインドネシア
の関係ほど単純じゃない
- 18. ScriptEngine
ScriptEngineManager engineManager =
new ScriptEngineManager();
ScriptEngine engine =
engineManager.getEngineByName("js");
engine
.eval("function sum(a,b){return a + b;}");
System.out.println(engine.eval("sum(1,2);"));
// 3
http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
- 20. React.js側のコード
window.renderOnClient = function (initialData) {
React.render(
<App data={initialData} />,
document.getElementById('content')
);
};
window.renderOnServer = function (initialData) {
//initialData = Java.from(initialData); Listの場合
return React.renderToString(
<App data={initialData} />
);
};
- 21. React.js側のコード
var App = React.createClass({
render: function () {
return (
<div>
<h1>React.js</h1>
<Greet
data={this.props.data} />
</div>
);
}
}); サーバーサイドで用意さ
れたデータが渡される
- 22. React.js側のコード
var Greet = React.createClass({
getInitialState: function () {
return this.props.data ||
{id: 0, content: 'Now Loading...'};
},
// …
});
getInitialState()でサーバー
で用意したデータを返す
- 23. サーバーサイド// JSONマッパー
ObjectMapper objectMapper = new ObjectMapper();
// ScriptEngineのラッパー
ScriptEngine engine = new JavaScriptEngine()
.polyfill()
.load("static/bundle.js")
.get();
@RequestMapping("/")
String index(Model model) throws Exception {
Greet initialData = new Greet(100, "Data on Server");
Object markup = ((Invocable) engine)
.invokeFunction("renderOnServer", initialData);
model.addAttribute("markup", markup);
model.addAttribute("initialData",
objectMapper.writeValueAsString(initialData));
return "index";
}
- 24. HTMLテンプレート
(Thymeleaf)
<body>
<div id="content" th:utext="${markup}"></div>
<script src="bundle.js"></script>
<script type="text/javascript"
th:inline="javascript">
document.addEventListener("DOMContentLoaded", function () {
var initialData = JSON.parse(/*[[${initialData}]]*/
'{"id": -1, "content": "モックデータ"}');
renderOnClient(initialData);
}, false);
</script>
</body> エンジン経由だとコメントの中身が評価される
テンプレートを直で開くとコメントの後ろが評価さ
れるので、フロントエンドに閉じて開発可能!
サーバーで生成した
HTMLを埋め込む