我正在尝试访问打包在同一个 .jar 文件 (testJetty.jar) 中的静态资源(例如,first.html),该文件还有一个启动 jetty(v.8)服务器(MainTest.java)的类。我无法正确设置资源库。
我的 jar 文件(testJetty.jar)的结构:
测试Jetty.jar
==
在本地计算机上工作正常,但是当我将其包装在 jar 文件中然后运行它时,它不起作用,给出“404:找不到文件”错误。
我尝试使用以下值设置资源库,但全部失败:
a) 尝试将其设置为 。
resource_handler.setResourceBase("."); // Results in directory containing the jar file, D:\Work\eclipseworkspace\testJettyResult
b) 尝试从 getResource 获取它
ClassLoader loader = this.getClass().getClassLoader();
File indexLoc = new File(loader.getResource("first.html").getFile());
String htmlLoc = indexLoc.getAbsolutePath();
resource_handler.setResourceBase(htmloc); // Results in D:\Work\eclipseworkspace\testJettyResult\file:\D:\Work\eclipseworkspace\testJettyResult\testJetty1.jar!\first.html
c) 尝试获取网络目录
String webDir = this.getClass().getProtectionDomain()
.getCodeSource().getLocation().toExternalForm();
resource_handler.setResourceBase(webdir); // Results in D:/Work/eclipseworkspace/testJettyResult/testJetty1.jar
这 3 种方法都不起作用。
任何帮助或替代方案将不胜感激
谢谢
阿巴斯
该线程中提供的解决方案有效,但我认为对解决方案进行一些澄清可能会很有用。
如果您正在构建一个胖罐子并使用ProtectionDomain
这样你可能会遇到一些问题,因为你正在加载整个罐子!
class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
所以更好的解决方案是其他提供的解决方案
contextHandler.setResourceBase(
YourClass.class
.getClassLoader()
.getResource("WEB-INF")
.toExternalForm());
这里的问题是,如果您正在构建一个 fat jar,您并没有真正将 webapp 资源转储到 WEB-INF 中,而是可能进入 jar 的根目录,因此一个简单的解决方法是创建一个文件夹 XXX 并使用第二种方法:如下:
contextHandler.setResourceBase(
YourClass.class
.getClassLoader()
.getResource("XXX")
.toExternalForm());
或者更改构建工具以将 webapp 文件导出到给定目录中。也许 Maven 会在 Jar 上为您执行此操作,但 gradle 不会。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)