Do you want to start a basic HTTP server to serve the files in a directory on your machine using Java? If so, here’s how.
Available since Java 18#
A simple web server is available since Java 18. Install your favorite distribution of JDK 18 or later. If you don’t have a favorite one, I recommend Eclipse Temurin (18 will be available shortly after this blog post publishing date). I also recommend using SDKMAN! if you are on Linux-like operating systems. It just makes it much easier to manage multiple versions of JDK on the same machine. For example, to try Java 18 on the same day the reference implementation was released, I just run the following:
$ sdk install java 18-open
You can install other distributions as well. See the available options running:
$ sdk list java
Check that the correct version of the JDK is installed and in use:
$ java --version
You should see something like the following:
openjdk 18 2022-03-22
OpenJDK Runtime Environment (build 18+36-2087)
OpenJDK 64-Bit Server VM (build 18+36-2087, mixed mode, sharing)
Creating an example HTML file#
Create a new directory to host the files you want to serve. Here’s how to do so using Linux/macOS:
$ mkdir web-content
Inside this directory, create a new index.html file with the following content:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Java's HTTP server</title>
  </head>
  <body>
    <h1>Hi! 👋</h1>
    <p>
      This content was served by Java's simple
      HTTP server.
    </p>
  </body>
</html>
Tip: if you are on macOS, you can copy the previous snippet of code and create the file with the copied text using the following command:Â pbpaste > index.html
.
Starting the server#
Start the HTTP web server:
$ jwebserver
Point your browser to http://localhost:8000 and see the HTML file rendered:
By default, the server serves the files in the current directory using port 8000. You can override the defaults as follows:
$ jwebserver -d /path/to/some/directory/ -p 9999
This will serve the files in /path/to/some/directory/ at http://localhost:9999. Make sure to use an absolute path, otherwise, you’ll get an error.
Alternatively, you can run the server using the java
command:
$ java -m jdk.httpserver
To stop the server, press CTRL+CÂ in the terminal.
Limitations#
At the time of writing this, Java’s simple HTTP web server has some limitations:
- HTTPS is not supported
- HTTP2 is not supported (only HTTP 1.1)
- Only the GET and HEAD HTTP request methods are supported
See JEP 408: Simple Web Server for more information.
Enjoyed this post? I can help your team implement similar solutions—contact me to learn more.