The route file is the entry point of every HTTP request. Somehow there must be mapping between a URL like /index.html or /person.json to something inside your application that actually does something. And that is defined in the route file.
By conventions every Ninja application contains the following
Java file: conf/Routes.java
.
Routes.java
contains all the routes for your application.
A minimal route file looks like:
public class Routes implements ApplicationRoutes { @Override public void init(Router router) { router.GET().route("/").with(ApplicationController::index); } }
This just means that a request to /
will be handled by a class called
ApplicationController
and its method index
.
… but how does that ApplicationController
look like?
Controllers are just simple Java classes and should be placed under the package
controllers
.
package controllers; @Singleton public class ApplicationController { public Result index() { return Results.html(); } }
Controller methods always return a Result
.
Results
(with “s” at the end) is just
a little helper that lets you create results easily.
In the case of the application controller the result is an HTML response.
Now we got one side of the equation - from Ninja to the routes to our controller. But how does Ninja generate the HTML ouput?
Views are declared inside package views
.
By convention views for controllers are always stored in
views/CONTROLLER_NAME/METHOD_NAME
.
In our case the view will be retrieved from
views/ApplicationController/index.ftl.html
.
A really simple view can look like:
<html> <body> <h1>Hello world</h1> </body> </html>
This is the basic concept of Ninja, and this is all you need to start your own
application. The basic flow of operations of Ninja is always Route => Controller => View
.
Of course views can not only render HTML, but also JSON or XML. And you can of course render models with your views. More about that in the following sections of the documentation.