A Simple HTTP Server in Java: jwebserver, HttpServer, Handlers and Filters
Serve HTTP with the JDK alone: the jwebserver tool, HttpServer contexts and HttpExchange handlers, sending responses correctly, executors and virtual threads, filters, HttpHandlers and SimpleFileServer (Java 18), basic authentication and HttpsServer.
kvi5hnuCode Sprout team member9 min readOn this page
The earlier networking demos already used a server from the JDK. The jdk.httpserver module contains a small HTTP/1.1 server in the package com.sun.net.httpserver, which has been there since Java 6. Despite the com.sun name, it is a supported, exported API. It is not a replacement for a production web server or framework. It is ideal for tests, prototypes, tools, mock back ends and serving files during development. Since Java 18 (JEP 408), the JDK also includes a ready-made static file server, jwebserver.
jwebserver: a file server in one command
$ jwebserver
Binding to loopback by default. For all interfaces use "-b 0.0.0.0" or "-b ::".
Serving /home/ada/site and subdirectories on 127.0.0.1 port 8000
URL http://127.0.0.1:8000/
It serves the current directory, read-only, on port 8000 of the loopback address. The options are -p (port), -d (directory, must be absolute), -b (bind address) and -o none|info|verbose (how much to log). java -m jdk.httpserver does the same thing.
It is deliberately minimal. It serves only GET and HEAD, picks MIME types from file extensions, lists directories, serves index.html for a directory, and has no HTTPS, authentication or HTTP/2. It's handy for viewing generated documentation, testing a page that needs to be served over HTTP, or giving a client test something to fetch.
HttpServer
Programmatic servers start from HttpServer:
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); // 0 = default backlog
server.createContext("/hello", exchange -> { ... });
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.start();
...
server.stop(2); // wait up to 2 seconds for exchanges in progress
Port 0 picks a free port, which server.getAddress().getPort() then reports, so tests can't collide. stop(seconds) closes the listener and waits for active exchanges up to the given delay.
By default, all requests are handled on a single thread, the one that also accepts connections, so one slow handler blocks everyone. Always set an executor. A virtual thread per task (Java 21) is the natural choice, and handlers can then simply block.
Contexts
A context maps a path prefix to a handler. A request goes to the context with the longest matching prefix, so /notes also receives /notes/42 and /notes?x=1. A request that matches no context gets a 404. Each HttpContext can carry filters, an authenticator and attributes, and removeContext takes one away again.
Handlers and HttpExchange
An HttpHandler has one method, handle(HttpExchange exchange). The exchange gives you the request and lets you build the response:
| Request side | Response side |
|---|---|
getRequestMethod(), getRequestURI() | getResponseHeaders() (a mutable Headers) |
getRequestHeaders() | sendResponseHeaders(status, length) |
getRequestBody() (an InputStream) | getResponseBody() (an OutputStream) |
getRemoteAddress(), getPrincipal() | close() |
The order matters, and so does the length argument:
- Read the request body if there is one.
- Set response headers.
- Call
sendResponseHeaders(status, length). A positive length means exactly that many bytes follow.0means an unknown length, so the response is sent with chunked encoding.-1means no body at all. Use-1for 204, 304 and 405 responses and for HEAD requests. - Write the body and
close()the exchange. Not closing it leaks the connection. BecauseHttpExchangeisAutoCloseable,try (exchange) { ... }is the safe form.
Headers is a case-insensitive map of header names to lists of values, with add, set and getFirst. Java 18 added Headers.of(...), which creates an immutable Headers.
Filters
A Filter wraps the handlers of a context, like a servlet filter. doFilter(exchange, chain) can run code before and after chain.doFilter(exchange), or skip the chain to answer on its own. That is the place for logging, authentication, CORS headers and compression. Add filters with context.getFilters().add(filter). They run in the order of the list.
Java 18 added factory methods for the common cases:
Filter.beforeHandler(description, exchange -> ...)runs a step before the handler.Filter.afterHandler(description, exchange -> ...)runs a step after it, when the status is known.Filter.adaptRequest(description, request -> request.with(...))replaces the request the handler sees, for example to add a default header.Requestis a read-only view of the method, URI and headers, andwith(name, values)returns a copy with one more header (if the header isn't already present).
HttpHandlers and SimpleFileServer
Java 18 also added building blocks so you don't have to write every handler:
HttpHandlers.of(status, headers, body)always returns the same canned response, which is perfect for test stubs.HttpHandlers.handleOrElse(predicate, handler, fallback)routes by aPredicate<Request>, for example by method.SimpleFileServer.createFileHandler(path)is the file handler behindjwebserver. It serves files and listings, answers 404 for missing files and 405 for methods other than GET and HEAD.SimpleFileServer.createFileServer(address, path, outputLevel)creates a completeHttpServerwith that handler.SimpleFileServer.createOutputFilter(stream, outputLevel)creates the request-logging filterjwebserveruses.
Authentication and HTTPS
A context can have an Authenticator. The built-in BasicAuthenticator implements HTTP Basic: override checkCredentials(user, password). Unauthenticated requests get a 401 with a WWW-Authenticate header, and handlers can call exchange.getPrincipal() to see who logged in. Basic authentication sends the password encoded, not encrypted, so use it only over HTTPS or on loopback.
For HTTPS, create an HttpsServer and call setHttpsConfigurator(new HttpsConfigurator(sslContext)) with an SSLContext built from a keystore, as in article 50. Everything else stays the same.
The program
The demo builds one server with five contexts. /notes is a hand-written handler: POST adds a note and answers 201 with a Location, GET lists the notes, and other methods get 405 with an Allow header. A logging filter on that context records each request before and after handling. /ping combines HttpHandlers.of and handleOrElse, and /files is a SimpleFileServer file handler over a temporary directory, with an afterHandler filter that logs status codes. /hello uses adaptRequest to supply a default header, and /admin is protected by BasicAuthenticator. An HttpClient exercises each context, and an unknown path shows the 404 for unmatched contexts. The temporary directory is deleted at the end.
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.net.http.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class Solution {
static final Map<String, String> notes = new ConcurrentSkipListMap<>();
// A small REST-style handler: GET lists notes, POST adds one, other methods get 405
static void notesHandler(HttpExchange ex) throws IOException {
try (ex) {
switch (ex.getRequestMethod()) {
case "GET" -> {
String body = String.join("\n", notes.entrySet().stream().map(e -> e.getKey() + ": " + e.getValue()).toList());
send(ex, 200, "text/plain; charset=utf-8", body);
}
case "POST" -> {
String text = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8);
String id = "n" + (notes.size() + 1);
notes.put(id, text);
ex.getResponseHeaders().set("Location", "/notes/" + id);
send(ex, 201, "text/plain; charset=utf-8", "created " + id);
}
default -> {
ex.getResponseHeaders().set("Allow", "GET, POST");
ex.sendResponseHeaders(405, -1); // -1: no body
}
}
}
}
static void send(HttpExchange ex, int status, String type, String body) throws IOException {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().set("Content-Type", type);
ex.sendResponseHeaders(status, bytes.length == 0 ? -1 : bytes.length);
ex.getResponseBody().write(bytes);
}
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("site");
Files.writeString(root.resolve("index.html"), "<h1>Hello from a file</h1>\n");
Files.createDirectory(root.resolve("docs"));
Files.writeString(root.resolve("docs/readme.txt"), "plain text\n");
var log = new ConcurrentLinkedQueue<String>();
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
// 1. a handler written by hand
HttpContext notesContext = server.createContext("/notes", Solution::notesHandler);
notesContext.getFilters().add(new Filter() { // a filter that logs and times
@Override public void doFilter(HttpExchange ex, Chain chain) throws IOException {
log.add("before " + ex.getRequestMethod() + " " + ex.getRequestURI());
chain.doFilter(ex);
log.add("after status " + ex.getResponseCode());
}
@Override public String description() { return "logging filter"; }
});
// 2. canned responses and routing by predicate (Java 18)
HttpHandler teapot = HttpHandlers.of(418, Headers.of("Content-Type", "text/plain"), "I'm a teapot");
HttpHandler ok = HttpHandlers.of(200, Headers.of("Content-Type", "text/plain"), "pong");
Predicate<Request> isGet = r -> r.getRequestMethod().equals("GET");
server.createContext("/ping", HttpHandlers.handleOrElse(isGet, ok, teapot));
// 3. a static file server (Java 18) with a filter that adapts the request
HttpHandler files = SimpleFileServer.createFileHandler(root);
HttpContext filesContext = server.createContext("/files", files);
filesContext.getFilters().add(Filter.afterHandler("count",
ex -> log.add("file request " + ex.getRequestURI().getPath() + " -> " + ex.getResponseCode())));
// 4. a filter that adapts the request before the handler sees it (Java 18)
HttpContext hello = server.createContext("/hello", ex -> {
try (ex) { send(ex, 200, "text/plain", "hello, " + ex.getRequestHeaders().getFirst("X-User")); }
});
hello.getFilters().add(Filter.adaptRequest("default user",
r -> r.getRequestHeaders().containsKey("X-User") ? r : r.with("X-User", List.of("guest"))));
// 5. basic authentication on one context
HttpContext admin = server.createContext("/admin", ex -> {
try (ex) { send(ex, 200, "text/plain", "welcome, " + ex.getPrincipal().getUsername()); }
});
admin.setAuthenticator(new BasicAuthenticator("admin area") {
@Override public boolean checkCredentials(String user, String password) {
return user.equals("ada") && password.equals("secret");
}
});
server.start();
URI base = URI.create("http://127.0.0.1:" + server.getAddress().getPort());
try (HttpClient client = HttpClient.newHttpClient()) {
System.out.println("--- hand-written handler with a filter ---");
for (String text : List.of("buy milk", "call Bob"))
show(client, HttpRequest.newBuilder(base.resolve("/notes")).POST(HttpRequest.BodyPublishers.ofString(text)).build());
show(client, HttpRequest.newBuilder(base.resolve("/notes")).build());
show(client, HttpRequest.newBuilder(base.resolve("/notes")).DELETE().build());
log.forEach(System.out::println);
log.clear();
System.out.println("--- HttpHandlers.of and handleOrElse ---");
show(client, HttpRequest.newBuilder(base.resolve("/ping")).build());
show(client, HttpRequest.newBuilder(base.resolve("/ping")).POST(HttpRequest.BodyPublishers.noBody()).build());
System.out.println("--- contexts match by path prefix ---");
show(client, HttpRequest.newBuilder(base.resolve("/nowhere")).build());
System.out.println("--- SimpleFileServer ---");
show(client, HttpRequest.newBuilder(base.resolve("/files/")).build());
show(client, HttpRequest.newBuilder(base.resolve("/files/docs/readme.txt")).build());
HttpResponse<String> listing = client.send(HttpRequest.newBuilder(base.resolve("/files/docs/")).build(), BodyHandlers.ofString());
System.out.println("directory listing mentions readme.txt: " + listing.body().contains("readme.txt"));
show(client, HttpRequest.newBuilder(base.resolve("/files/missing.txt")).build());
show(client, HttpRequest.newBuilder(base.resolve("/files/index.html")).DELETE().build());
log.forEach(System.out::println);
System.out.println("--- Filter.adaptRequest ---");
show(client, HttpRequest.newBuilder(base.resolve("/hello")).build());
show(client, HttpRequest.newBuilder(base.resolve("/hello")).header("X-User", "Grace").build());
System.out.println("--- BasicAuthenticator ---");
show(client, HttpRequest.newBuilder(base.resolve("/admin")).build());
String credentials = Base64.getEncoder().encodeToString("ada:secret".getBytes(StandardCharsets.UTF_8));
show(client, HttpRequest.newBuilder(base.resolve("/admin")).header("Authorization", "Basic " + credentials).build());
} finally {
server.stop(0);
try (Stream<Path> paths = Files.walk(root)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) Files.delete(p);
}
}
}
static void show(HttpClient client, HttpRequest request) throws IOException, InterruptedException {
HttpResponse<String> r = client.send(request, BodyHandlers.ofString());
String type = r.headers().firstValue("Content-Type").orElse("-");
String body = r.body().strip().replace("\n", " | ");
if (body.length() > 50) body = body.substring(0, 50) + "...";
String extra = r.headers().firstValue("WWW-Authenticate").map(v -> " [" + v + "]").orElse("")
+ r.headers().firstValue("Allow").map(v -> " [Allow: " + v + "]").orElse("");
System.out.printf("%-6s %-24s %d %s%s %s%n", request.method(), request.uri().getPath(), r.statusCode(), type, extra, body);
}
}
--- hand-written handler with a filter ---
POST /notes 201 text/plain; charset=utf-8 created n1
POST /notes 201 text/plain; charset=utf-8 created n2
GET /notes 200 text/plain; charset=utf-8 n1: buy milk | n2: call Bob
DELETE /notes 405 - [Allow: GET, POST]
before POST /notes
after status 201
before POST /notes
after status 201
before GET /notes
after status 200
before DELETE /notes
after status 405
--- HttpHandlers.of and handleOrElse ---
GET /ping 200 text/plain pong
POST /ping 418 text/plain I'm a teapot
--- contexts match by path prefix ---
GET /nowhere 404 text/html <h1>404 Not Found</h1>No context found for request
--- SimpleFileServer ---
GET /files/ 200 text/html <h1>Hello from a file</h1>
GET /files/docs/readme.txt 200 text/plain plain text
directory listing mentions readme.txt: true
GET /files/missing.txt 404 text/html; charset=UTF-8 <!DOCTYPE html> | <html> | <head> | <meta charset=...
DELETE /files/index.html 405 - [Allow: HEAD, GET]
file request /files/ -> 200
file request /files/docs/readme.txt -> 200
file request /files/docs/ -> 200
file request /files/missing.txt -> 404
file request /files/index.html -> 405
--- Filter.adaptRequest ---
GET /hello 200 text/plain hello, guest
GET /hello 200 text/plain hello, Grace
--- BasicAuthenticator ---
GET /admin 401 - [Basic realm="admin area", charset="UTF-8"]
GET /admin 200 text/plain welcome, ada
Common questions
Can I use HttpServer in production?
For small internal tools, health endpoints, or embedded admin pages, it's acceptable, especially with a virtual-thread executor. For public services, use a full server or framework (Jetty, Tomcat, Undertow, Netty, Helidon, Spring Boot), which handle HTTP/2, robust parsing, limits, TLS configuration, observability and security updates.
How do I read query parameters?
exchange.getRequestURI().getRawQuery() gives the raw string; split on & and =, and decode names and values with URLDecoder.decode(s, StandardCharsets.UTF_8). There's no built-in parameter parser.
How do I serve JSON?
Set Content-Type: application/json; charset=utf-8, convert the text to UTF-8 bytes, and send the byte length (not the string length) to sendResponseHeaders. A mismatch between the declared length and the bytes written causes truncated responses or an IOException.
Can jwebserver serve on another port or for other machines?
Yes: jwebserver -p 9000 -b 0.0.0.0. Binding to all interfaces makes the files visible to the whole network, as the tool warns on startup.
Why does my handler's exception not show anywhere?
The server logs it at TRACE through the com.sun.net.httpserver System.Logger, which is off by default. Wrap the handler body in try/catch, log it yourself, and send a 500.
How do I stop the server in a test?
Call server.stop(0) in a finally block or test teardown, and shut down the executor you supplied. Using port 0 avoids conflicts between tests that run in parallel.
API reference
| API | Purpose |
|---|---|
jwebserver [-b addr] [-p port] [-d dir] [-o level] | static file server tool (Java 18) |
HttpServer.create(address, backlog), start(), stop(delay) | create, run and stop a server |
setExecutor(executor) | threads that run handlers |
createContext(path, handler), removeContext | map path prefixes to handlers |
HttpHandler.handle(HttpExchange) | handle a request |
HttpExchange.getRequestMethod, getRequestURI, getRequestHeaders, getRequestBody | read the request |
getResponseHeaders, sendResponseHeaders(status, length), getResponseBody, close | send the response |
Headers.add, set, getFirst, Headers.of (Java 18) | header maps |
Filter.doFilter(exchange, chain), beforeHandler, afterHandler, adaptRequest (Java 18) | filters |
HttpHandlers.of, handleOrElse (Java 18) | ready-made handlers |
SimpleFileServer.createFileHandler, createFileServer, createOutputFilter (Java 18) | serve files |
BasicAuthenticator.checkCredentials, HttpContext.setAuthenticator, HttpExchange.getPrincipal | Basic authentication |
HttpsServer, HttpsConfigurator | HTTPS |
Summary
jwebserver(Java 18) serves a directory over HTTP on loopback with one command. It's for development and testing only.HttpServermaps path prefixes to handlers through contexts. Always give it an executor, ideally virtual threads.- In a handler, read the request, set headers, call
sendResponseHeaderswith the right length (-1for no body), write the body and close the exchange, preferably with try-with-resources. - Filters add behavior around handlers.
beforeHandler,afterHandlerandadaptRequestcover the common cases. HttpHandlersandSimpleFileServerprovide canned responses, routing and file serving.BasicAuthenticatorandHttpsServeradd authentication and TLS.
Practice Questions
Your HttpServer handles requests one at a time, and one slow request delays all others. What's missing?
An executor. Without setExecutor, the server runs every handler on its single dispatcher thread. Call server.setExecutor(Executors.newVirtualThreadPerTaskExecutor()) before start() so each exchange runs on its own virtual thread.
What do the length values 0, -1 and 42 mean in sendResponseHeaders(200, length)?
42 promises exactly 42 bytes of body, sent with a Content-Length header. 0 means the length is unknown, so the body is sent in chunks until you close the stream. -1 means there is no body at all, which is right for HEAD requests and statuses like 204 or 405.
Both /api and /api/users are registered as contexts. Which handler receives /api/users/7, and which receives /apis?
/api/users/7 goes to /api/users, the longest matching prefix. /apis also starts with /api as a string, so it goes to the /api context. Matching is by string prefix, not path segment. Check getRequestURI().getPath() in the handler if that distinction matters.
How would you add a CORS header to every response from one context without changing its handler?
Add a filter to the context: context.getFilters().add(Filter.beforeHandler("cors", ex -> ex.getResponseHeaders().set("Access-Control-Allow-Origin", "*"))). A before-handler step runs before the handler sends its headers, so the header is included.
A colleague wants to share a folder with the whole office using jwebserver. What should they be aware of?
They must bind to a non-loopback address (-b 0.0.0.0), and then everyone who can reach the port can read every file in that folder and its subfolders. There's no authentication or HTTPS. It's meant for development, so a proper file share or web server is a better choice for this.
Previous: Asynchronous HTTP and WebSocket in Java: sendAsync, HTTP/2 and WebSocket
Related reading
- Asynchronous HTTP and WebSocket in Java: sendAsync, HTTP/2 and WebSocket
- The Java HttpClient: Requests, Responses, Body Publishers and Handlers
- Posting Form Data in Java: GET and POST, URL Encoding and Multipart
- URIs, URLs and URLConnection in Java: Retrieving Web Data and Headers
- Interruptible Sockets and TLS in Java: SocketChannel, Virtual Threads and SSLSocket

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.