Request Handling

Implement the logic to handle requests to WebServer in a Handler, which is a FunctionalInterface. Handlers:

  • Process the request and send a response.

  • Act as a filter and forward requests to downstream handlers using the request.next() method.

  • Throw an exception or call request.next(exception) to begin error handling.

Process Request and Produce Response

Each Handler has two parameters. ServerRequest and ServerResponse.

  • Request provides access to the request method, URI, path, query parameters, headers and entity.

  • Response provides an ability to set response code, headers, and entity.

Handler as a Filter

The handler forwards the request to the downstream handlers by nexting. There are two options:

  • call req.next()

    .any("/hello", (req, res) -> { 
        // filtering logic  
        req.next(); 
    })
    Copied
    • handler for any HTTP method using the /hello path
    • business logic implementation
    • forward the current request to the downstream handler
  • call req.next(throwable) to forward the handling to the error handlers

    .any("/hello", (req, res) -> { 
        // filtering logic (e.g., validating parameters) 
        if (userParametersOk()) {
            req.next(); 
        } else {
            req.next(new IllegalArgumentException("Invalid parameters."); 
        }
    })
    Copied
    • handler for any HTTP method using the /hello path
    • custom logic
    • forward the current request to the downstream handler
    • forward the request to the error handler

The handling logic can explicitly forward the execution to a different thread. This is the reason why returning from the handler can’t automatically trigger calling the next handler.

Sending a response

To complete the request handling, you must send a response by calling the res.send() method.

.get("/hello", (req, res) -> { 
    // terminating logic
    res.status(Http.Status.ACCEPTED_201);
    res.send("Saved!"); 
})
Copied
  • handler that terminates the request handling for any HTTP method using the /hello path
  • send the response