Getting Started

Project Setup

Start by creating a new java project using the tools and project structure of your liking and add the libraries as explained in Installation. At the moment we only officially support JDK 8 but most of the features should run on JDK 9+ aswell so you can try this on your own risk.

Next create a main class for your application. Inside the main method you can simply create a new instance of the HTTPServer, optionally set a port (default is 80) and start the server.

public class ExampleApp {

    public static void main(String[] args) {
        HTTPServer server = new HTTPServer().port(8080);
        server.start(); // Starts the server
        server.join();  // Joins the server thread
    }

}

After compiling and starting this application you can visit http://localhost:8080 using your favourite browser and should see a "Page not found!" page. Congratulations, you've started your first http server!

Hello World

That's all cool but a webserver that only serves 404 pages isn't quite that interesting. In the next step you can create your first route. There are multiple ways to achieve this but for a single route you can start by simply providing a RequestHandler. It's a functional interface so you can simply provide a lambda that handles the request.

public class ExampleApp {

    public static void main(String[] args) {
        HTTPServer server = new HTTPServer().port(8080);

        server.get("/", exchange -> "Hello World!");

        server.start().join();
    }

}

After restarting the application and reloading the page in your browser you should see "Hello World!" instead of the 404 page. The first parameter ("exchange" in this example) holds all information about the incoming request aswell as allowing to set the response headers and status.

None by JavaWebStack Maintainers, 2024 - 2025. All Rights Reserved. Built with Typemill.