Search code examples
javahttpserverfileserver

Java SimpleFileServer disable directory listing


For a minimalistic SimpleFileServer pseudocode below, how to disable directory listing?

var server = HttpsServer.create(new InetSocketAddress(port), 2)
server.createContext("/file", SimpleFileServer.createFileHandler(Path.of("d:\file")));
server.start();

Solution

  • If you put an index file (index.html or index.htm) in the directory, then that will be served, rather than the directory contents.

    One more thing: you probably want a / at the end of the context path (so "/file/") as per the note in the API:

    The path should generally, but is not required to, end with '/'. If the path does not end with '/', eg such as with "/foo" then this would match requests with a path of "/foobar" or "/foo/bar".

    Alternatively:

    var server = HttpServer.create(new InetSocketAddress(8080), 2);
    var fileHandler = SimpleFileServer.createFileHandler(Path.of("d:\file"));
    server.createContext("/file/", (exchange) -> {
        if (exchange.getHttpContext().getPath().equals(exchange.getRequestURI().getPath())) {
            try (exchange) {
                exchange.setAttribute("request-path", "could not resolve request URI path");
                exchange.sendResponseHeaders(404, 0);
            }
        } else {
            fileHandler.handle(exchange);
        }
    });
    server.start();