In this tutorial we are going to build a simple Veronica application that handles http cookies.

Here's a list of the required preliminary knowledge for this tutorial:

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

Moreover, it is recommended that you have a strong knowledge of how do http cookies work.
If you lack the preliminary knowledge, we advise you to go back to previous tutorials to get started.

Here's a list of the topics that we are going to cover in this tutorial:

  • Http cookies manipulation

We are going to create a simple "hit counter" application, that stores the amount of times that a user has visited our website before. Let's get started!

  1. First we need to define a simple route for our application
Route<Request, Response> route = Route.builder()
    .requestMatcher(get("/"))
    .requestHandler(req -> ok(Response.builder().build()))
    .build();
  1. We are now going to work within our route's RequestHandler:
Route<Request, Response> route = Route.builder()
    .requestHandler(req -> {

        Map<String, String> cookie = req.getCookie();

        int hitCounter = 0;

        if (cookie.containsKey("hit-counter")) {

            hitCounter = Integer.parseInt(cookie.get("hit-counter"));

        }

        return ok(Response.builder()
            .cookie(SetCookieHeader.builder()
                .name("hit-counter")
                .value(String.valueOf(hitCounter + 1))
                .build()
            )
            .body("You have visited this page " + hitCounter + " times before")
            .build());

    })
    .build();
  1. Now we build and start the application
Router<Request, Response> router = Router.builder()
  .fallbackRoute(route)
  .build();

int port = 8000;

Application<Request, Response> app = Application.basic()
  .port(port)
  .router(router)
  .build();
app.start();
  1. If you test the application with a normal web browser, you will notice that the counter increases by 2 instead of 1. That is because our web browser tries to download our website's favicon with every request. Therefore, we effectively perform two request per page load, which results in our hit counter increasing by 2. Let's try and fix that by creating a secondary route that catches this:
Router<Request, Response> router = Router.builder()
    .route(Route.builder()
        .requestMatcher(get("/favicon.ico"))
        .requestHandler(request -> ok(Response.builder())
            .body("")
            .httpStatus(HttpStatus.NOT_FOUND)
            .build()
        )
        .build()
    )
    .fallbackRoute(route)
    .build();