Class HttpHandlers

java.lang.Object
com.sun.net.httpserver.HttpHandlers

public final class HttpHandlers extends Object
Implementations of HttpHandler that implement various useful handlers, such as a static response handler, or a conditional handler that complements one handler with another.

The factory method of(int, Headers, String) provides a means to create handlers with pre-set static response state. For example, a jsonHandler that always returns 200 with the same json:


    HttpHandlers.of(200,
                    Headers.of("Content-Type", "application/json"),
                    Files.readString(Path.of("some.json")));
 
or a notAllowedHandler that always replies with 405 - Method Not Allowed, and indicates the set of methods that are allowed:

    HttpHandlers.of(405, Headers.of("Allow", "GET"), "");
 

The functionality of a handler can be extended or enhanced through the use of handleOrElse, which allows to complement a given handler. For example, complementing a jsonHandler with notAllowedHandler:


    Predicate<Request> IS_GET = r -> r.getRequestMethod().equals("GET");
    var handler = HttpHandlers.handleOrElse(IS_GET, jsonHandler, notAllowedHandler);
 
The above handleOrElse handler offers an if-else like construct; if the request method is "GET" then handling of the exchange is delegated to the jsonHandler, otherwise handling of the exchange is delegated to the notAllowedHandler.

Since:
18