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

Jetty 11.0.11 Fat Jar在Linux下访问静态资源报404

Jetty 11.0.11 Fat Jar静态资源404排查与解决

问题场景

  • 项目环境:NetBeans 14 + Jetty 11.0.11 + JDK 17
  • 静态资源位置:src/main/webapp/static/index.html
  • Windows本地运行:访问http://127.0.0.1:8086/index.html可正常获取资源
  • Linux(Ubuntu 20.04 LTS)运行Fat Jar:访问http://172.16.1.33/index.html返回HTTP 404

已排查信息

  • Windows环境资源路径:file:/D:/Projects/verdi_2/target/classes/static
  • Linux环境资源路径:jar:file:/usr/src/verdi/verdi-12-JDK17-jar-with-dependencies.jar!/static
  • 确认JAR包内/static目录及资源完整,运行无异常抛出
  • 低版本Jetty可正常处理该JAR内资源路径
  • 已提交相关官方问题反馈

解决方法

1. 修正Jetty资源加载逻辑

Jetty 11对JAR内资源的处理逻辑有调整,避免直接使用字符串路径加载,改用Resource.newResource(URI)方式保证跨环境兼容:

ResourceHandler resourceHandler = new ResourceHandler();
// 从类路径获取静态资源URI
URI staticUri = getClass().getResource("/static").toURI();
Resource staticResource = Resource.newResource(staticUri);
resourceHandler.setBaseResource(staticResource);
// 配置欢迎页与目录访问权限
resourceHandler.setWelcomeFiles(new String[]{"index.html"});
resourceHandler.setDirectoriesListed(true);

2. 调整打包配置确保资源纳入JAR

检查Maven/Gradle打包规则,确保src/main/webapp/static下的资源被正确打包进Fat Jar。以Maven为例,在pom.xml中补充资源配置:

<build>
  <resources>
    <resource>
      <directory>src/main/webapp</directory>
      <includes>
        <include>static/**</include>
      </includes>
    </resource>
  </resources>
</build>

3. 显式配置上下文资源路径

使用ServletContextHandler处理静态资源时,需明确设置资源基准路径为类路径资源的外部形式:

ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
// 绑定类路径下的static目录为资源根
context.setResourceBase(getClass().getResource("/static").toExternalForm());
// 注册默认Servlet处理静态资源请求
context.addServlet(DefaultServlet.class, "/");

4. 临时降级Jetty版本

若需快速恢复服务,可暂时降级到能正常处理JAR内资源的Jetty版本,等待官方问题修复后再升级。

内容的提问来源于stack exchange,提问作者Stefan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 11:39:25