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

Jetty 12.1.9静态资源服务报错:非法字符与目录不可读问题求助

Jetty 12.1.9 静态资源部署问题解决

问题原因分析

你的问题核心是Windows系统下file URI格式与Jetty资源解析逻辑不匹配:

  • 使用file:///C:/...时,Java NIO解析路径会把/C:/视为非法路径(冒号出现在路径起始位置),触发InvalidPathException。
  • 使用file://C:/...时,该URI不符合标准Windows file URI规范(缺少第三个斜杠),导致Jetty无法正确识别为可读目录。

可行解决方案

方案1:直接通过File对象创建Resource(推荐)

跳过手动构造URI的步骤,直接用本地文件路径创建File对象,再交由Jetty的ResourceFactory处理,避免URI格式错误:

public static void main(String[] args) throws Exception {
    int port = 80;
    var server = new Server();
    HttpConfiguration httpConf = new HttpConfiguration();
    HttpConnectionFactory httpFac = new HttpConnectionFactory(httpConf);
    ServerConnector connector = new ServerConnector(server, httpFac);
    connector.setPort(port);
    server.addConnector(connector);
    ContextHandlerCollection contextCollection = new ContextHandlerCollection();
    
    ResourceHandler handler = new ResourceHandler();
    // 直接使用File对象创建Resource
    File baseDir = new File("C:/some/path/to/html/");
    Resource baseResource = ResourceFactory.of(handler).newResource(baseDir);
    if (!Resources.isReadableDirectory(baseResource)) {
        throw new RuntimeException("Resource is not a readable directory");
    }

    handler.setBaseResource(baseResource);
    handler.setDirAllowed(true);
    handler.setWelcomeFiles(List.of("index.html"));
    // 调整ContextHandler创建方式,确保路径映射正确
    ContextHandler contextHandler = new ContextHandler("/file");
    contextHandler.setHandler(handler);
    contextCollection.addHandler(contextHandler);
        
    server.setHandler(contextCollection);

    server.start();
    server.join();
}

方案2:使用Paths生成标准URI

如果需要用URI方式,通过Java NIO的Paths类生成符合规范的file URI,避免手动构造错误:

// 替换原URI构造代码
URI baseDir = Paths.get("C:/some/path/to/html/").toUri();
Resource baseResource = ResourceFactory.of(handler).newResource(baseDir);

关键注意点

  • Windows系统的标准file URI格式应为file:///C:/path/to/dir/,但手动构造时容易因斜杠数量错误导致解析失败,推荐通过File或Paths自动生成URI。
  • Jetty 12中ContextHandler的构造方式需确保路径映射正确,建议显式设置路径后再关联Handler,避免构造参数顺序导致的隐式错误。

内容的提问来源于stack exchange,提问作者Aleksander Mendoza-Drosik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 02:23:10