Hello World

In this first example we are going to build the simplest Veronica application possible, to demonstrate how to initialize the basic structure of your application.

Here's a list of the topics covered by this tutorial:

  • Basic application initialization
  • How to create a route
  • How to initialize the application router

Let's get started:

  1. First step, is to create a RequestHandler object:
import static rocks.gioac96.veronica.routing.pipeline.stages.RequestHandlerPayload.ok;
...
RequestHandler<Request, Response> helloWorldHandler = new RequestHandler<Request, Response>() {
    @Override
    public RequestHandlerPayload<Response> handle(Request request) {
        return ok(Response.builder()
            .body("Hello World")
            .build());
    }
};

The "ok" static method that we imported is nothing else than an helper method that makes our code look cleaner. You can find more about what exactly it does in the Pipeline tutorial, but as of now you should think of it as a simple helper method that we need to wrap around our RequestHander return value.
We can also use lambda expressions in order to make our code look cleaner:

RequestHandler<Request, Response> helloWorldHandler = request -> ok(Response.builder()
	  .body("Hello World")
    .build());
  1. Now we create our route, and assign the helloWorldHandler to it:
RequestHandler<Request, Response> helloWorldHandler = request -> Response.builder()
    .body("Hello World")
    .build();

Route<Request, Response> helloWorldRoute = Route.builder()
    .requestHandler(helloWorldHandler)
    .build();
  1. Now we are ready to create the application router, and set our route as the fallback route. This will set our route as the default one, and will ensure that it handles all incoming requests:
RequestHandler<Request, Response> helloWorldHandler = request -> ok(Response.builder()
    .body("Hello World")
    .build());

Route<Request, Response> helloWorldRoute = Route.builder()
    .requestHandler(helloWorldHandler)
    .build();

Router<Request, Response> router = Router.builder()
    .fallbackRoute(helloWorldRoute)
    .build();
  1. We are now ready for the last step, which is to build the Veronica application and assign a port to it:
RequestHandler<Request, Response> helloWorldHandler = request -> ok(Response.builder()
    .body("Hello World")
    .build());

Route<Request, Response> helloWorldRoute = Route.builder()
    .requestHandler(helloWorldHandler)
    .build();

Router<Request, Response> router = Router.builder()
    .fallbackRoute(helloWorldRoute)
    .build();

int port = 8000;

Application<Request, Response> app = Application.basic()
    .port(port)
    .router(router)
    .build();

app.start();

Et voilà! You have just created your first Veronica application. You can now start your application, and open this url in your browser to make sure that it works.