You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁用Java SimpleFileServer的目录列表功能

如何禁用Java SimpleFileServer的目录列表功能

嘿,我来帮你搞定这个问题!Java自带的SimpleFileServer默认会自动展示目录下的文件列表,要禁用这个功能,我们没法直接用SimpleFileServer.createFileHandler()的默认实现——得自己包装一个处理器,拦截目录请求,不让它生成列表页面。

具体思路是:创建一个自定义的HttpHandler,先判断请求的路径是不是目录,如果是,就直接返回404(或者你想要的其他错误响应);如果是文件请求,再交给默认的文件处理器去处理。

下面是完整的代码示例:

首先定义自定义的处理器类:

import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.nio.file.Path;
import java.nio.file.Files;
import java.io.IOException;

class NoListFileHandler implements HttpHandler {
    private final HttpHandler defaultFileHandler;
    private final Path rootPath;

    public NoListFileHandler(Path rootPath) {
        this.rootPath = rootPath;
        this.defaultFileHandler = SimpleFileServer.createFileHandler(rootPath);
    }

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        // 提取请求路径,去掉上下文前缀"/file"
        String requestPath = exchange.getRequestURI().getPath();
        Path targetPath = rootPath.resolve(requestPath.substring("/file".length())).normalize();

        // 检查目标路径是否是目录
        if (Files.isDirectory(targetPath)) {
            // 返回404 Not Found,也可以改成403 Forbidden禁止访问
            exchange.sendResponseHeaders(404, -1);
            exchange.close();
            return;
        }

        // 如果是文件请求,交给默认处理器处理
        defaultFileHandler.handle(exchange);
    }
}

然后替换原来的处理器配置:

var server = HttpsServer.create(new InetSocketAddress(port), 2);
// 用自定义的NoListFileHandler替代默认的FileHandler
server.createContext("/file", new NoListFileHandler(Path.of("d:\\file")));
server.start();

这里有几个小细节要注意:

  • 我用了normalize()来处理路径,避免恶意的路径遍历攻击(比如../这种跳转),确保只能访问指定根目录下的内容
  • 你可以根据需求修改响应码:比如返回403表示禁止访问目录,或者返回一个自定义的错误页面(需要把响应内容写入exchange的输出流)
  • 如果你的上下文路径不是/file,记得修改substring()里的参数,匹配你的实际上下文前缀

备注:内容来源于stack exchange,提问作者Tugalsan Karabacak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 13:23:05