Class SimpleFileServer

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

public final class SimpleFileServer extends Object
A simple HTTP file server and its components (intended for testing, development and debugging purposes only).

A simple file server is composed of three components:

  • an HttpServer that is bound to a given address,
  • an HttpHandler that serves files from a given directory path, and
  • an optional Filter that prints log messages relating to the exchanges handled by the server.
The individual server components can be retrieved for reuse and extension via the static methods provided.

Simple file server

The createFileServer static factory method returns an HttpServer that is a simple out-of-the-box file server. The server comes with an initial handler that serves files from a given directory path (and its subdirectories). The output level determines what log messages are printed to System.out, if any.

Example of a simple file server:


    var addr = new InetSocketAddress(8080);
    var server = SimpleFileServer.createFileServer(addr, Path.of("/some/path"), OutputLevel.INFO);
    server.start();
 

File handler

The createFileHandler static factory method returns an HttpHandler that serves files and directory listings. The handler supports only the HEAD and GET request methods; to handle other request methods, one can either add additional handlers to the server, or complement the file handler by composing a single handler via HttpHandlers.handleOrElse(Predicate, HttpHandler, HttpHandler).

Example of composing a single handler:


    var handler = HttpHandlers.handleOrElse(
        (req) -> req.getRequestMethod().equals("PUT"),
        (exchange) -> {
            // validate and handle PUT request
        },
        SimpleFileServer.createFileHandler(Path.of("/some/path")))
    );
 

Output filter

The createOutputFilter static factory method returns a post-processing filter that prints log messages relating to the exchanges handled by the server. The output format is specified by the outputLevel.

Example of an output filter:


    var filter = SimpleFileServer.createOutputFilter(System.out, OutputLevel.VERBOSE);
    var server = HttpServer.create(new InetSocketAddress(8080), 10, "/some/path/", new SomeHandler(), filter);
    server.start();
 

jwebserver Tool

A simple HTTP file server implementation is provided via the jwebserver tool.

Tool Guides:
jwebserver
Since:
18