Java Simple Webserver
Java 18 and higher include a simple web server that can be invoked from the command-line, as follows:
jwebserver -b 0.0.0.0 -p 8080
The simple HTTP server can also be started from the API:
import com.sun.net.httpserver.*;
var server = SimpleFileServer.createFileServer(
new InetSocketAddress(8080),
Path.of("/tmp/files"),
OutputLevel.VERBOSE
);
server.start();
The simple web server can be extended with filters and handlers. Handlers are used to provide different branches of handling for different types of requests. Filters are used to add pre-processors and post-processors to the processing pipeline:
var handler = SimpleFileServer.createFileHandler(Path.of("/tmp/files"));
var filter = SimpleFileServer.createOutputFilter(System.out, OutputLevel.INFO);
The handler and filter can be used with the HttpServer.create method like this:
var handler = SimpleFileServer.createFileHandler(Path.of("/Users/nitin.katkam/Documents/landd/javaProjects"));
var filter = SimpleFileServer.createOutputFilter(System.out, SimpleFileServer.OutputLevel.INFO);
var server = HttpServer.create(
new InetSocketAddress(8080),
0,
"/Users/nitin.katkam/Documents/landd/javaProjects",
handler,
filter
);
server.start();
TODO: I have yet to find a fix for the “404 Not FoundNo context found for request%” for the above code snippet.