If you need to create your own server side controllers, eg to update data or perform specific transformations, or to build your own REST api, you can create those controllers with server side javascript. This is conceptually similar to NodeJs although without any threading limitations.
For more information on using javascript functions in your templates see here
Creating these is similar to creating custom apps. It involves
- Create a WEB-INF directory in your website
- Create a controllers.xml file inside the WEB-INF folder which lists the js files to load
- Create a js file which contains mappings of paths as regular expressions to js functions
- Create the js functions to handle requests
This shows you the folder structure to start with.
Here's the XML i used to load the JS source file:
/WEB-INF/app.js
And my very simple controller mapping and controller function look like this:
controllerMappings
.websiteController()
.path("/myController/")
.enabled(true)
.isPublic(true)
.addMethod("GET", "sayHelloWorld")
.build();
function sayHelloWorld(page, params, files) {
log.info("sayHelloWorld has been called");
return page.jsonResult(true, "Hello world!");
}
You can then request this URL from your web browser:
And you can verify from the logs that your controller is being processed:
Templates and other views
The example above uses a convenience method on the page object (a ControllerResource) to return a jsonResult. But to get access to the full range of views you should use the ViewsBuilder object which is the "views" variable.
To render a template:
return views.templateView("/theme/myTemplate.html")
To send a redirect:
return views.redirectView("/some/other/page");