Using controllers
In the Getting Started section you've learned how to set up a simple http server and map your first route. With a lot of routes this can get quite messy really quickly though so it's better to organize your request handlers in so called controllers. To create your first controller you can start by creating a simple class. Now you can write one or more handler methods which can optionally receive different arguments (more on this later). To bind routes to those method you can add the @Get
, @Post
, ... annotations to your methods. Then register the controller on your http server instance.
public class HelloWorldController {
@Get
public String helloWorld() {
return "Hello World!";
}
}
public class ExampleApp {
public static void main(String[] args) {
HTTPServer server = new HTTPServer().port(8080);
server.controller(new HelloWorldController());
server.start().join();
}
}
After restarting the app and reloading the page you should still see the "Hello World!" text.
Parameter injection
As explained previously controller methods can take several arguments. The simplest one is the Exchange
that you already know from the previous chapter but there are few more options you can inject using @Body
, @Query
, @Path
(for path parameters), @Attrib
, etc. The order of the parameters doesn't matter and the server will try to guess the correct value based on the type and annotations. If it can't guess a value for the parameter, it will fall back to null.
public class EchoController {
@Post("/echo")
public String echo(@Body String body) {
return body;
}
}
Registration using package scanning
When the project becomes larger you will probably have quite a few controllers and registering each controller manually will take quite a few lines and you'll probably forget about it every now and then. To make your life easier there is an option to automatically scan a package for controllers. This method requires all your controllers to have a common parent class. Then you can simply provide the parent class and the package you want to scan and all controllers will be registered automatically.
public abstract class Controller {
// optionally add some helpers
}
public class ExampleController extends Controller {
// Your controller methods
}
public class ExampleApp {
public static void main(String[] args) {
HTTPServer server = new HTTPServer().port(8080);
server.controller(Controller.class, Controller.class.getPackage());
server.start().join();
}
}
Learn more about controllers in this section.