将Jetty资源库设置为嵌入在同一jar文件中的静态文件 [英] Setting Jetty resourcebase to static file embedded in the same jar file
问题描述
我正在尝试访问包装在同一.jar文件(testJetty.jar)中的静态资源(例如first.html),该文件也具有启动码头(v.8)服务器(MainTest.java)的类. .我无法正确设置资源库.
I am trying to access static resource (eg. first.html) packed inside the same .jar file (testJetty.jar), which also has a class which starts the jetty (v.8) server (MainTest.java). I am unable to set the resource base correctly.
我的jar文件(testJetty.jar)的结构: testJetty.jar
The structure of my jar file (testJetty.jar): testJetty.jar
-
first.html
first.html
MainTest.java
MainTest.java
== 在本地计算机上工作正常,但是当我将其包装在jar文件中然后运行时,它不起作用,并显示"404:找不到文件"错误.
== Works fine on local machine, but when I wrap it in jar file and then run it, it doesn't work, giving "404: File not found" error.
我尝试使用以下值设置资源库,所有这些都失败了:
I tried to set the resourcebase with the following values, all of which failed:
a)尝试将其设置为.
a) Tried setting it to .
resource_handler.setResourceBase("."); // Results in directory containing the jar file, D:\Work\eclipseworkspace\testJettyResult
b)尝试从getResource获取它
b) Tried getting it from 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)尝试获取Webdir
c) Tried getting the webdir
String webDir = this.getClass().getProtectionDomain()
.getCodeSource().getLocation().toExternalForm();
resource_handler.setResourceBase(webdir); // Results in D:/Work/eclipseworkspace/testJettyResult/testJetty1.jar
这3种方法均无效.
任何帮助或替代方案将不胜感激
Any help or alternative would be appreciated
谢谢 阿巴斯
推荐答案
Not unusually, I found a solution to my problem. The 3rd approach mentioned by Stephen in Embedded Jetty : how to use a .war that is included in the .jar from which Jetty starts? worked!
因此,我从Resource_handler更改为WebAppContext,其中WebAppContext指向相同的jar(testJetty.jar),并且可以正常工作!
So, I changed from Resource_handler to WebAppContext, where WebAppContext is pointing to the same jar (testJetty.jar) and it worked!
String webDir = MainTest.class.getProtectionDomain()
.getCodeSource().getLocation().toExternalForm(); ; // Results in D:/Work/eclipseworkspace/testJettyResult/testJetty.jar
WebAppContext webappContext = new WebAppContext(webDir, "/");
这篇关于将Jetty资源库设置为嵌入在同一jar文件中的静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!