-
Notifications
You must be signed in to change notification settings - Fork 11
RouterMiddleware
This guide will show you how to create routes for handling HTTP requests using the RouterMiddleware
.
There are three ways in which you can define your routes. The easiest is by using the methods get
, post
, etc. from the org.jogger.RouterMiddleware
class:
RouterMiddleware router = new RouterMiddleware();
router.get("/", new RouteHandler() {
@Override
public void handle(Request request, Response response) throws Exception {
// do something here
}
});
Jogger jogger = new Jogger(router);
jogger.listen();
Every time we receive GET
request to /
it will call the RouteHandler
instance. You can add as many routes as you want like this.
This method works great for small applications. However, if you have more than a couple routes it is much better to separate the route definition from the route logic. Consider the following class that will act as a controller of multiple routes:
public class Users {
public void index(Request request, Response response) {
// list the users
}
public void newForm(Request request, Response response) {
// show the form for creating a user
}
public void create(Request request, Response response) {
// create the user
}
...
}
We can now define the routes as follows:
Users users = new Users();
RouterMiddleware router = new RouterMiddleware();
router.addRoute(HttpMethod.GET, "/users", users, "index"); // list users
router.addRoute(HttpMethod.GET, "/users/new", users, "newForm"); // new user form
router.addRoute(HttpMethod.POST, "/users", users, "create"); // create user
...
A controller is just a Java class that has a public default constructor (i.e. no constructor specified or a constructor with no arguments) and an action is just a Java method that receives two arguments: a org.jogger.http.Request
and a org.jogger.http.Response
.
You can also use an external file to define your routes:
FileSystemRoutesLoader routesLoader = new FileSystemRoutesLoader("routes.config");
routesLoader.setBasePackage("com.mycompany.controllers"); // we don't want to repeat this for each controller
RouterMiddleware router = new RouterMiddleware();
router.setRoutes(routesLoader.load());
The routes.config file looks like this:
GET / Pages#index
GET /users Users#index
GET /users/new Users#newForm
POST /users Users#create
DELETE /users/{id} Users#delete
...
Path variables allow you to define routes with holders such as:
GET /users/{userId} Users#show
{userId}
acts as a holder that will match paths like /users/1
or /users/[email protected]
. You can retrieve path variables from you controllers using the org.jogger.http.Request#getPathVariable(String)
method:
public class Users {
public void show(Request request, Response response) {
long userId = request.getPathVariable("userId").asLong();
// retrieve the user and do your stuff
}
}