JavaScript controllers

2019-10-08 19:46:00.0

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

  1. Create a WEB-INF directory in your website
  2. Create a controllers.xml file inside the WEB-INF folder which lists the js files to load
  3. Create a js file which contains mappings of paths as regular expressions to js functions
  4. 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:



And my very simple controller mapping and controller function look like this:

        .addMethod("GET", "sayHelloWorld")

function sayHelloWorld(page, params, files) {"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");