Isomorphic web apps – where the backend and frontend share the same code – are all the rage nowadays. With them, you render the page on the server with the same code which is used on the client. This gives the advantages of for example quickly loading pages, SEO, and less code.
But Spring hasn’t had the same kind of support for this technique as node.js, which made a user raise an issue here: https://jira.spring.io/browse/SPR-12266
This was picked up by Sébastien Deleuze, who then implemented support for Javascript templating to Spring MVC. There are still some things to improve, but as far as I can see they will be fixed quite soon.
Sébastien held a presentation where he showed a demo which really made me want to go home and try it out!
His solution supports not only Javascript rendering engines, but all JSR-223 engines: JRuby, Jython, Nashorn (Rhino is too slow to be useful for this)
What you have to do to get this to work is:
- define a bean of type ScriptTemplateViewResolver which points to your template directory
- define a ScriptTemplateConfigurer with the desired script engine (‘nashorn’, for example), and which scripts to load.
This makes Spring render the template using Nashorn and React (if you told it to load that script).
If you thought this was maybe a bit too little information, check out the slides and sample projects:
Isomorphic React application: https://github.com/sdeleuze/spring-react-isomorphic
…and another using Handlebars as template engine: https://github.com/sdeleuze/spring-boot-sample-web-handlebars
Slides:
https://speakerdeck.com/sdeleuze/isomorphic-templating-with-spring-boot-nashorn-and-react
The presentation was recorded, but hasn’t been uploaded yet. I’ll update this post when it is!